关键词搜索

源码搜索 ×
×

RSA Data must start with zero问题解决方法

发布2017-03-17浏览14644次

详情内容

RSA工具使用公钥加密之后生成byte[] ,直接解密是没有问题的,但将byte[]通过Base64.encode(byte[])之后得到的字符串重新getBytes()去解密是会出现RSA Data must start with zero的问题的。

解决方法:

  1. /**
  2. * 将加密后的字节数组转换为对象
  3. *
  4. * @MethodName: bytesToString
  5. * @Description:
  6. * @param encrytpByte
  7. * @return
  8. * @throws
  9. */
  10. public static String bytesToString(byte[] encrytpByte) {
  11. String result = "";
  12. for (Byte bytes : encrytpByte) {
  13. result += bytes.toString() + " ";
  14. }
  15. return result;
  16. }
  17. /**
  18. * 公钥加密
  19. *
  20. * @MethodName: encrypt
  21. * @Description:
  22. * @param publicKey
  23. * @param obj
  24. * @return
  25. * @throws
  26. */
  27. public static byte[] encrypt(RSAPublicKey publicKey, byte[] obj) {
  28. if (publicKey != null) {
  29. try {
  30. Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
  31. cipher.init(Cipher.ENCRYPT_MODE, publicKey);
  32. return cipher.doFinal(obj);
  33. } catch (Exception e) {
  34. e.printStackTrace();
  35. }
  36. }
  37. return null;
  38. }
  39. /**
  40. * 私钥解密
  41. *
  42. * @MethodName: decrypt
  43. * @Description:
  44. * @param privateKey
  45. * @param obj
  46. * @return
  47. * @throws
  48. */
  49. public static byte[] decrypt(RSAPrivateKey privateKey, byte[] obj) {
  50. if (privateKey != null) {
  51. try {
  52. Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
  53. cipher.init(Cipher.DECRYPT_MODE, privateKey);
  54. return cipher.doFinal(obj);
  55. } catch (Exception e) {
  56. e.printStackTrace();
  57. }
  58. }
  59. return null;
  60. }
测试方法:

  1. @Test
  2. public void testRSA() throws Exception{
  3. String publicKey=EhcacheUtil.get(StaticProperty.WMS_OPEN_API_RSA_PUBLIC_KEY).toString();
  4. String privateKey=EhcacheUtil.get(StaticProperty.WMS_OPEN_API_RSA_PRIVATE_KEY).toString();
  5. String platformCode="1234",tenantCode="10000";
  6. byte [] bytes=SAASTokenManager.generateBytesToken(publicKey, platformCode, tenantCode);
  7. System.out.println("RSA bites 加密:"+new String(bytes));
  8. System.out.println("RSA bites 解密:"+new String(RSAUtils.decryptByPrivateKey(bytes, privateKey)));
  9. // 将bytes转换为String
  10. String bytesStr = RSAUtils.bytesToString(bytes);
  11. String[] strArr = bytesStr.split(" ");
  12. int len = strArr.length;
  13. // 转回bytes
  14. byte[] clone = new byte[len];
  15. for (int i = 0; i < len; i++) {
  16. clone[i] = Byte.parseByte(strArr[i]);
  17. }
  18. System.out.println("RSA bites 解密:"+new String(RSAUtils.decryptByPrivateKey(clone, privateKey)));
  19. }


相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载