1. 程式人生 > >開罐即用系列-RSA加密解密

開罐即用系列-RSA加密解密

用途:適用於少量資料的加密解密(RSA加密特點:安全性高、成熟度高、速度慢、資源消耗高)

第一步:工具類(2個)

RSA工具類

import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * RSA工具類
 * @author szw
 * @version 1.0
 * @since JDK1.8
 */
public class RSAUtil {
    private static KeyPair keyPair;
    private static String publicKeyStr;
    private static String privateKeyStr;

    public static String getPublicKeyStr() {
        return publicKeyStr;
    }

    public static void setPublicKeyStr(String publicKeyStr) {
        RSAUtil.publicKeyStr = publicKeyStr;
    }

    public static String getPrivateKeyStr() {
        return privateKeyStr;
    }

    public static void setPrivateKeyStr(String privateKeyStr) {
        RSAUtil.privateKeyStr = privateKeyStr;
    }

    static {
        try {
            keyPair = getKeyPair();
        } catch (Exception e) {
            e.printStackTrace();
        }

        publicKeyStr = getPublicKey();
        privateKeyStr = getPrivateKey();
    }

    /**
     * 生成金鑰對
     * @return
     * @throws Exception
     */
    private static KeyPair getKeyPair() throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        return keyPair;
    }

    /**
     * 獲取公鑰(Base64編碼)
     * @return
     */
    private static String getPublicKey(){
        PublicKey publicKey = keyPair.getPublic();
        byte[] bytes = publicKey.getEncoded();
        return Base64Util.byteToBase64(bytes);
    }

    /**
     * 獲取私鑰(Base64編碼)
     * @return
     */
    private static String getPrivateKey(){
        PrivateKey privateKey = keyPair.getPrivate();
        byte[] bytes = privateKey.getEncoded();
        return Base64Util.byteToBase64(bytes);
    }


    /**
     * 公鑰加密
     * 加密後的內容經過了base64轉碼
     * @param msg
     * @return
     * @throws Exception
     */
    public static String publicEncrypt(String msg) throws Exception{
        byte[] content = msg.getBytes();
        byte[] keyBytes = Base64Util.base64ToBytes(publicKeyStr);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] bytes = cipher.doFinal(content);
        return Base64Util.byteToBase64(bytes);
    }

    /**
     * 私鑰解密
     *
     * @param publicEncrypt 經過base64轉碼的密文
     * @return
     * @throws Exception
     */
    public static String privateDecrypt(String publicEncrypt) throws Exception{
        byte[] content = Base64Util.base64ToBytes(publicEncrypt);
        byte[] keyBytes = Base64Util.base64ToBytes(privateKeyStr);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] bytes = cipher.doFinal(content);
        return new String(bytes);
    }

}

base64工具類

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.IOException;

/**
 * base64工具類
 * @author szw
 * @version 1.0
 * @since JDK1.8
 */
public class Base64Util {

    /**
     * 將位元組碼轉換成base64
     *
     * @param bytes
     * @return
     */
    public static String byteToBase64(byte[] bytes) {
        BASE64Encoder base64Encoder = new BASE64Encoder();
        return base64Encoder.encode(bytes);
    }

    /**
     * 將base64轉換成位元組碼
     * @param base64
     * @return
     * @throws IOException
     */
    public static byte[] base64ToBytes(String base64) throws IOException {
        BASE64Decoder base64Decoder = new BASE64Decoder();
        return base64Decoder.decodeBuffer(base64);
    }
}

使用方式:

用工具類生成RSA金鑰對儲存起來:

String publicKeyStr = RSAUtil.getPublicKeyStr();
String privateKeyStr = RSAUtil.getPrivateKeyStr();

使用金鑰對進行加密解密:

/**
 * 
 * @author sunziwen
 * 2018-08-13 11:04
 * @version 1.0
 **/
public class Main {
    public static void main(String args[]) throws Exception {
        String publicKeyStr = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5t9yr2YPa/Cmy2gUbItLxmSpkizcTH0z\n" +
                "YnBZ7x3n07HNuRPAe215tZtodfSoz9GxpLKgn9HrKan5zQN6ESJ2U21evcY0VZjWYMBY0X9oJNQq\n" +
                "FQyZwYVH78//yYzcDyZejVy54/SFeWUwv89Gy155I96ao0pao4CJh16sf/b7H60+idzmmye/o9PK\n" +
                "5JiiOSGEaNyMFFlmg11gTrBqHN/7PAHNc6V22a9GpMeKfO7qEljBEyfzgkxhC6JP1dOOqIS9iBRg\n" +
                "wIymZxYWQaRhVfhniRYQZKQYBr3uZ6zRi/np7C8M8TWK3riHey5y/U868XELzdAmgwFJz3mjcnZJ\n" +
                "Rze6SwIDAQAB";
        String privateKeyStr = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDm33KvZg9r8KbLaBRsi0vGZKmS\n" +
                "LNxMfTNicFnvHefTsc25E8B7bXm1m2h19KjP0bGksqCf0espqfnNA3oRInZTbV69xjRVmNZgwFjR\n" +
                "f2gk1CoVDJnBhUfvz//JjNwPJl6NXLnj9IV5ZTC/z0bLXnkj3pqjSlqjgImHXqx/9vsfrT6J3Oab\n" +
                "J7+j08rkmKI5IYRo3IwUWWaDXWBOsGoc3/s8Ac1zpXbZr0akx4p87uoSWMETJ/OCTGELok/V046o\n" +
                "hL2IFGDAjKZnFhZBpGFV+GeJFhBkpBgGve5nrNGL+ensLwzxNYreuId7LnL9TzrxcQvN0CaDAUnP\n" +
                "eaNydklHN7pLAgMBAAECggEBAJLhCXdpONp1CchSeNvtatHW7MKgY68N4Aj6bVzg68IUVksus8BS\n" +
                "j6HoMvcIJfXA9IFRWzsSM8gX6WJymdAY2qqM5D9bv6PNTmXTOS5fHgSALh2iHJevkWqSK6swQDgr\n" +
                "MvBAU8sgn2Hx7Ke62NE9U1hsoHjOLwfiGJzUsG3g1Tb6rWrKz+fyVBtwQE0GwsWPKpft1XfSuTNg\n" +
                "c8Jh+//wXqyn+k+MgTmdstnHb7zfhPC5CSzmhmuZLl68ry1HaFvPjQpAmcKjVKIgK+qkb2+RYz84\n" +
                "XHl2PInN3rggNmfP6lD8TF8i53BIv3ziksaITk4YK1AfLKb6Wjt7A1gCgoq9A1ECgYEA+KWd1vUo\n" +
                "0OM466CKioJD7/VSOvVR2QAdS3TiWclUVWjL6lOTBhJf0Y8oK9xy3+XNykwKF2YoFpkIikO5dX7l\n" +
                "NZTwJ2J66Ij006ocYlWtyUcBgJCIt7QTGSdxnvDdt25x1UXXbch2PaH7P4OPhdlWkeckJyQ0hycY\n" +
                "m3ktoEm5/dUCgYEA7bNFwv4KpbmXRpTZvpWi6uuDQnYIH6fb5Qozp0WbAZY2RjPpUpGz54loiusz\n" +
                "RRqdP9sr79GIARAuxvJAFRcnmZKcbrEQEFSzO0fFVX0f1HIfMrkce0Cpk8Y2RSkmeYmSvr1vlZ6d\n" +
                "QnuTzBV9HtJvtwQ9LbbBQkjCffQEQeeZR58CgYEAyaaXMaO1rGL64K1cbiRjMJJGVCZscI6VM4Lh\n" +
                "p2uOB45sAegxjnUMXIm7TIcGauqWUQAGFx/0Vw9ZS7jNCasV/LSDZ42InFmmJJsLVfyiamA5qaiO\n" +
                "GF3kNzwz+3Dgf0kE7LAtnI08x5M8jjAGD8lJWh6YxV2pdAqS/FP0WtAwFNkCgYAmEKJoUoRj+6+F\n" +
                "BwtDoPThB+wSNZKhdyEYsaSJ8fSbsXFplqCTr2+O8YtDS9z/AP8TncaQdg6AlRXYmCy48+dMiZTx\n" +
                "iPtYkifNo3WvdgUl4Uyrs8ci2b0ORBymwKs/pU9RqkZ3QFpQrjeB5CMQT4TCWzRs4KpcMgirYOtZ\n" +
                "nnwGYwKBgEmmGl5KHjeDvZx+WkYOV+LXzsvVaBxHFE/LFHD5srcoeSW2dyBK8q+RXwpFQsmh9Q58\n" +
                "ARb/hyWZ70V+XeTRKPPt9B4nYu1s40liZGFAf5Dutd7aDWL7H8FlBYhYa9u1wv4x5YtRKItNvwl6\n" +
                "G8id3M/BPGsJrOJrmhhFyOTiJc/V";
        /**
         * 待加密資料
         */
        String msg = "身先士卒";
        RSAUtil.setPublicKeyStr(publicKeyStr);
        RSAUtil.setPrivateKeyStr(privateKeyStr);
        /**
         * 公鑰加密
         */
        String publicEncrypt = RSAUtil.publicEncrypt(msg);
        /**
         * 私鑰解密
         */
        String privateDecrypt = RSAUtil.privateDecrypt(publicEncrypt);
    }

}