前端RSA加密密钥格式

前端生成公钥方式:

let szPublicKeyString = Secure.generateRSAPublicKey(szMattsRSAkey);

前端有对公钥进行base64进行编码, 代码未体现
后端使用前端生成的公钥进行数据加密报错
后端使用的Hutool依赖包,代码如下:

public class RsaUtils {

public static String encrypt(String content, String publicKey) {

try{

RSA rsa = new RSA(null,publicKey);

return rsa.encryptBase64(content, KeyType.PublicKey);

}catch (Exception e){

e.printStackTrace();

}

return null;

}

public static void main(String[] args) {

encrypt("xxxxx", "YTZhNTU2ODdkMjE3NzFlZGMxMjYw" +

"MTczZGRmODE5NWI2ODY2ZGE5ZjI1YTVjZjAzMGJm" +

"ZTdmYWNiZDIwMDExOTNjZTMwNmUyMTg1M2I3NGZmOWViZG" +

"FiYmNkZmVjYmY3MTk3MDY4NDIxZWQ3YzNkMTZiN2M5ZDljYjFmNjlhYmM5M" +

"zAwNWFiNjFiMWJlZDc0NThhYjAwZTdiMmRiYWU2ZjU0MzFhNjZiNjNjN2U4MDhmMjBkZG" +

"JmODJmN2I1NTdjZDFiMDdlM2JjZmIxODFjOTRkMWYxMDM5MWM0YjA1ZDExYjJiMmY4MTVlO" +

"DUwMjM2ODdkZTUwMGY1ZWEwNGE5Nw==");

}

}

报错如下:

cn.hutool.crypto.CryptoException: InvalidKeySpecException: java.security.InvalidKeyException: invalid key format

at cn.hutool.crypto.SecureUtil.generatePublicKey(SecureUtil.java:266)

at cn.hutool.crypto.SecureUtil.generatePublicKey(SecureUtil.java:249)

at cn.hutool.crypto.asymmetric.BaseAsymmetric.init(BaseAsymmetric.java:108)

at cn.hutool.crypto.asymmetric.BaseAsymmetric.<init>(BaseAsymmetric.java:77)

at cn.hutool.crypto.asymmetric.AsymmetricCrypto.<init>(AsymmetricCrypto.java:119)

at cn.hutool.crypto.asymmetric.AsymmetricCrypto.<init>(AsymmetricCrypto.java:68)

at cn.hutool.crypto.asymmetric.RSA.<init>(RSA.java:76)

at com.h2t.study.RsaUtils.encrypt(RsaUtils.java:59)

at com.h2t.study.RsaUtils.main(RsaUtils.java:127)

Caused by: java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format

at sun.security.rsa.RSAKeyFactory.engineGeneratePublic(RSAKeyFactory.java:205)

at java.security.KeyFactory.generatePublic(KeyFactory.java:334)

at cn.hutool.crypto.SecureUtil.generatePublicKey(SecureUtil.java:264)

... 8 more

Caused by: java.security.InvalidKeyException: invalid key format

at sun.security.x509.X509Key.decode(X509Key.java:387)

at sun.security.x509.X509Key.decode(X509Key.java:403)

现在感觉是前后端生成公钥的方式不一致,导致后端这边无法使用前端的公钥进行加密
有没有大佬曾经搞过加密解密的,忘指点一下,卡这好久了,在卡要被劝退了

回答:

image
我们之前是后端生成的公钥, 前端用来加密字段

回答:

我也怀疑是密钥位数问题,理论上只要密钥位数是一致的,这个流程就应该有效(BASE64编解码不应该影响结果)

以上是 前端RSA加密密钥格式 的全部内容, 来源链接: utcz.com/a/167372.html

回到顶部