java下RSA加密解密的使用

RSA简单介绍

一般来说,RSA是非对称加解密,有一对密钥,公钥进行加密,私钥进行解密。

实现过程

  1. JAVA中相关的类及作用

    • KeyPairGenerator用来生成KeyPair的密钥生成器.

      • 构造函数入参(string)为密钥类型,如 RSA,AES.
      • initialize(),用以初始化密钥生成器,入参为密钥长度,最低为512
      • genKeyPair(),生成密钥对
    • Cipher为编解码器,实现编解码的过程,编解码的入参和返回都是byte[]类型

      • getInstance为生成器函数,入参为密码类型,如 RSA,AES.
      • init 为初始化设置,设置工作模式和密钥。
      • doFinal返回最终结果
  2. 具体演示程序如下

    • 主要有三个函数,genKeyPair用来生成密钥,encrypt用来加密,decrypt用来解密。

    • 实现代码

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      public class AuthKeyPair {
      private static final String RSA = "RSA";
      public static void main(String... args) throws Exception {
      String data = "this is text for auth encode";
      KeyPair keyPair = genKeyPair(512);
      PublicKey publicKey = keyPair.getPublic();
      System.out.println("public key : " + stringBase64FromBytes(publicKey.getEncoded()));
      PrivateKey privateKey = keyPair.getPrivate();
      System.out.println("private key : " + stringBase64FromBytes(privateKey.getEncoded()));
      byte[] encryptBytes = encrypt(data.getBytes(), publicKey);
      System.out.println("加密后 : " + stringBase64FromBytes(encryptBytes));
      byte[] decryptBytes = decrypt(encryptBytes, privateKey);
      System.out.println("解密后 : " + new String(decryptBytes));
      System.out.println("原来的大小 : " + data.getBytes().length);
      System.out.println("加密后的大小 : " + encryptBytes.length);
      System.out.println("解密后的大小 : " + decryptBytes.length);
      System.out.println(stringBase64FromBytes(data.getBytes()).getBytes().length);
      }
      public static String stringBase64FromBytes(byte[] data) throws Exception {
      return new String(Base64.getEncoder().encode(data));
      }
      public static KeyPair genKeyPair(int keyLength) throws Exception {
      KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA);
      keyPairGenerator.initialize(keyLength);
      return keyPairGenerator.genKeyPair();
      }
      public static byte[] encrypt(byte[] content, PublicKey publicKey) throws Exception {
      Cipher cipher = Cipher.getInstance(RSA);
      cipher.init(Cipher.ENCRYPT_MODE, publicKey);
      return cipher.doFinal(content);
      }
      public static byte[] decrypt(byte[] content, PrivateKey privateKey) throws Exception {
      Cipher cipher = Cipher.getInstance(RSA);
      cipher.init(Cipher.DECRYPT_MODE, privateKey);
      return cipher.doFinal(content);
      }
      }
    • 运行结果