monotone

monotone Mtn Source Tree

Root/botan/asn1_ku.cpp

1/*************************************************
2* KeyUsage Source File *
3* (C) 1999-2005 The Botan Project *
4*************************************************/
5
6#include <botan/asn1_obj.h>
7#include <botan/bit_ops.h>
8
9namespace Botan {
10
11namespace DER {
12
13/*************************************************
14* DER encode a KeyUsage BIT STRING *
15*************************************************/
16void encode(DER_Encoder& encoder, Key_Constraints usage)
17 {
18 if(usage == NO_CONSTRAINTS)
19 throw Encoding_Error("Cannot encode zero usage constraints");
20
21 const u32bit unused_bits = low_bit(usage) - 1;
22
23 SecureVector<byte> der;
24 der.append(BIT_STRING);
25 der.append(2 + ((unused_bits < 8) ? 1 : 0));
26 der.append(unused_bits % 8);
27 der.append((usage >> 8) & 0xFF);
28 if(usage & 0xFF)
29 der.append(usage & 0xFF);
30
31 encoder.add_raw_octets(der);
32 }
33
34}
35
36namespace BER {
37
38/*************************************************
39* Decode a BER encoded KeyUsage *
40*************************************************/
41void decode(BER_Decoder& source, Key_Constraints& key_usage)
42 {
43 BER_Object obj = source.get_next_object();
44
45 if(obj.type_tag != BIT_STRING || obj.class_tag != UNIVERSAL)
46 throw BER_Bad_Tag("Bad tag for usage constraint",
47 obj.type_tag, obj.class_tag);
48 if(obj.value.size() != 2 && obj.value.size() != 3)
49 throw BER_Decoding_Error("Bad size for BITSTRING in usage constraint");
50 if(obj.value[0] >= 8)
51 throw BER_Decoding_Error("Invalid unused bits in usage constraint");
52
53 const byte mask = (0xFF << obj.value[0]);
54 obj.value[obj.value.size()-1] &= mask;
55
56 u16bit usage = 0;
57 for(u32bit j = 1; j != obj.value.size(); j++)
58 usage = (obj.value[j] << 8) | usage;
59
60 key_usage = Key_Constraints(usage);
61 }
62
63}
64
65}

Archive Download this file

Branches

Tags

Quick Links:     www.monotone.ca    -     Downloads    -     Documentation    -     Wiki    -     Code Forge    -     Build Status