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 "remoting/base/rsa_key_pair.h"
11 #include "base/base64.h"
12 #include "base/logging.h"
13 #include "base/rand_util.h"
14 #include "base/time.h"
15 #include "crypto/rsa_private_key.h"
16 #include "crypto/signature_creator.h"
17 #include "net/cert/x509_certificate.h"
21 RsaKeyPair::RsaKeyPair(scoped_ptr
<crypto::RSAPrivateKey
> key
)
26 RsaKeyPair::~RsaKeyPair() {}
29 scoped_refptr
<RsaKeyPair
> RsaKeyPair::Generate() {
30 scoped_ptr
<crypto::RSAPrivateKey
> key(crypto::RSAPrivateKey::Create(2048));
32 LOG(ERROR
) << "Cannot generate private key.";
35 return new RsaKeyPair(key
.Pass());
39 scoped_refptr
<RsaKeyPair
> RsaKeyPair::FromString(
40 const std::string
& key_base64
) {
42 if (!base::Base64Decode(key_base64
, &key_str
)) {
43 LOG(ERROR
) << "Failed to decode private key.";
47 std::vector
<uint8
> key_buf(key_str
.begin(), key_str
.end());
48 scoped_ptr
<crypto::RSAPrivateKey
> key(
49 crypto::RSAPrivateKey::CreateFromPrivateKeyInfo(key_buf
));
51 LOG(ERROR
) << "Invalid private key.";
55 return new RsaKeyPair(key
.Pass());
58 std::string
RsaKeyPair::ToString() const {
59 // Check that the key initialized.
60 DCHECK(key_
.get() != NULL
);
62 std::vector
<uint8
> key_buf
;
63 CHECK(key_
->ExportPrivateKey(&key_buf
));
64 std::string
key_str(key_buf
.begin(), key_buf
.end());
65 std::string key_base64
;
66 if (!base::Base64Encode(key_str
, &key_base64
)) {
67 LOG(FATAL
) << "Base64Encode failed";
72 std::string
RsaKeyPair::GetPublicKey() const {
73 std::vector
<uint8
> public_key
;
74 CHECK(key_
->ExportPublicKey(&public_key
));
75 std::string
public_key_str(public_key
.begin(), public_key
.end());
76 std::string public_key_base64
;
77 base::Base64Encode(public_key_str
, &public_key_base64
);
78 return public_key_base64
;
81 std::string
RsaKeyPair::SignMessage(const std::string
& message
) const {
82 scoped_ptr
<crypto::SignatureCreator
> signature_creator(
83 crypto::SignatureCreator::Create(key_
.get()));
84 signature_creator
->Update(reinterpret_cast<const uint8
*>(message
.c_str()),
86 std::vector
<uint8
> signature_buf
;
87 signature_creator
->Final(&signature_buf
);
88 std::string
signature_str(signature_buf
.begin(), signature_buf
.end());
89 std::string signature_base64
;
90 base::Base64Encode(signature_str
, &signature_base64
);
91 return signature_base64
;
94 std::string
RsaKeyPair::GenerateCertificate() const {
95 scoped_refptr
<net::X509Certificate
> cert
=
96 net::X509Certificate::CreateSelfSigned(
97 key_
.get(), "CN=chromoting",
98 base::RandInt(1, std::numeric_limits
<int>::max()),
99 base::TimeDelta::FromDays(1));
101 return std::string();
104 bool result
= net::X509Certificate::GetDEREncoded(cert
->os_cert_handle(),
110 } // namespace remoting