1 // Copyright 2015 The BoringSSL Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include <openssl/bn.h>
16
17 #include <openssl/bytestring.h>
18 #include <openssl/err.h>
19
20
BN_parse_asn1_unsigned(CBS * cbs,BIGNUM * ret)21 int BN_parse_asn1_unsigned(CBS *cbs, BIGNUM *ret) {
22 CBS child;
23 int is_negative;
24 if (!CBS_get_asn1(cbs, &child, CBS_ASN1_INTEGER) ||
25 !CBS_is_valid_asn1_integer(&child, &is_negative)) {
26 OPENSSL_PUT_ERROR(BN, BN_R_BAD_ENCODING);
27 return 0;
28 }
29
30 if (is_negative) {
31 OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER);
32 return 0;
33 }
34
35 return BN_bin2bn(CBS_data(&child), CBS_len(&child), ret) != NULL;
36 }
37
BN_marshal_asn1(CBB * cbb,const BIGNUM * bn)38 int BN_marshal_asn1(CBB *cbb, const BIGNUM *bn) {
39 // Negative numbers are unsupported.
40 if (BN_is_negative(bn)) {
41 OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER);
42 return 0;
43 }
44
45 CBB child;
46 if (!CBB_add_asn1(cbb, &child, CBS_ASN1_INTEGER) ||
47 // The number must be padded with a leading zero if the high bit would
48 // otherwise be set or if |bn| is zero.
49 (BN_num_bits(bn) % 8 == 0 && !CBB_add_u8(&child, 0x00)) ||
50 !BN_bn2cbb_padded(&child, BN_num_bytes(bn), bn) ||
51 !CBB_flush(cbb)) {
52 OPENSSL_PUT_ERROR(BN, BN_R_ENCODE_ERROR);
53 return 0;
54 }
55
56 return 1;
57 }
58