java RSA加密類

fp34 9年前發布 | 3K 次閱讀 Java 加密

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import javax.crypto.Cipher;

/**

  • RSA加密類
  • */ public class RSAEncrypt {

    public static void main(String[] args) {

     try {
         RSAEncrypt encrypt = new RSAEncrypt();
         String encryptText = "12345678";
         KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
         keyPairGen.initialize(1024);
         KeyPair keyPair = keyPairGen.generateKeyPair();
         // Generate keys
         RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 私鑰
         RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 公鑰
         byte[] e = encrypt.encrypt(publicKey, encryptText.getBytes());
         byte[] de = encrypt.decrypt(privateKey, e);
         System.out.println(encrypt.bytesToString(e));
         System.out.println();
    
         System.out.println(encrypt.bytesToString(de));
     } catch (Exception e) {
         e.printStackTrace();
     }
    

    }

    /**

    • byte數組轉為string
    • @param encrytpByte
    • @return */ protected String bytesToString(byte[] encrytpByte) { String result = ""; for (Byte bytes : encrytpByte) {

       result += (char) bytes.intValue();
      

      } return result; }

      /**

    • 加密方法
    • @param publicKey
    • @param obj
    • @return */ protected byte[] encrypt(RSAPublicKey publicKey, byte[] obj) { if (publicKey != null) {

       try {
           Cipher cipher = Cipher.getInstance("RSA");
           cipher.init(Cipher.ENCRYPT_MODE, publicKey);
           return cipher.doFinal(obj);
       } catch (Exception e) {
           e.printStackTrace();
       }
      

      } return null; }

      /**

    • 解密方法
    • @param privateKey
    • @param obj
    • @return */ protected byte[] decrypt(RSAPrivateKey privateKey, byte[] obj) { if (privateKey != null) {
       try {
           Cipher cipher = Cipher.getInstance("RSA");
           cipher.init(Cipher.DECRYPT_MODE, privateKey);
           return cipher.doFinal(obj);
       } catch (Exception e) {
           e.printStackTrace();
       }
      
      } return null; } }</pre>
 本文由用戶 fp34 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!