jwt使用rsa加密时报错(main方法测试始终正确,一使用web运行就报错)

编程入门 行业动态 更新时间:2024-10-26 02:34:59

jwt使用rsa加密时<a href=https://www.elefans.com/category/jswz/34/1771188.html style=报错(main方法测试始终正确,一使用web运行就报错)"/>

jwt使用rsa加密时报错(main方法测试始终正确,一使用web运行就报错)

错误信息

java.security.InvalidKeyException: IOException: DerInputStream.getLength(): lengthTag=13, too big.

原因:多线程引起的并发问题(更具体的原因不清楚)。

解决:使用synchronized (或者Lock,我懒得用Lock了)

	/*** 从文件中获取公钥* * @param publicKeyFilePath*            文件路径* @return*/public synchronized static PublicKey getPublicKey(String publicKeyFilePath) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {return getPublicKey(new FileInputStream(publicKeyFilePath));}/*** 从文件中获取公钥* * @param publicKeyFilePath*            classpath中的文件相对路径(只有文件名都行,ClassLoader.getResourceAsStream会自行搜索)* @return*/public synchronized static PublicKey getPublicKeyClasspath(String publicKeyFilePath) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {return getPublicKey(RsaKeyUtil.class.getClassLoader().getResourceAsStream(publicKeyFilePath));}/*** 从字节输入流中获取公钥* * @param publicKeyInput* @return* @throws IOException* @throws NoSuchAlgorithmException* @throws InvalidKeySpecException*/public synchronized static PublicKey getPublicKey(InputStream publicKeyInput) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {try (InputStream input = publicKeyInput; DataInputStream dis = new DataInputStream(input)) {byte[] keyBytes = new byte[input.available()];dis.readFully(keyBytes);X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);KeyFactory kf = KeyFactory.getInstance("RSA");return kf.generatePublic(spec);}}public synchronized static PublicKey getPublicKey64(String publicKeyFilePath) throws Exception {return getPublicKey64(new FileInputStream(publicKeyFilePath));}public synchronized static PublicKey getPublicKey64Classpath(String publicKeyFilePath) throws Exception {return getPublicKey64(RsaKeyUtil.class.getClassLoader().getResourceAsStream(publicKeyFilePath));}public synchronized static PublicKey getPublicKey64(InputStream publicKeyInput) throws Exception {try (InputStream input = publicKeyInput) {String key64 = FileUtil.readAllString(input);byte[] keyByte = Base64Util.decodeBase64(key64);X509EncodedKeySpec spec = new X509EncodedKeySpec(keyByte);KeyFactory kf = KeyFactory.getInstance("RSA");return kf.generatePublic(spec);}}

更多推荐

jwt使用rsa加密时报错(main方法测试始终正确,一使用web运行就报错)

本文发布于:2023-11-16 23:49:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1636064.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:报错   时报   正确   测试   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!