前言:

     最近无意中和同事交流数据安全传输的问题,想起自己曾经使用过的Rsa非对称加密算法,闲下来总结一下。

     其他几种加密方式:

什么是Rsa加密?

RSA算法是最流行的公钥密码算法,使用长度可以变化的密钥。RSA是第一个既能用于数据加密也能用于数字签名的算法。

RSA算法原理如下:

1.随机选择两个大质数p和q,p不等于q,计算N=pq; 
2.选择一个大于1小于N的自然数e,e必须与(p-1)(q-1)互素。 
3.用公式计算出d:d×e = 1 (mod (p-1)(q-1)) 。
4.销毁p和q。

最终得到的N和e就是“公钥”,d就是“私钥”,发送方使用N去加密数据,接收方只有使用d才能解开数据内容。

RSA的安全性依赖于大数分解,小于1024位的N已经被证明是不安全的,而且由于RSA算法进行的都是大数计算,使得RSA最快的情况也比DES慢上倍,这是RSA最大的缺陷,因此通常只能用于加密少量数据或者加密密钥,但RSA仍然不失为一种高强度的算法。

 

该如何使用呢?

 第一步:首先生成秘钥对

  1. /**
  2. * 随机生成RSA密钥对
  3. *
  4. * @param keyLength 密钥长度,范围:512~2048
  5. * 一般1024
  6. * @return
  7. */
  8. public static KeyPair generateRSAKeyPair(int keyLength) {
  9. try {
  10. KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
  11. kpg.initialize(keyLength);
  12. return kpg.genKeyPair();
  13. } catch (NoSuchAlgorithmException e) {
  14. e.printStackTrace();
  15. return null;
  16. }
  17. }

具体加密实现:

公钥加密

  1. /**
  2. * 用公钥对字符串进行加密
  3. *
  4. * @param data 原文
  5. */
  6. public static byte[] encryptByPublicKey(byte[] data, byte[] publicKey) throws Exception {
  7. // 得到公钥
  8. X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
  9. KeyFactory kf = KeyFactory.getInstance(RSA);
  10. PublicKey keyPublic = kf.generatePublic(keySpec);
  11. // 加密数据
  12. Cipher cp = Cipher.getInstance(ECB_PKCS1_PADDING);
  13. cp.init(Cipher.ENCRYPT_MODE, keyPublic);
  14. return cp.doFinal(data);
  15. }

私钥加密

  1. /**
  2. * 私钥加密
  3. *
  4. * @param data 待加密数据
  5. * @param privateKey 密钥
  6. * @return byte[] 加密数据
  7. */
  8. public static byte[] encryptByPrivateKey(byte[] data, byte[] privateKey) throws Exception {
  9. // 得到私钥
  10. PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);
  11. KeyFactory kf = KeyFactory.getInstance(RSA);
  12. PrivateKey keyPrivate = kf.generatePrivate(keySpec);
  13. // 数据加密
  14. Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
  15. cipher.init(Cipher.ENCRYPT_MODE, keyPrivate);
  16. return cipher.doFinal(data);
  17. }

公钥解密

  1. /**
  2. * 公钥解密
  3. *
  4. * @param data 待解密数据
  5. * @param publicKey 密钥
  6. * @return byte[] 解密数据
  7. */
  8. public static byte[] decryptByPublicKey(byte[] data, byte[] publicKey) throws Exception {
  9. // 得到公钥
  10. X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
  11. KeyFactory kf = KeyFactory.getInstance(RSA);
  12. PublicKey keyPublic = kf.generatePublic(keySpec);
  13. // 数据解密
  14. Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
  15. cipher.init(Cipher.DECRYPT_MODE, keyPublic);
  16. return cipher.doFinal(data);
  17. }

私钥解密

  1. /**
  2. * 使用私钥进行解密
  3. */
  4. public static byte[] decryptByPrivateKey(byte[] encrypted, byte[] privateKey) throws Exception {
  5. // 得到私钥
  6. PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);
  7. KeyFactory kf = KeyFactory.getInstance(RSA);
  8. PrivateKey keyPrivate = kf.generatePrivate(keySpec);
  9. // 解密数据
  10. Cipher cp = Cipher.getInstance(ECB_PKCS1_PADDING);
  11. cp.init(Cipher.DECRYPT_MODE, keyPrivate);
  12. byte[] arr = cp.doFinal(encrypted);
  13. return arr;
  14. }

几个全局变量解说:

  1. public static final String RSA = "RSA";// 非对称加密密钥算法
  2. public static final String ECB_PKCS1_PADDING = "RSA/ECB/PKCS1Padding";//加密填充方式
  3. public static final int DEFAULT_KEY_SIZE = 2048;//秘钥默认长度
  4. public static final byte[] DEFAULT_SPLIT = "#PART#".getBytes(); // 当要加密的内容超过bufferSize,则采用partSplit进行分块加密
  5. public static final int DEFAULT_BUFFERSIZE = (DEFAULT_KEY_SIZE / 8) - 11;// 当前秘钥支持加密的最大字节数

 

关于加密填充方式:之前以为上面这些操作就能实现rsa加解密,以为万事大吉了,呵呵,这事还没完,悲剧还是发生了,Android这边加密过的数据,服务器端死活解密不了,原来android系统的RSA实现是”RSA/None/NoPadding”,而标准JDK实现是”RSA/None/PKCS1Padding” ,这造成了在android机上加密后无法在服务器上解密的原因,所以在实现的时候这个一定要注意。

实现分段加密:搞定了填充方式之后又自信的认为万事大吉了,可是意外还是发生了,RSA非对称加密内容长度有限制,1024位key的最多只能加密127位数据,否则就会报错(javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes) , RSA 是常用的非对称加密算法。最近使用时却出现了“不正确的长度”的异常,研究发现是由于待加密的数据超长所致。RSA 算法规定:待加密的字节数不能超过密钥的长度值除以 8 再减去 11(即:KeySize / 8 – 11),而加密后得到密文的字节数,正好是密钥的长度值除以 8(即:KeySize / 8)。

 

公钥分段加密

  1. /**
  2. * 用公钥对字符串进行分段加密
  3. *
  4. */
  5. public static byte[] encryptByPublicKeyForSpilt(byte[] data, byte[] publicKey) throws Exception {
  6. int dataLen = data.length;
  7. if (dataLen <= DEFAULT_BUFFERSIZE) {
  8. return encryptByPublicKey(data, publicKey);
  9. }
  10. List<Byte> allBytes = new ArrayList<Byte>(2048);
  11. int bufIndex = 0;
  12. int subDataLoop = 0;
  13. byte[] buf = new byte[DEFAULT_BUFFERSIZE];
  14. for (int i = 0; i < dataLen; i++) {
  15. buf[bufIndex] = data[i];
  16. if (++bufIndex == DEFAULT_BUFFERSIZE || i == dataLen - 1) {
  17. subDataLoop++;
  18. if (subDataLoop != 1) {
  19. for (byte b : DEFAULT_SPLIT) {
  20. allBytes.add(b);
  21. }
  22. }
  23. byte[] encryptBytes = encryptByPublicKey(buf, publicKey);
  24. for (byte b : encryptBytes) {
  25. allBytes.add(b);
  26. }
  27. bufIndex = 0;
  28. if (i == dataLen - 1) {
  29. buf = null;
  30. } else {
  31. buf = new byte[Math.min(DEFAULT_BUFFERSIZE, dataLen - i - 1)];
  32. }
  33. }
  34. }
  35. byte[] bytes = new byte[allBytes.size()];
  36. {
  37. int i = 0;
  38. for (Byte b : allBytes) {
  39. bytes[i++] = b.byteValue();
  40. }
  41. }
  42. return bytes;
  43. }

私钥分段加密

  1. /**
  2. * 分段加密
  3. *
  4. * @param data 要加密的原始数据
  5. * @param privateKey 秘钥
  6. */
  7. public static byte[] encryptByPrivateKeyForSpilt(byte[] data, byte[] privateKey) throws Exception {
  8. int dataLen = data.length;
  9. if (dataLen <= DEFAULT_BUFFERSIZE) {
  10. return encryptByPrivateKey(data, privateKey);
  11. }
  12. List<Byte> allBytes = new ArrayList<Byte>(2048);
  13. int bufIndex = 0;
  14. int subDataLoop = 0;
  15. byte[] buf = new byte[DEFAULT_BUFFERSIZE];
  16. for (int i = 0; i < dataLen; i++) {
  17. buf[bufIndex] = data[i];
  18. if (++bufIndex == DEFAULT_BUFFERSIZE || i == dataLen - 1) {
  19. subDataLoop++;
  20. if (subDataLoop != 1) {
  21. for (byte b : DEFAULT_SPLIT) {
  22. allBytes.add(b);
  23. }
  24. }
  25. byte[] encryptBytes = encryptByPrivateKey(buf, privateKey);
  26. for (byte b : encryptBytes) {
  27. allBytes.add(b);
  28. }
  29. bufIndex = 0;
  30. if (i == dataLen - 1) {
  31. buf = null;
  32. } else {
  33. buf = new byte[Math.min(DEFAULT_BUFFERSIZE, dataLen - i - 1)];
  34. }
  35. }
  36. }
  37. byte[] bytes = new byte[allBytes.size()];
  38. {
  39. int i = 0;
  40. for (Byte b : allBytes) {
  41. bytes[i++] = b.byteValue();
  42. }
  43. }
  44. return bytes;
  45. }

公钥分段解密

  1. /**
  2. * 公钥分段解密
  3. *
  4. * @param encrypted 待解密数据
  5. * @param publicKey 密钥
  6. */
  7. public static byte[] decryptByPublicKeyForSpilt(byte[] encrypted, byte[] publicKey) throws Exception {
  8. int splitLen = DEFAULT_SPLIT.length;
  9. if (splitLen <= 0) {
  10. return decryptByPublicKey(encrypted, publicKey);
  11. }
  12. int dataLen = encrypted.length;
  13. List<Byte> allBytes = new ArrayList<Byte>(1024);
  14. int latestStartIndex = 0;
  15. for (int i = 0; i < dataLen; i++) {
  16. byte bt = encrypted[i];
  17. boolean isMatchSplit = false;
  18. if (i == dataLen - 1) {
  19. // 到data的最后了
  20. byte[] part = new byte[dataLen - latestStartIndex];
  21. System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);
  22. byte[] decryptPart = decryptByPublicKey(part, publicKey);
  23. for (byte b : decryptPart) {
  24. allBytes.add(b);
  25. }
  26. latestStartIndex = i + splitLen;
  27. i = latestStartIndex - 1;
  28. } else if (bt == DEFAULT_SPLIT[0]) {
  29. // 这个是以split[0]开头
  30. if (splitLen > 1) {
  31. if (i + splitLen < dataLen) {
  32. // 没有超出data的范围
  33. for (int j = 1; j < splitLen; j++) {
  34. if (DEFAULT_SPLIT[j] != encrypted[i + j]) {
  35. break;
  36. }
  37. if (j == splitLen - 1) {
  38. // 验证到split的最后一位,都没有break,则表明已经确认是split段
  39. isMatchSplit = true;
  40. }
  41. }
  42. }
  43. } else {
  44. // split只有一位,则已经匹配了
  45. isMatchSplit = true;
  46. }
  47. }
  48. if (isMatchSplit) {
  49. byte[] part = new byte[i - latestStartIndex];
  50. System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);
  51. byte[] decryptPart = decryptByPublicKey(part, publicKey);
  52. for (byte b : decryptPart) {
  53. allBytes.add(b);
  54. }
  55. latestStartIndex = i + splitLen;
  56. i = latestStartIndex - 1;
  57. }
  58. }
  59. byte[] bytes = new byte[allBytes.size()];
  60. {
  61. int i = 0;
  62. for (Byte b : allBytes) {
  63. bytes[i++] = b.byteValue();
  64. }
  65. }
  66. return bytes;
  67. }

私钥分段解密

  1. /**
  2. * 使用私钥分段解密
  3. *
  4. */
  5. public static byte[] decryptByPrivateKeyForSpilt(byte[] encrypted, byte[] privateKey) throws Exception {
  6. int splitLen = DEFAULT_SPLIT.length;
  7. if (splitLen <= 0) {
  8. return decryptByPrivateKey(encrypted, privateKey);
  9. }
  10. int dataLen = encrypted.length;
  11. List<Byte> allBytes = new ArrayList<Byte>(1024);
  12. int latestStartIndex = 0;
  13. for (int i = 0; i < dataLen; i++) {
  14. byte bt = encrypted[i];
  15. boolean isMatchSplit = false;
  16. if (i == dataLen - 1) {
  17. // 到data的最后了
  18. byte[] part = new byte[dataLen - latestStartIndex];
  19. System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);
  20. byte[] decryptPart = decryptByPrivateKey(part, privateKey);
  21. for (byte b : decryptPart) {
  22. allBytes.add(b);
  23. }
  24. latestStartIndex = i + splitLen;
  25. i = latestStartIndex - 1;
  26. } else if (bt == DEFAULT_SPLIT[0]) {
  27. // 这个是以split[0]开头
  28. if (splitLen > 1) {
  29. if (i + splitLen < dataLen) {
  30. // 没有超出data的范围
  31. for (int j = 1; j < splitLen; j++) {
  32. if (DEFAULT_SPLIT[j] != encrypted[i + j]) {
  33. break;
  34. }
  35. if (j == splitLen - 1) {
  36. // 验证到split的最后一位,都没有break,则表明已经确认是split段
  37. isMatchSplit = true;
  38. }
  39. }
  40. }
  41. } else {
  42. // split只有一位,则已经匹配了
  43. isMatchSplit = true;
  44. }
  45. }
  46. if (isMatchSplit) {
  47. byte[] part = new byte[i - latestStartIndex];
  48. System.arraycopy(encrypted, latestStartIndex, part, 0, part.length);
  49. byte[] decryptPart = decryptByPrivateKey(part, privateKey);
  50. for (byte b : decryptPart) {
  51. allBytes.add(b);
  52. }
  53. latestStartIndex = i + splitLen;
  54. i = latestStartIndex - 1;
  55. }
  56. }
  57. byte[] bytes = new byte[allBytes.size()];
  58. {
  59. int i = 0;
  60. for (Byte b : allBytes) {
  61. bytes[i++] = b.byteValue();
  62. }
  63. }
  64. return bytes;
  65. }

这样总算把遇见的问题解决了,项目中使用的方案是客户端公钥加密,服务器私钥解密,服务器开发人员说是出于效率考虑,所以还是自己写了个程序测试一下真正的效率

第一步:准备100条对象数据

  1. List<Person> personList=new ArrayList<>();
  2. int testMaxCount=100;//测试的最大数据条数
  3. //添加测试数据
  4. for(int i=0;i<testMaxCount;i++){
  5. Person person =new Person();
  6. person.setAge(i);
  7. person.setName(String.valueOf(i));
  8. personList.add(person);
  9. }
  10. //FastJson生成json数据
  11. String jsonData=JsonUtils.objectToJsonForFastJson(personList);
  12. Log.e("MainActivity","加密前json数据 ---->"+jsonData);
  13. Log.e("MainActivity","加密前json数据长度 ---->"+jsonData.length());

 

第二步生成秘钥对

  1. KeyPair keyPair=RSAUtils.generateRSAKeyPair(RSAUtils.DEFAULT_KEY_SIZE);
  2. // 公钥
  3. RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
  4. // 私钥
  5. RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

接下来分别使用公钥加密 私钥解密   私钥加密 公钥解密

  1. //公钥加密
  2. long start=System.currentTimeMillis();
  3. byte[] encryptBytes= RSAUtils.encryptByPublicKeyForSpilt(jsonData.getBytes(),publicKey.getEncoded());
  4. long end=System.currentTimeMillis();
  5. Log.e("MainActivity","公钥加密耗时 cost time---->"+(end-start));
  6. String encryStr=Base64Encoder.encode(encryptBytes);
  7. Log.e("MainActivity","加密后json数据 --1-->"+encryStr);
  8. Log.e("MainActivity","加密后json数据长度 --1-->"+encryStr.length());
  9. //私钥解密
  10. start=System.currentTimeMillis();
  11. byte[] decryptBytes= RSAUtils.decryptByPrivateKeyForSpilt(Base64Decoder.decodeToBytes(encryStr),privateKey.getEncoded());
  12. String decryStr=new String(decryptBytes);
  13. end=System.currentTimeMillis();
  14. Log.e("MainActivity","私钥解密耗时 cost time---->"+(end-start));
  15. Log.e("MainActivity","解密后json数据 --1-->"+decryStr);
  16. //私钥加密
  17. start=System.currentTimeMillis();
  18. encryptBytes= RSAUtils.encryptByPrivateKeyForSpilt(jsonData.getBytes(),privateKey.getEncoded());
  19. end=System.currentTimeMillis();
  20. Log.e("MainActivity","私钥加密密耗时 cost time---->"+(end-start));
  21. encryStr=Base64Encoder.encode(encryptBytes);
  22. Log.e("MainActivity","加密后json数据 --2-->"+encryStr);
  23. Log.e("MainActivity","加密后json数据长度 --2-->"+encryStr.length());
  24. //公钥解密
  25. start=System.currentTimeMillis();
  26. decryptBytes= RSAUtils.decryptByPublicKeyForSpilt(Base64Decoder.decodeToBytes(encryStr),publicKey.getEncoded());
  27. decryStr=new String(decryptBytes);
  28. end=System.currentTimeMillis();
  29. Log.e("MainActivity","公钥解密耗时 cost time---->"+(end-start));
  30. Log.e("MainActivity","解密后json数据 --2-->"+decryStr);

运行结果:

对比发现:私钥的加解密都很耗时,所以可以根据不同的需求采用不能方案来进行加解密。个人觉得服务器要求解密效率高,客户端私钥加密,服务器公钥解密比较好一点

 

加密后数据大小的变化:数据量差不多是加密前的1.5倍

版权声明:本文为whoislcj原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/whoislcj/p/5470095.html