Skip to content

Commit

Permalink
增强 RSAUtils 以解决 RSA 加密/解密长度限制 (elunez#604)
Browse files Browse the repository at this point in the history
  • Loading branch information
tsln1998 authored Mar 2, 2021
1 parent a0b6e85 commit 162cff2
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions eladmin-common/src/main/java/me/zhengjie/utils/RsaUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
Expand Down Expand Up @@ -80,7 +81,7 @@ public static String decryptByPublicKey(String publicKeyText, String text) throw
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] result = cipher.doFinal(Base64.decodeBase64(text));
byte[] result = doLongerCipherFinal(cipher, Base64.decodeBase64(text));
return new String(result);
}

Expand All @@ -98,7 +99,7 @@ public static String encryptByPrivateKey(String privateKeyText, String text) thr
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] result = cipher.doFinal(text.getBytes());
byte[] result = doLongerCipherFinal(cipher, text.getBytes());
return Base64.encodeBase64String(result);
}

Expand All @@ -116,7 +117,7 @@ public static String decryptByPrivateKey(String privateKeyText, String text) thr
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] result = cipher.doFinal(Base64.decodeBase64(text));
byte[] result = doLongerCipherFinal(cipher, Base64.decodeBase64(text));
return new String(result);
}

Expand All @@ -133,10 +134,23 @@ public static String encryptByPublicKey(String publicKeyText, String text) throw
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] result = cipher.doFinal(text.getBytes());
byte[] result = doLongerCipherFinal(cipher, text.getBytes());
return Base64.encodeBase64String(result);
}

private static byte[] doLongerCipherFinal(Cipher cipher, byte[] source) throws Exception {
int offset = 0;
int totalSize = source.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
while (totalSize - offset > 0) {
int size = Math.min(1024 / 8 - 11, totalSize - offset);
out.write(cipher.doFinal(source, offset, size));
offset += size;
}
out.close();
return out.toByteArray();
}

/**
* 构建RSA密钥对
*
Expand Down

0 comments on commit 162cff2

Please sign in to comment.