Security | RSA2048私钥存在小于256byte(比如255byte)

最近搞TEE里面Crypto模块,遇到RSA2048 Private key(d因子)只有255byte

而在解密的时候我直接使用长度为256byte,导致解密失败(原因是末尾补零出现公私钥不匹配)

解决方法要么使用255byte,要么高位补零(比256小都需要高位补零)

TEE_GetObjectBufferAttribute(key, attributeID, d, &dL);
uint32_t cnt = 256 - dL;
if (cnt > 0) {
	char tmp[512] = { 0 };
	memcpy(tmp + cnt, d, dL);
	memset(d, 0x00, 256);
	memcpy(d, tmp, dL + cnt);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用 Java 实现 RSA对生成,以及从推导公的示例代码: ```java import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.EncodedKeySpec; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import javax.crypto.Cipher; public class RSAExample { public static void main(String[] args) throws Exception { // 生成 RSA对 KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); // 从推导公 EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded()); EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(privateKeySpec.getEncoded()); PublicKey derivedPublicKey = KeyFactory.getInstance("RSA").generatePublic(publicKeySpec); // 测试加解密 String message = "Hello, world!"; byte[] encrypted = encrypt(message.getBytes(), publicKey); byte[] decrypted = decrypt(encrypted, privateKey); System.out.println(new String(decrypted)); } public static byte[] encrypt(byte[] plainText, PublicKey publicKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); return cipher.doFinal(plainText); } public static byte[] decrypt(byte[] cipherText, PrivateKey privateKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); return cipher.doFinal(cipherText); } } ``` 首先,我们使用 `KeyPairGenerator` 生成一个 2048 位的 RSA对。然后,我们从中提取出 PKCS#8 编码格式的字节数组,并使用 `X509EncodedKeySpec` 将其转换为公,即可完成从推导公的过程。 最后,我们使用 `encrypt` 和 `decrypt` 方法测试加解密功能。注意,加密和解密时使用的是公,而不是推导出来的公和原始

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值