TEE 非对称加密 RSA 签名验签实例
/** * 自动分配存放秘钥对象 * */ TEE_Result lge_utils_generate_keypair(TEE_ObjectHandle * rsa_key_obj) { TEE_Result ret; ret = TEE_AllocateTransientObject(TEE_TYPE_RSA_KEYPAIR, RSA_KEY_SIZE, rsa_key_obj); if (ret != TEE_SUCCESS) { EMSG("Fail to allocate rsa key pair object, ret 0x%xn", ret); return ret; } ret = TEE_GenerateKey(*rsa_key_obj, RSA_KEY_SIZE, NULL, 0); if (ret != TEE_SUCCESS) { EMSG("Fail to generate rsa key, ret 0x%xn", ret); return ret; } } /** * 把消息hash运算 ,生成摘要 * */ TEE_Result lge_utils_message_do_digest(uint8_t * msg_buffer, uint32_t msg_len, uint8_t * dig_buf , uint32_t *dig_len) { TEE_Result ret; TEE_OperationHandle oper_digest = NULL; ret = TEE_AllocateOperation(&oper_digest, TEE_ALG_SHA256, TEE_MODE_DIGEST, msg_len); if (ret != TEE_SUCCESS) { EMSG("Fail to allocate sha256 digest operation, ret 0x%xn", ret); return ret; } ret = TEE_DigestDoFinal(oper_digest, msg_buffer, msg_len, dig_buf, dig_len); if (ret != TEE_SUCCESS) { EMSG("Fail to do final sha256 digest, ret 0x%x!!!n", ret); TEE_FreeOperation(oper_digest); return ret; } TEE_FreeOperation(oper_digest); return TEE_SUCCESS; } /** * 把摘要进行签名 * */ TEE_Result lge_utils_rsa_sign(TEE_ObjectHandle rsa_key_obj, uint8_t *buf, size_t buf_len, uint8_t *signature, size_t *sign_len) { TEE_Result ret; TEE_OperationHandle oper_sign = NULL; ret = TEE_AllocateOperation(&oper_sign, TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256, TEE_MODE_SIGN, RSA_KEY_SIZE); if (ret != TEE_SUCCESS) { EMSG("Fail to allocate rsa signature operation!!!!!!!!!!!!!!, ret 0x%xn", ret); return ret; } ret = TEE_SetOperationKey(oper_sign, rsa_key_obj); if (ret != TEE_SUCCESS) { EMSG("Fail to set rsa signature key, ret 0x%xn", ret); goto clear; } ret = TEE_AsymmetricSignDigest(oper_sign, NULL, 0, buf, buf_len, signature, sign_len); if (ret != TEE_SUCCESS) { EMSG("Fail to do rsa signaturen"); goto clear; } EMSG("sign_len :%d",*sign_len); clear: TEE_FreeOperation(oper_sign); return ret; } /** * 输入签名和摘要 ,解密签名 对比摘要是否一致 * */ TEE_Result lge_utils_rsa_verify(TEE_ObjectHandle rsa_key_obj, uint8_t *buf, size_t buf_len, uint8_t *signature, size_t *sign_len) { TEE_Result ret; TEE_OperationHandle oper_sign = NULL; ret = TEE_AllocateOperation(&oper_sign, TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256, TEE_MODE_VERIFY, RSA_KEY_SIZE); if (ret != TEE_SUCCESS) { EMSG("Fail to allocate rsa signature operation!!!!!!!!!!!!!!, ret 0x%xn", ret); return ret; } ret = TEE_SetOperationKey(oper_sign, rsa_key_obj); if (ret != TEE_SUCCESS) { EMSG("Fail to set rsa signature key, ret 0x%xn", ret); goto clear; } ret = TEE_AsymmetricVerifyDigest(oper_sign, NULL, 0, buf, buf_len, signature, sign_len); if (ret != TEE_SUCCESS) { EMSG("Fail to do rsa signaturen"); goto clear; } EMSG("TEE_AsymmetricVerifyDigest success"); clear: TEE_FreeOperation(oper_sign); return ret; }