26.RSA加密解密在Java專案中的簡單應用

團長李雲龍發表於2019-03-28

做這個加密解密我是在網上找了好多的東西覺得都不大合適,於是自己整理了一下這個加密與解密的過程,同時把加解密與MD5的那個工具類都放出來,至於原理什麼的在前面的MD文章裡面已經說了一個大概

1.直接看如下測試程式碼

    public static void main(String[] args) {
        SpringApplication.run(WhblogApplication.class, args);
//        1.測試MD5
//        String password = "starry12345";
//        System.out.println(WHEncryptTools.MD5Encode(password,"utf-8")+"md5的加密是");
//        2.測試RSA
        try {
            KeyPair keyPair = WHEncryptTools.genKeyPair(1024);
            PrivateKey privateKey = keyPair.getPrivate();
            WHEncryptTools.saveKeyAsPemFormat(privateKey,"rsa_private_key.pem");
            System.out.println("新建私鑰是:"+new String(Base64.getEncoder().encode(privateKey.getEncoded())));

            PublicKey publicKey = keyPair.getPublic();
            WHEncryptTools.saveKeyAsPemFormat(publicKey,"rsa_public_key.pem");
            System.out.println("新建公鑰是:"+new String(Base64.getEncoder().encode(publicKey.getEncoded())));

            PrivateKey privateKey2 = WHEncryptTools.getPemPrivateKey("rsa_private_key.pem","RSA");
            System.out.println("讀取私鑰是:"+new String(Base64.getEncoder().encode(privateKey2.getEncoded())));

            PublicKey publicKey2 = WHEncryptTools.getPemPublicKey("rsa_public_key.pem");
            System.out.println("讀取公鑰是:"+new String(Base64.getEncoder().encode(publicKey2.getEncoded())));

            String teststr = "leewihong";
            byte [] testhello = WHEncryptTools.RSAEncrypt(teststr.getBytes(),publicKey);
            System.out.println("加密後:"+new String(testhello));

            byte [] decryhello = WHEncryptTools.RSADecrypt(testhello,privateKey);
            System.out.println("解密後:"+new String(decryhello));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
複製程式碼

這段程式碼是包含有MD5的測試在裡頭的,MD5想要測試直接把註釋去掉就可以了的

2.封裝的工具類如下程式碼所示

    package com.gz.whblog.utils;

import javax.crypto.Cipher;
import java.io.*;
import java.security.*;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMReader;
import org.bouncycastle.openssl.PEMWriter;
import org.bouncycastle.util.io.pem.PemObject;


public class WHEncryptTools {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }
    private static final String hexDigIts[] = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};

    /**
    * @description: MD5加密,用於儲存在資料庫中的密碼是MD5加密的
    *
    * @return: md5加密後的32位字串
    **/
    public static String MD5Encode(String orign,String charsetname){
        String resultString = null;
        try {
            resultString = new String(orign);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || charsetname.equals("")){
                resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
            }
            else {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return resultString;
    }

    public static String byteArrayToHexString(byte b[]){
        StringBuffer resultSb = new StringBuffer();
        for(int i = 0; i < b.length; i++){
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }

    public static String byteToHexString(byte b){
        int n = b;
        if(n < 0){
            n += 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigIts[d1] + hexDigIts[d2];
    }

    /**
    * @description: RSA加密,生成金鑰對
    *
    * @return:
    **/
    public static KeyPair genKeyPair(int KeyLength) throws Exception{
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        return keyPairGenerator.generateKeyPair();
    }

    /**
    * @description: 把生成的公鑰私鑰檔案儲存為PEM檔案
    *
    * @return: 
    **/
    public static void saveKeyAsPemFormat(Key key, String pem) throws IOException {
        PEMWriter pemWriter = new PEMWriter(new FileWriter(pem));
        pemWriter.writeObject(key);
        pemWriter.flush();
        pemWriter.close();
    }

    /**
    * @description: 從專案檔案結構中獲取私鑰pem檔案
    *
    * @return: 
    **/
    public static PrivateKey getPemPrivateKey(String filename, String algorithm) throws Exception {
        BufferedReader br = new BufferedReader(new FileReader(filename));
        Security.addProvider(new BouncyCastleProvider());
        PEMReader pp = new PEMReader(br);
        PemObject pem = pp.readPemObject();
        byte[] content = pem.getContent();
        pp.close();

        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(content);
        KeyFactory kf = KeyFactory.getInstance(algorithm);
        return kf.generatePrivate(spec);
    }

    /**
    * @description: 從專案資料夾獲取公鑰pem檔案
    *
    * @return:
    **/
    public static PublicKey getPemPublicKey(String pubKeyStr) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        BufferedReader br = new BufferedReader(new FileReader(pubKeyStr));
        Security.addProvider(new BouncyCastleProvider());
        PEMReader pp = new PEMReader(br);
        PemObject pem = pp.readPemObject();
        byte[] content = pem.getContent();
        pp.close();

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(content);
        RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(pubSpec);
        return pubKey;
    }

    /**
    * @description: 公鑰加密返回加密資料
    *
    * @return:
    **/

    public static byte[] RSAEncrypt(byte[] content, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");// java預設"RSA"="RSA/ECB/PKCS1Padding"
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(content);
    }

    /**
    * @description: // 私鑰解密得到返回的真實資料
    *
    * @return:
    **/

    public static byte[] RSADecrypt(byte[] content, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(content);
    }
    
}
複製程式碼

3.第三方依賴如下

<!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15 -->
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15</artifactId>
            <version>1.46</version>
        </dependency>
複製程式碼

4.輸出結果如下所示

26.RSA加密解密在Java專案中的簡單應用
寫的不好的地方,懇請大神斧正,謝謝。。。。

Github同步更新個人學習筆記,如果這篇文章對你有好處點個星星你不虧 WiHongNoteBook

相關文章