5 // Created by Mitch Adler on 6/19/12.
6 // Copyright (c) 2012 Apple Inc. All rights reserved.
12 #include "utilities/SecCFRelease.h"
13 #include "utilities/der_plist.h"
14 #include "utilities/der_plist_internal.h"
16 #include <corecrypto/ccder.h>
17 #include <CoreFoundation/CoreFoundation.h>
20 const uint8_t* der_decode_number(CFAllocatorRef allocator
, CFOptionFlags mutability
,
21 CFNumberRef
* number
, CFErrorRef
*error
,
22 const uint8_t* der
, const uint8_t *der_end
)
27 size_t payload_size
= 0;
28 const uint8_t *payload
= ccder_decode_tl(CCDER_INTEGER
, &payload_size
, der
, der_end
);
30 if (NULL
== payload
|| (der_end
- payload
) < payload_size
) {
31 SecCFDERCreateError(kSecDERErrorUnknownEncoding
, CFSTR("Unknown number encoding"), NULL
, error
);
34 if (payload_size
> sizeof(long long)) {
35 SecCFDERCreateError(kSecDERErrorUnsupportedNumberType
, CFSTR("Number too large"), NULL
, error
);
42 if (payload_size
> 0) {
43 if ((*payload
& 0x80) == 0x80)
44 value
= -1; // Negative integers fill with 1s so we end up negative.
46 const uint8_t* const payload_end
= payload
+ payload_size
;
48 for (const uint8_t *payload_byte
= payload
;
49 payload_byte
< payload_end
;
52 value
|= *payload_byte
;
56 *number
= CFNumberCreate(allocator
, kCFNumberLongLongType
, &value
);
58 if (*number
== NULL
) {
59 SecCFDERCreateError(kSecDERErrorAllocationFailure
, CFSTR("Number allocation failed"), NULL
, error
);
63 return payload
+ payload_size
;
67 static inline uint8_t byte_of(size_t byteNumber
, long long value
)
69 return value
>> (8 * (byteNumber
- 1));
72 static inline size_t bytes_when_encoded(long long value
)
74 size_t bytes_encoded
= sizeof(long long);
76 uint8_t first_byte
= byte_of(bytes_encoded
, value
);
78 // Skip initial 0xFFs or 0x00
79 if (first_byte
== 0xFF || first_byte
== 0x00) {
82 } while (bytes_encoded
> 1 && (byte_of(bytes_encoded
, value
) == first_byte
));
84 if ((first_byte
& 0x80) != (byte_of(bytes_encoded
, value
) & 0x80))
91 size_t der_sizeof_number(CFNumberRef data
, CFErrorRef
*error
)
94 if (!CFNumberGetValue(data
, kCFNumberLongLongType
, &value
))
97 return ccder_sizeof(CCDER_INTEGER
, bytes_when_encoded(value
));
100 uint8_t* der_encode_number(CFNumberRef number
, CFErrorRef
*error
,
101 const uint8_t *der
, uint8_t *der_end
)
104 if (!CFNumberGetValue(number
, kCFNumberLongLongType
, &value
))
107 size_t first_byte_to_include
= bytes_when_encoded(value
);
109 if (!der_end
|| der_end
- der
< first_byte_to_include
)
112 // Put the bytes we should include on the end.
113 for(int bytes_included
= 0; bytes_included
< first_byte_to_include
; ++bytes_included
)
116 *der_end
= value
& 0xFF;
120 return ccder_encode_tl(CCDER_INTEGER
, first_byte_to_include
, der
, der_end
);