RSA加解密

1. 问题

今天在写一段RSA加解密的代码,代码本身不复杂。

  private static final String RSA = "RSA";
  private static final String UTF8 = "UTF-8";
  private static final String KEY_STORE = "PKCS12";
  private static final String X509 = "X.509";


  private static final int MAX_ENCRYPT_BLOCK = 117;
  private static final int MAX_DECRYPT_BLOCK = 128;

  public static byte[] encryptToBase64(byte[] originalContent, Key key) throws NoSuchPaddingException,
      NoSuchAlgorithmException, InvalidKeyException, IOException, BadPaddingException, IllegalBlockSizeException {
    Cipher cipher = Cipher.getInstance(key.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, key);
    //cipher一次能加密的长度有限制,因此需要分段加密
    byte[] originalBytes = originalContent;
    int totalLength = originalBytes.length;
    int offset = 0;
    ByteArrayOutputStream resultStream = new ByteArrayOutputStream();
    while (totalLength > offset) {
      byte[] encryptedBlock = cipher.doFinal(
          originalBytes, offset, Math.min(totalLength - offset, RSAUtils.MAX_ENCRYPT_BLOCK));
      resultStream.write(encryptedBlock);

      offset = offset + RSAUtils.MAX_ENCRYPT_BLOCK;
    }
    
    byte[] encryptedContent = resultStream.toByteArray();
    return encryptedContent;
  }

  public static byte[] decryptFromBase64(byte[] encryptedContent, Key key) throws NoSuchPaddingException,
      NoSuchAlgorithmException, InvalidKeyException, IOException, BadPaddingException, IllegalBlockSizeException {
    Cipher cipher = Cipher.getInstance(key.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, key);
    //cipher一次能解密的长度有限制,因此需要分段解密
    byte[] encryptedBytes = encryptedContent;
    int totalLength = encryptedBytes.length;
    int offset = 0;
    ByteArrayOutputStream resultStream = new ByteArrayOutputStream();
    while (totalLength > offset) {
      int blockLength = Math.min(totalLength - offset, RSAUtils.MAX_DECRYPT_BLOCK);
      byte[] decryptedBlock = cipher.doFinal(encryptedBytes, offset, blockLength);
      resultStream.write(decryptedBlock);

      offset = offset + RSAUtils.MAX_DECRYPT_BLOCK;
    }
    resultStream.close();
    byte[] originalContent = resultStream.toByteArray();
    return originalContent;
  }

但是在执行单元测试的时候,总是报如下的错误

javax.crypto.BadPaddingException: Decryption error

    at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:379)
    at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:290)
    at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:365)
    at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:391)
    at javax.crypto.Cipher.doFinal(Cipher.java:2226)
    at wang.afrag.base.util.RSAUtils.decryptFromBase64(RSAUtils.java:72)
    at wang.afrag.base.util.RSAUtilsTest.testEncrypt(RSAUtilsTest.java:86)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:212)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:208)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.util.ArrayList.forEach(ArrayList.java:1259)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.util.ArrayList.forEach(ArrayList.java:1259)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)

2. 解决的方法

经过一番折腾,总算是找到了原因,在这里记录下来。

主要的原因在于加密和解密是的block size,也就是 MAX_ENCRYPT_BLOCK 和 MAX_DECRYPT_BLOCK 这两个常量的值。这两个值必须和使用的密钥的长度匹配。 我使用的密钥是2048 bit的密钥,因此这两个值设置的长度分别应该分别设置为245和256。

3. 根本的原因

在进行RSA加密的时候,必须考虑密钥长度,明文长度和密文长度。

3.1 密钥及密钥长度

在RSA中,我们常说的密钥,其实指的是 (公钥 + 模值)、或(私钥 + 模值)中的一组。 这一组中的数据是需要配合起来使用的。

我们所说的密钥长度,指的是模值的位长度。目前主流的密钥长度是在1024bit以上,上不封顶。

3.2 加解密数据块的长度

由于密钥的长度是有限的,因此一次能够加/解密的长度也是有限的,和密钥的长度是相同的。但是要注意到,我们所说的密钥长度,单位是bit。但是我们在计算明文或者密文的长度的时候,通常单位是byte,因此要除以8。比如我用的密钥长度是2048,除以8之后为256, 因此我一次能够加密或者解密的数据的最大长度是256个byte。如果需要加密或者解密的数据多于这个值怎么办?答案是分块处理,前面代码中就是这样处理的。

那为什么加密的数据块大小和解密的数据块大小不一致呢?因为在加密的时候,我们需要在明文中填充一些随机数,这样每次产生的密文都会发生变化,这个过程称为padding。在加密的过程中,有各种各样的padding标准,在前面的代码中,采用的是默认的PKCS1Padding标准,这个标准中生成的随机数要占用11个字节,因此明文最长只能取245个字节,合起来是256个字节。

4 其他

在RSA中,还有很多其他的Padding类型,例如使用OAEP算法的OAEPWITHSHA-256ANDMGF1PADDING等,这些Padding对应的密文长度,就需要各位自己去发现了……

你可能感兴趣的:(RSA加解密)