1 // Copyright 2013 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. 4 5 #include "google_apis/cup/client_update_protocol.h" 6 7 #include <keyhi.h> 8 #include <pk11pub.h> 9 #include <seccomon.h> 10 11 #include "base/logging.h" 12 #include "crypto/nss_util.h" 13 #include "crypto/scoped_nss_types.h" 14 15 typedef scoped_ptr_malloc< 16 CERTSubjectPublicKeyInfo, 17 crypto::NSSDestroyer<CERTSubjectPublicKeyInfo, 18 SECKEY_DestroySubjectPublicKeyInfo> > 19 ScopedCERTSubjectPublicKeyInfo; 20 21 ClientUpdateProtocol::~ClientUpdateProtocol() { 22 if (public_key_) 23 SECKEY_DestroyPublicKey(public_key_); 24 } 25 26 bool ClientUpdateProtocol::LoadPublicKey(const base::StringPiece& public_key) { 27 crypto::EnsureNSSInit(); 28 29 // The binary blob |public_key| is expected to be a DER-encoded ASN.1 30 // Subject Public Key Info. 31 SECItem spki_item; 32 spki_item.type = siBuffer; 33 spki_item.data = 34 reinterpret_cast<unsigned char*>(const_cast<char*>(public_key.data())); 35 spki_item.len = static_cast<unsigned int>(public_key.size()); 36 37 ScopedCERTSubjectPublicKeyInfo spki( 38 SECKEY_DecodeDERSubjectPublicKeyInfo(&spki_item)); 39 if (!spki.get()) 40 return false; 41 42 public_key_ = SECKEY_ExtractPublicKey(spki.get()); 43 if (!public_key_) 44 return false; 45 46 if (!PublicKeyLength()) 47 return false; 48 49 return true; 50 } 51 52 size_t ClientUpdateProtocol::PublicKeyLength() { 53 if (!public_key_) 54 return 0; 55 56 return SECKEY_PublicKeyStrength(public_key_); 57 } 58 59 bool ClientUpdateProtocol::EncryptKeySource( 60 const std::vector<uint8>& key_source) { 61 // WARNING: This call bypasses the usual PKCS #1 padding and does direct RSA 62 // exponentiation. This is not secure without taking measures to ensure that 63 // the contents of r are suitable. This is done to remain compatible with 64 // the implementation on the Google Update servers; don't copy-paste this 65 // code arbitrarily and expect it to work and/or remain secure! 66 if (!public_key_) 67 return false; 68 69 size_t keysize = SECKEY_PublicKeyStrength(public_key_); 70 if (key_source.size() != keysize) 71 return false; 72 73 encrypted_key_source_.resize(keysize); 74 return SECSuccess == PK11_PubEncryptRaw( 75 public_key_, 76 &encrypted_key_source_[0], 77 const_cast<unsigned char*>(&key_source[0]), 78 key_source.size(), 79 NULL); 80 } 81 82