1 // Copyright (c) 2010 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 "net/base/x509_openssl_util.h" 6 7 #include <algorithm> 8 9 #include "base/logging.h" 10 #include "base/string_piece.h" 11 #include "net/base/x509_cert_types.h" 12 13 namespace net { 14 15 namespace x509_openssl_util { 16 17 bool ParsePrincipalKeyAndValueByIndex(X509_NAME* name, 18 int index, 19 std::string* key, 20 std::string* value) { 21 X509_NAME_ENTRY* entry = X509_NAME_get_entry(name, index); 22 if (!entry) 23 return false; 24 25 if (key) { 26 ASN1_OBJECT* object = X509_NAME_ENTRY_get_object(entry); 27 key->assign(OBJ_nid2sn(OBJ_obj2nid(object))); 28 } 29 30 ASN1_STRING* data = X509_NAME_ENTRY_get_data(entry); 31 if (!data) 32 return false; 33 34 unsigned char* buf = NULL; 35 int len = ASN1_STRING_to_UTF8(&buf, data); 36 if (len <= 0) 37 return false; 38 39 value->assign(reinterpret_cast<const char*>(buf), len); 40 OPENSSL_free(buf); 41 return true; 42 } 43 44 bool ParsePrincipalValueByIndex(X509_NAME* name, 45 int index, 46 std::string* value) { 47 return ParsePrincipalKeyAndValueByIndex(name, index, NULL, value); 48 } 49 50 bool ParsePrincipalValueByNID(X509_NAME* name, int nid, std::string* value) { 51 int index = X509_NAME_get_index_by_NID(name, nid, -1); 52 if (index < 0) 53 return false; 54 55 return ParsePrincipalValueByIndex(name, index, value); 56 } 57 58 bool ParseDate(ASN1_TIME* x509_time, base::Time* time) { 59 if (!x509_time || 60 (x509_time->type != V_ASN1_UTCTIME && 61 x509_time->type != V_ASN1_GENERALIZEDTIME)) 62 return false; 63 64 base::StringPiece str_date(reinterpret_cast<const char*>(x509_time->data), 65 x509_time->length); 66 67 CertDateFormat format = x509_time->type == V_ASN1_UTCTIME ? 68 CERT_DATE_FORMAT_UTC_TIME : CERT_DATE_FORMAT_GENERALIZED_TIME; 69 return ParseCertificateDate(str_date, format, time); 70 } 71 72 } // namespace x509_openssl_util 73 74 } // namespace net 75