aboutsummaryrefslogtreecommitdiff
path: root/CpriMisc.c
blob: edc5c4b64a94f42d969b78ee2119dcbd2030ec08 (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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// This file was extracted from the TCG Published
// Trusted Platform Module Library
// Part 4: Supporting Routines
// Family "2.0"
// Level 00 Revision 01.16
// October 30, 2014

#include "OsslCryptoEngine.h"
//
//
//      Functions
//
//      BnTo2B()
//
//     This function is used to convert a BigNum() to a byte array of the specified size. If the number is too large
//     to fit, then 0 is returned. Otherwise, the number is converted into the low-order bytes of the provided array
//     and the upper bytes are set to zero.
//
//     Return Value                     Meaning
//
//     0                                failure (probably fatal)
//     1                                conversion successful
//
BOOL
BnTo2B(
    TPM2B               *outVal,             // OUT: place for the result
    BIGNUM              *inVal,              // IN: number to convert
    UINT16               size                // IN: size of the output.
    )
{
    BYTE      *pb = outVal->buffer;
    UINT16    unpaddedSize = (((UINT16) BN_num_bits(inVal) + 7) / 8);
    outVal->size = size;
    if(size < unpaddedSize)
        return FALSE;

    size -= unpaddedSize;
    for(;size > 0; size--)
        *pb++ = 0;
    BN_bn2bin(inVal, pb);
    return TRUE;
}
//
//
//      Copy2B()
//
//     This function copies a TPM2B structure. The compiler can't generate a copy of a TPM2B generic
//     structure because the actual size is not known. This function performs the copy on any TPM2B pair. The
//     size of the destination should have been checked before this call to make sure that it will hold the TPM2B
//     being copied.
//     This replicates the functionality in the MemoryLib.c.
//
void
Copy2B(
    TPM2B               *out,                // OUT: The TPM2B to receive the copy
    TPM2B               *in                  // IN: the TPM2B to copy
    )
{
    BYTE        *pIn = in->buffer;
    BYTE        *pOut = out->buffer;
    int          count;
    out->size = in->size;
    for(count = in->size; count > 0; count--)
       *pOut++ = *pIn++;
   return;
}
//
//
//      BnFrom2B()
//
//     This function creates a BIGNUM from a TPM2B and fails if the conversion fails.
//
BIGNUM *
BnFrom2B(
   BIGNUM              *out,              // OUT: The BIGNUM
   const TPM2B         *in                // IN: the TPM2B to copy
   )
{
   if(BN_bin2bn(in->buffer, in->size, out) == NULL)
       FAIL(FATAL_ERROR_INTERNAL);
   return out;
}