OP-TEE / optee_os

Trusted side of the TEE
Other
1.59k stars 1.07k forks source link

use TEE_BigIntNeg function,input is 0x35,but output is still 35? #6969

Closed hallowsman closed 3 months ago

hallowsman commented 3 months ago

use TEE_BigIntNeg function,input is 0x35,but output is still 35?

// 打印带符号的大整数 void TEE_BigIntPrintSigned(const TEE_BigInt bigInt) { size_t len = TEE_BigIntSizeInBytes(bigInt); uint8_t buffer = malloc(len); if (!buffer) { printf("内存分配失败\n"); return; }

// 将 TEE_BigInt 转换为字节数组并存储在缓冲区中
TEE_Result res = TEE_BigIntConvertToOctetString(buffer, &len, bigInt);
if (res != TEE_SUCCESS)
{
    free(buffer);
    printf("转换到字节数组失败: 0x%x\n", res);
    return;
}

// 确定符号
bool isNegative = (buffer[0] & 0x80) != 0; // 最高位为1表示负数

// 打印负号(如果需要)
if (isNegative)
{
    printf("-");
}
else
{

    printf("****不是isNegative");
}

// 打印字节数组中的每个字节
for (size_t i = 0; i < len; i++)
{
    printf("%02X", buffer[len - 1 - i]); // 注意顺序,从最低有效字节开始打印
}
printf("\n");

free(buffer);

}

// TEE_BigIntNeg 取反 取负操作 void fun_tee_bigint_neg() { size_t len = TEE_BigIntSizeInU32(1024); uint32_t twoints[2 * len]; // 分配足够的空间来存储两个大整数

// 分配静态内存
TEE_BigInt *result = (TEE_BigInt *)twoints;
TEE_BigInt *op1 = (TEE_BigInt *)(twoints + len);

// 初始化大整数
TEE_BigIntInit(result, len);
TEE_BigIntInit(op1, len);

// 定义初值
uint8_t value_op1[] = {0x35};    // 例如:53
uint8_t value_result[] = {0x00}; // 例如:53

// 将初值转换为 TEE_BigInt 格式
TEE_BigIntConvertFromOctetString(op1, value_op1, sizeof(value_op1), 1);
TEE_BigIntConvertFromOctetString(result, value_result, sizeof(value_result), 1);

// 打印初始值
DMSG("*****Initial op1*****");
TEE_BigIntPrintSigned(op1);

// 执行大整数取负操作
TEE_BigIntNeg(result, op1);

// 打印结果
DMSG("*****neg result *****");
TEE_BigIntPrintSigned(result);

}

jforissier commented 3 months ago

Hi @hallowsman,

This is expected as per the specification of the TEE_BigIntConvertToOctetString() function:

The TEE_BigIntConvertToOctetString function converts the absolute value of an integer in TEE_BigInt format into an octet string

Note the words: "absolute value". You can use TEE_BigIntCmpS32(op, 0) to get the sign of op.

If you add this to your example:

int32_t s;
TEE_BigIntConvertToS32(&s, result);
printf("%d\n", s)

...it will print -53.

hallowsman commented 3 months ago

it worked ,thanks!!!