gpt4 book ai didi

java - 在没有 BouncyCaSTLe 的情况下在 Java 中使用 RSA 加密

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:31:08 27 4
gpt4 key购买 nike

在我的程序中,我尝试使用以下代码使用 RSA 加密一些明文:

static String RSAEncrypt(String pubkey, String plain){
return encrypt(pubkey,plain,"RSA");
}
static String encrypt(String stringKey, String plain, String algo){
String enc="failed";
try{
byte[] byteKey = new BASE64Decoder().decodeBuffer(stringKey);
Key key = new SecretKeySpec(byteKey,algo);

byte[] data = plain.getBytes();
Cipher c = Cipher.getInstance(algo);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = c.doFinal(data);
enc = new BASE64Encoder().encode(encVal);
}catch(Exception e){e.printStackTrace();}

return enc;
}

但是,当它运行时,它显示如下错误:

java.security.InvalidKeyException: No installed provider supports this key: javax.crypto.spec.SecretKeySpec
at javax.crypto.Cipher.chooseProvider(Cipher.java:877)
at javax.crypto.Cipher.init(Cipher.java:1212)
at javax.crypto.Cipher.init(Cipher.java:1152)
at Crypto.encrypt(Crypto.java:37)
at Crypto.RSAEncrypt(Crypto.java:62)

我已经尝试将其更改为 RSA/None/PKCS1Padding 和 RSA/ECB/PKCS1Padding 无济于事。我知道安装 BouncyCaSTLe 可能会有所帮助,但我想避免它(我想避免更多的依赖和无论如何,我在安装它时遇到了一些问题)。提前感谢您的任何想法。

最佳答案

如评论中所述,SecretKeySpec 仅适用于对称算法。您提到您通过调用 getEncoded 获得了包含 key 的 byte[]

有两种可能性和两种结果格式:

RSA私钥编码

在 RSA 私钥实例上调用 PrivateKey#getEncoded 将导致私钥的 PKCS#8 编码,并且可以借助 PKCS8EncodedKeySpec 恢复它.

RSA公钥编码

RSA 公钥上的

PublicKey#getEncoded 生成通用 X.509 公钥编码,可以使用 X509EncodedKeySpec 恢复.

示例用法

byte[] data = "test".getBytes("UTF8");
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(512);
KeyPair keyPair = kpg.genKeyPair();

byte[] pk = keyPair.getPublic().getEncoded();
X509EncodedKeySpec spec = new X509EncodedKeySpec(pk);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(spec);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] encrypted = cipher.doFinal(data);

byte[] priv = keyPair.getPrivate().getEncoded();
PKCS8EncodedKeySpec spec2 = new PKCS8EncodedKeySpec(priv);
PrivateKey privKey = keyFactory.generatePrivate(spec2);
cipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] plain = cipher.doFinal(encrypted);

System.out.println(new String(plain, "UTF8")); //=> "test"

关于java - 在没有 BouncyCaSTLe 的情况下在 Java 中使用 RSA 加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10956956/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com