Upgrade Duplicate utility to the latest tss
[aaf/sshsm.git] / tpm-util / duplicate / util.c
1 /*
2  * Copyright 2018 Intel Corporation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *     Unless required by applicable law or agreed to in writing, software
11  *     distributed under the License is distributed on an "AS IS" BASIS,
12  *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *     See the License for the specific language governing permissions and
14  *     limitations under the License.
15  */
16 // Author: Arun Kumar Sekar
17
18 #include "util.h"
19
20 TPM2_RC ConcatSizedByteBuffer( TPM2B_MAX_BUFFER *result, TPM2B *addBuffer )
21 {
22     int i;
23
24     if( ( result->size + addBuffer->size ) > TPM2_MAX_DIGEST_BUFFER )
25         return TSS2_SYS_RC_BAD_VALUE;
26     else
27     {
28         for( i = 0; i < addBuffer->size; i++ )
29             result->buffer[i + result->size] = addBuffer->buffer[i];
30
31         result->size += addBuffer->size;
32
33         return TPM2_RC_SUCCESS;
34     }
35 }
36
37 int saveDataToFile(const char *fileName, UINT8 *buf, UINT16 size)
38 {
39     FILE *f;
40     UINT16 count = 1;
41     if( fileName == NULL || buf == NULL || size == 0 )
42         return -1;
43
44     f = fopen(fileName, "wb+");
45     if( f == NULL ) {
46         printf("File(%s) open error.\n", fileName);
47         return -2;
48     }
49
50     while( size > 0 && count > 0 ) {
51         count = fwrite(buf, 1, size, f);
52         size -= count;
53         buf += count;
54     }
55
56     if( size > 0 ) {
57         printf("File write error\n");
58         fclose(f);
59         return -3;
60     }
61
62     fclose(f);
63     return 0;
64 }
65
66 int loadDataFromFile(const char *fileName, UINT8 *buf, UINT16 *size)
67 {
68     UINT16 count = 1, left;
69     FILE *f;
70     if ( size == NULL || buf == NULL || fileName == NULL )
71         return -1;
72
73     f = fopen(fileName, "rb+");
74     if( f == NULL ) {
75         printf("File(%s) open error.\n", fileName);
76         return -2;
77     }
78
79     left = *size;
80     *size = 0;
81     while( left > 0 && count > 0 ) {
82         count = fread(buf, 1, left, f);
83         *size += count;
84         left -= count;
85         buf += count;
86     }
87
88     if( *size == 0 ) {
89         printf("File read error\n");
90         fclose(f);
91         return -3;
92     }
93     fclose(f);
94     return 0;
95 }