Revert "Fix broken channel icon in chrome://help on CrOS" and try again
[chromium-blink-merge.git] / net / cert / x509_util.cc
blobbbdc194a9aaee7baa1df04641a1e28b8793a3cd0
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/cert/x509_util.h"
7 #include "base/memory/scoped_ptr.h"
8 #include "base/time/time.h"
9 #include "crypto/ec_private_key.h"
10 #include "crypto/rsa_private_key.h"
11 #include "net/cert/x509_certificate.h"
13 namespace net {
15 namespace x509_util {
17 // RSA keys created by CreateKeyAndSelfSignedCert will be of this length.
18 static const uint16_t kRSAKeyLength = 1024;
20 // Certificates made by CreateKeyAndSelfSignedCert and
21 // CreateKeyAndChannelIDEC will be signed using this digest algorithm.
22 static const DigestAlgorithm kSignatureDigestAlgorithm = DIGEST_SHA256;
24 ClientCertSorter::ClientCertSorter() : now_(base::Time::Now()) {}
26 bool ClientCertSorter::operator()(
27 const scoped_refptr<X509Certificate>& a,
28 const scoped_refptr<X509Certificate>& b) const {
29 // Certificates that are null are sorted last.
30 if (!a.get() || !b.get())
31 return a.get() && !b.get();
33 // Certificates that are expired/not-yet-valid are sorted last.
34 bool a_is_valid = now_ >= a->valid_start() && now_ <= a->valid_expiry();
35 bool b_is_valid = now_ >= b->valid_start() && now_ <= b->valid_expiry();
36 if (a_is_valid != b_is_valid)
37 return a_is_valid && !b_is_valid;
39 // Certificates with longer expirations appear as higher priority (less
40 // than) certificates with shorter expirations.
41 if (a->valid_expiry() != b->valid_expiry())
42 return a->valid_expiry() > b->valid_expiry();
44 // If the expiration dates are equivalent, certificates that were issued
45 // more recently should be prioritized over older certificates.
46 if (a->valid_start() != b->valid_start())
47 return a->valid_start() > b->valid_start();
49 // Otherwise, prefer client certificates with shorter chains.
50 const X509Certificate::OSCertHandles& a_intermediates =
51 a->GetIntermediateCertificates();
52 const X509Certificate::OSCertHandles& b_intermediates =
53 b->GetIntermediateCertificates();
54 return a_intermediates.size() < b_intermediates.size();
57 bool CreateKeyAndSelfSignedCert(const std::string& subject,
58 uint32_t serial_number,
59 base::Time not_valid_before,
60 base::Time not_valid_after,
61 scoped_ptr<crypto::RSAPrivateKey>* key,
62 std::string* der_cert) {
63 scoped_ptr<crypto::RSAPrivateKey> new_key(
64 crypto::RSAPrivateKey::Create(kRSAKeyLength));
65 if (!new_key.get())
66 return false;
68 bool success = CreateSelfSignedCert(new_key.get(),
69 kSignatureDigestAlgorithm,
70 subject,
71 serial_number,
72 not_valid_before,
73 not_valid_after,
74 der_cert);
75 if (success)
76 key->reset(new_key.release());
78 return success;
81 } // namespace x509_util
83 } // namespace net