1 // This file was extracted from the TCG Published
2 // Trusted Platform Module Library
3 // Part 4: Supporting Routines
4 // Family "2.0"
5 // Level 00 Revision 01.16
6 // October 30, 2014
7 
8 #include "OsslCryptoEngine.h"
9 //
10 //
11 //      Functions
12 //
13 //      BnTo2B()
14 //
15 //     This function is used to convert a BigNum() to a byte array of the specified size. If the number is too large
16 //     to fit, then 0 is returned. Otherwise, the number is converted into the low-order bytes of the provided array
17 //     and the upper bytes are set to zero.
18 //
19 //     Return Value                     Meaning
20 //
21 //     0                                failure (probably fatal)
22 //     1                                conversion successful
23 //
24 BOOL
BnTo2B(TPM2B * outVal,BIGNUM * inVal,UINT16 size)25 BnTo2B(
26     TPM2B               *outVal,             // OUT: place for the result
27     BIGNUM              *inVal,              // IN: number to convert
28     UINT16               size                // IN: size of the output.
29     )
30 {
31     BYTE      *pb = outVal->buffer;
32     UINT16    unpaddedSize = (((UINT16) BN_num_bits(inVal) + 7) / 8);
33     outVal->size = size;
34     if(size < unpaddedSize)
35         return FALSE;
36 
37     size -= unpaddedSize;
38     for(;size > 0; size--)
39         *pb++ = 0;
40     BN_bn2bin(inVal, pb);
41     return TRUE;
42 }
43 //
44 //
45 //      Copy2B()
46 //
47 //     This function copies a TPM2B structure. The compiler can't generate a copy of a TPM2B generic
48 //     structure because the actual size is not known. This function performs the copy on any TPM2B pair. The
49 //     size of the destination should have been checked before this call to make sure that it will hold the TPM2B
50 //     being copied.
51 //     This replicates the functionality in the MemoryLib.c.
52 //
53 void
Copy2B(TPM2B * out,TPM2B * in)54 Copy2B(
55     TPM2B               *out,                // OUT: The TPM2B to receive the copy
56     TPM2B               *in                  // IN: the TPM2B to copy
57     )
58 {
59     BYTE        *pIn = in->buffer;
60     BYTE        *pOut = out->buffer;
61     int          count;
62     out->size = in->size;
63     for(count = in->size; count > 0; count--)
64        *pOut++ = *pIn++;
65    return;
66 }
67 //
68 //
69 //      BnFrom2B()
70 //
71 //     This function creates a BIGNUM from a TPM2B and fails if the conversion fails.
72 //
73 BIGNUM *
BnFrom2B(BIGNUM * out,const TPM2B * in)74 BnFrom2B(
75    BIGNUM              *out,              // OUT: The BIGNUM
76    const TPM2B         *in                // IN: the TPM2B to copy
77    )
78 {
79    if(BN_bin2bn(in->buffer, in->size, out) == NULL)
80        FAIL(FATAL_ERROR_INTERNAL);
81    return out;
82 }
83