aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/pubkey/x509_key.cpp
blob: 5952d5ccd26329fcff6c37a5bab3ed81b16994c3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
* X.509 Public Key
* (C) 1999-2010 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/x509_key.h>
#include <botan/data_src.h>
#include <botan/ber_dec.h>
#include <botan/pem.h>
#include <botan/asn1_obj.h>
#include <botan/pk_algs.h>

namespace Botan::X509 {

/*
* PEM encode a X.509 public key
*/
std::string PEM_encode(const Public_Key& key)
   {
   return PEM_Code::encode(key.subject_public_key(),
                           "PUBLIC KEY");
   }

/*
* Extract a public key and return it
*/
Public_Key* load_key(DataSource& source)
   {
   try {
      AlgorithmIdentifier alg_id;
      std::vector<uint8_t> key_bits;

      if(ASN1::maybe_BER(source) && !PEM_Code::matches(source))
         {
         BER_Decoder(source)
            .start_sequence()
            .decode(alg_id)
            .decode(key_bits, ASN1_Type::BitString)
         .end_cons();
         }
      else
         {
         DataSource_Memory ber(
            PEM_Code::decode_check_label(source, "PUBLIC KEY")
            );

         BER_Decoder(ber)
            .start_sequence()
            .decode(alg_id)
            .decode(key_bits, ASN1_Type::BitString)
         .end_cons();
         }

      if(key_bits.empty())
         throw Decoding_Error("X.509 public key decoding");

      return load_public_key(alg_id, key_bits).release();
      }
   catch(Decoding_Error& e)
      {
      throw Decoding_Error("X.509 public key decoding", e);
      }
   }

}