RSA 私钥加密,公钥解密


  1. public class RSATest {
  2. public static void main(String[] args) throws Exception {
  3. // 生成公钥和私钥
  4. KeyPair keyPair = generateKeyPair();
  5. PublicKey publicKey = keyPair.getPublic();
  6. PrivateKey privateKey = keyPair.getPrivate();
  7. // 要加密的信息
  8. String message = "This is a very long message that needs to be encrypted in chunks. It should be longer than a single RSA encryption block to demonstrate chunking.";
  9. // 加密
  10. byte[] encryptedMessage = encrypt(message.getBytes(), privateKey);
  11. //byte[] encryptedMessage = encrypt(Base64.getDecoder().decode("XXX"), privateKey);
  12. // 解密
  13. byte[] decryptedMessage = decrypt(encryptedMessage, publicKey);
  14. // 输出结果
  15. System.out.println("Original message: " + message);
  16. System.out.println("Decrypted message: " + new String(decryptedMessage));
  17. /* ----------- 以下测试序列化 ----------*/
  18. PublicKey publicKey2 = getPublicKey(convertPublic(publicKey));
  19. PrivateKey privateKey2 = getPrivateKey(convertPrivate(privateKey));
  20. // 加密
  21. byte[] encryptedMessage2 = encrypt(message.getBytes(), privateKey2);
  22. String dataStr = Base64.getEncoder().encodeToString(encryptedMessage2);
  23. System.out.println("密文: " + dataStr);
  24. // 解密
  25. byte[] decryptedMessage2 = decrypt(Base64.getDecoder().decode(dataStr), publicKey2);
  26. System.out.println("Original message2: " + message);
  27. System.out.println("Decrypted message2: " + new String(decryptedMessage2));
  28. }
  29. private static KeyPair generateKeyPair() throws Exception {
  30. KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
  31. keyGen.initialize(1024);
  32. return keyGen.generateKeyPair();
  33. }
  34. private static byte[] encrypt(byte[] message, Key publicKey) throws Exception {
  35. Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
  36. cipher.init(Cipher.ENCRYPT_MODE, publicKey);
  37. int maxLength = 109;
  38. List<byte[]> chunks = new ArrayList<>();
  39. for (int i = 0; i < message.length; i += maxLength) {
  40. byte[] chunk = new byte[Math.min(maxLength, message.length - i)];
  41. System.arraycopy(message, i, chunk, 0, chunk.length);
  42. chunks.add(cipher.doFinal(chunk));
  43. }
  44. return combineChunks(chunks);
  45. }
  46. private static byte[] decrypt(byte[] encryptedMessage, Key privateKey) throws Exception {
  47. Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
  48. cipher.init(Cipher.DECRYPT_MODE, privateKey);
  49. int chunkSize = 128; // 对于1024位的密钥
  50. List<byte[]> chunks = new ArrayList<>();
  51. for (int i = 0; i < encryptedMessage.length; i += chunkSize) {
  52. byte[] chunk = new byte[chunkSize];
  53. System.arraycopy(encryptedMessage, i, chunk, 0, chunkSize);
  54. chunks.add(cipher.doFinal(chunk));
  55. }
  56. return combineChunks(chunks);
  57. }
  58. private static byte[] combineChunks(List<byte[]> chunks) {
  59. int totalLength = chunks.stream().mapToInt(chunk -> chunk.length).sum();
  60. byte[] result = new byte[totalLength];
  61. int currentPosition = 0;
  62. for (byte[] chunk : chunks) {
  63. System.arraycopy(chunk, 0, result, currentPosition, chunk.length);
  64. currentPosition += chunk.length;
  65. }
  66. return result;
  67. }
  68. public static String convertPublic(PublicKey publicKey) {
  69. return Base64.getEncoder()
  70. .withoutPadding()
  71. .encodeToString(publicKey.getEncoded());
  72. }
  73. public static String convertPrivate(PrivateKey privateKey) {
  74. return Base64.getEncoder()
  75. .withoutPadding()
  76. .encodeToString(privateKey.getEncoded());
  77. }
  78. @SneakyThrows
  79. public static PublicKey getPublicKey(String sshPublicKey) {
  80. sshPublicKey = sshPublicKey.replace("\n", "");
  81. byte[] publicKeyBytes = Base64.getDecoder().decode(sshPublicKey);
  82. // 创建X509EncodedKeySpec对象
  83. X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
  84. return KeyFactory.getInstance("RSA").generatePublic(keySpec);
  85. }
  86. @SneakyThrows
  87. public static PrivateKey getPrivateKey(String sshPrivateKey) {
  88. sshPrivateKey = sshPrivateKey.replace("\n", "");
  89. byte[] byteKey = Base64.getDecoder().decode(sshPrivateKey);
  90. PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(byteKey);
  91. return KeyFactory.getInstance("RSA").generatePrivate(pkcs8EncodedKeySpec);
  92. }
  93. }

寒烟濡雨 2023年8月31日 22:08 收藏文档