项目背景:要对打印地址进行加密,用公钥加密后会乱码需要base64 decode一下,但是在解密时报错:javax.crypto.BadPaddingException: Data must start with zero

解决办法:

1.加解密时KeyFactory keyFactory = KeyFactory.getInstance("RSA");

2.将加解密的Cipher cipher = Cipher.getInstance(“RSA”)改为Cipher cipher = Cipher.getInstance(“RSA/ECB/NoPadding”)

困扰了两天的问题解决了,代码如下,希望有次问题的同学不必再走此弯路。


  1. package resources.util.encryption;
  2. import java.io.FileInputStream;
  3. import java.io.FileOutputStream;
  4. import java.io.ObjectInputStream;
  5. import java.io.ObjectOutputStream;
  6. import java.security.Key;
  7. import java.security.KeyFactory;
  8. import java.security.KeyPair;
  9. import java.security.KeyPairGenerator;
  10. import java.security.PrivateKey;
  11. import java.security.PublicKey;
  12. import java.security.spec.PKCS8EncodedKeySpec;
  13. import java.security.spec.X509EncodedKeySpec;
  14. import javax.crypto.Cipher;
  15. import org.junit.Test;
  16. public class EncryptionUtil {
  17. private static final String RSA = "RSA";
  18. private static final String RSANOPADDING = "RSA/ECB/NoPadding";
  19. private static final String PUBLIC_KEY_PATH = "public.key";
  20. private static final String PRIVATE_KEY_PATH = "private.key";
  21. private static final String path = Thread.currentThread().getContextClassLoader().getResource("/").getPath();
  22. // private static final String path = "";
  23. @Test
  24. public void generateKey() throws Exception {
  25. //KeyPairGenerator引擎类用于产生密钥对,JDK(7)默认支持的算法有,DiffieHellman、DSA、RSA、EC
  26. KeyPairGenerator generator = KeyPairGenerator.getInstance(RSA);
  27. generator.initialize(512);
  28. //产生密钥对
  29. KeyPair keyPair = generator.generateKeyPair();
  30. //获取公钥
  31. PublicKey publicKey = keyPair.getPublic();
  32. //获取私钥
  33. PrivateKey privateKey = keyPair.getPrivate();
  34. //将公钥与私钥写入文件,以备后用
  35. writeKey(PUBLIC_KEY_PATH, publicKey);
  36. writeKey(PRIVATE_KEY_PATH, privateKey);
  37. }
  38. //公钥加密
  39. public byte[] SRAEncrypt(String src) throws Exception {
  40. PublicKey publicKey= (PublicKey)readKey(path + PUBLIC_KEY_PATH);
  41. X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());
  42. KeyFactory keyFactory = KeyFactory.getInstance(RSA);
  43. publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
  44. Cipher cipher = Cipher.getInstance(RSANOPADDING);
  45. cipher.init(Cipher.ENCRYPT_MODE, publicKey);
  46. byte[] data = src.getBytes();
  47. int blockSize = 53;//根据异常提示设的53
  48. //根据块大小分块,不足一块的部分为一块
  49. int blocksNum = (int)Math.ceil((1.0*data.length)/blockSize);
  50. //加密
  51. for (int i = 0; i < blocksNum; i++) {
  52. if (i < blocksNum - 1) {
  53. cipher.doFinal(data, i * blockSize, blockSize);
  54. } else {
  55. cipher.doFinal(data, i * blockSize, data.length - i * blockSize);
  56. }
  57. }
  58. return data;
  59. }
  60. //私钥解密
  61. public String SRADecrypt(byte[] data) throws Exception{
  62. PrivateKey privateKey= (PrivateKey)readKey(path + PRIVATE_KEY_PATH);
  63. PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
  64. KeyFactory keyFactory = KeyFactory.getInstance(RSA);
  65. privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
  66. Cipher cipher = Cipher.getInstance(RSANOPADDING);
  67. cipher.init(Cipher.DECRYPT_MODE, privateKey);
  68. int blockSize = 64;//根据异常提示设的64
  69. //根据块大小分块,不足一块的部分为一块
  70. int blocksNum = (int)Math.ceil((1.0*data.length)/blockSize);
  71. //解密
  72. for (int i = 0; i < blocksNum; i++) {
  73. if (i < blocksNum - 1) {
  74. cipher.doFinal(data, i * blockSize, blockSize);
  75. } else {
  76. cipher.doFinal(data, i * blockSize, data.length - i * blockSize);
  77. }
  78. }
  79. return new String(data);
  80. }
  81. public void writeKey(String path, Key key) throws Exception {
  82. FileOutputStream fos = new FileOutputStream(path);
  83. ObjectOutputStream oos = new ObjectOutputStream(fos);
  84. oos.writeObject(key);
  85. oos.close();
  86. }
  87. public Key readKey(String path) throws Exception {
  88. FileInputStream fis = new FileInputStream(path);
  89. ObjectInputStream bis = new ObjectInputStream(fis);
  90. Object object = bis.readObject();
  91. bis.close();
  92. return (Key)object;
  93. }
  94. @Test
  95. public void testEncryptAndDecrypt() throws Exception {
  96. Cipher cipher = Cipher.getInstance(RSA);
  97. //读取公钥,进行加密
  98. PublicKey publicKey= (PublicKey) readKey("component/"+PUBLIC_KEY_PATH);
  99. cipher.init(Cipher.ENCRYPT_MODE, publicKey);
  100. //加密
  101. String sendInfo = "我的明文";
  102. byte[] results = cipher.doFinal(sendInfo.getBytes());
  103. //读取私钥,进行解密
  104. PrivateKey privateKey = (PrivateKey) readKey("component/"+PRIVATE_KEY_PATH);
  105. cipher.init(Cipher.DECRYPT_MODE, privateKey);
  106. //解密
  107. byte[] deciphered = cipher.doFinal(results);
  108. //得到明文
  109. String recvInfo = new String(deciphered);
  110. System.out.println(recvInfo);
  111. }
  112. @Test
  113. public void testSRA() throws Exception{
  114. PublicKey publicKey= (PublicKey)readKey("component/" + PUBLIC_KEY_PATH);
  115. X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());
  116. KeyFactory keyFactory = KeyFactory.getInstance(RSA);
  117. publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
  118. Cipher cipher = Cipher.getInstance(RSA);
  119. cipher.init(Cipher.ENCRYPT_MODE, publicKey);
  120. byte[] result = cipher.doFinal("yuanyuan".getBytes());
  121. PrivateKey privateKey= (PrivateKey)readKey("component/" + PRIVATE_KEY_PATH);
  122. PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
  123. privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
  124. cipher = Cipher.getInstance(RSANOPADDING);
  125. cipher.init(Cipher.DECRYPT_MODE, privateKey);
  126. result = cipher.doFinal(result);
  127. System.out.println(new String(result));
  128. }
  129. }

SRA解密报错:Data must start with zero的更多相关文章

  1. JAVA实现AES 解密报错Input length must be multiple of 16 when decrypting with padded cipher

    加密代码 /**解密 * @param content 待解密内容 * @param password 解密密钥 * @return */ public static byte[] decrypt(b ...

  2. 微信第三方平台解密报错:Illegal key size

    今天在交接别人代码的时候遇到的,微信第三方平台解密报的错误,原因: 如果密钥大于128, 会抛出java.security.InvalidKeyException: Illegal key size ...

  3. RSA解密报错java.security.spec.InvalidKeySpecException的解决办法

    java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : algid p ...

  4. 安装mysql_cluster报错: Data::Dumper丢失

    步骤 安装包:mysql-cluster-gpl-7.3.5-linux-glibc2.5-x86_64.tar.gz 下载解压到/usr/local/mysql mkdir /usr/local/m ...

  5. Echart..js插件渲染报错 data.length<1?

    问题 getJSON提交 返回数据正常,在传入参数进行序列化,渲染报表时报错 option.data.length < 1. 分析  1.可能情况一: . 可自己明明是getJSON()把渲染放 ...

  6. dubbo报错Data length too large: 10710120处理,及服务提供者协议配置详细说明

    工作中遇到以下报错信息 cause: java.io.IOException: Data length too large: 10710120, max payload: 8388608, chann ...

  7. PHP执行insert语句报错“Data too long for column”解决办法

    PHP执行mysql 插入语句, insert语句在Navicat for mysql(或任意的mysql管理工具) 中可以正确执行,但是用mysql_query()函数执行却报错. 错误 : “Da ...

  8. 【翻译】详解HTML5 自定义 Data 属性

    原标题:HTML5 Custom Data Attributes (data-*) 你是否曾经使用 class 或 rel 来保存任意的元数据,只为了使你的JavaScript更简单?如果你回答是的, ...

  9. OC学习笔记之属性详解和易错点

    属性的概念在OC1.0中就存在,格式是定义实例变量,然后定义setter和getter方法,用点操作符操作属性 举例,类的接口部分 @interface Father : NSObject { NSI ...

随机推荐

  1. 如何使用maven 打包源代码呢?

    如何使用maven 打包源代码呢? http://hw1287789687.iteye.com/blog/1943157

  2. HDU 4927 Series 1(推理+大数)

    HDU 4927 Series 1 题目链接 题意:给定一个序列,要求不断求差值序列.直到剩一个,输出这个数字 思路:因为有高精度一步.所以要推理一下公式,事实上纸上模拟一下非常easy推出公式就是一 ...

  3. 14.ZooKeeper Java API 使用样例

    转自:http://www.aboutyun.com/thread-7332-1-1.html package com.taobao.taokeeper.research.sample; import ...

  4. mysql 获取自增id的值的方法

    原生jdbc方式: Statement.getGeneratedKeys() 示例: Statement stmt = null; ResultSet rs = null; try { // // C ...

  5. 认识一下JavaScript

    1.什么是JavaScript? JavaScript简称“JS”,应用于HTML和WEB,广泛应用于服务器.PC.笔记本等设备. JavaScript 是 Web 的编程语言. 所有现代的 HTML ...

  6. Python产生随机数组,测试用

    import numpy as np if __name__ == '__main__': a=np.random.randint(0,10,size=[3,3])    print(a) 输出: [ ...

  7. Vue 使用use、prototype自定义自己的全局组件

    使用Vue.use()写一个自己的全局组件. 目录如下: 然后在Loading.vue里面定义自己的组件模板 <template> <div v-if="loadFlag& ...

  8. 为什么出现ORM

    ORM(Object Relational Mapping)对象关系映射,是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术 . 为什么出现ORM? 面向对象的特征:我们通常使用的开发语言J ...

  9. python基础-合并列表

    1.append()  向列表尾部追加一个新元素,列表只占一个索引位,在原有列表上增加 2.extend() 向列表尾部追加一个列表,将列表中的每个元素都追加进来,在原有列表上增加 3.+  直接用+ ...

  10. Android(Lollipop/5.0) Material Design(一) 简单介绍

    Material Design系列 Android(Lollipop/5.0)Material Design(一) 简单介绍 Android(Lollipop/5.0)Material Design( ...