Java加密算法筆記--RSA算法實現

Java加密算法筆記--RSA算法實現

import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

/**
 * 一、公鑰加密,私鑰解密用於信息加密
 * 二、私鑰加密,公鑰解密用於數字簽名
 */
public class RSA {
    /**
     * 測試方法
     */
    public static void main(String[] args) {
//        Map<String, Object> map = new HashMap<String, Object>();
//        map = RSA.init();
//        System.out.println("公鑰:"+RSA.getPublicKey(map));
//        System.out.println("私鑰:"+RSA.getPrivateKey(map));
        //由前四行代碼得到公、私密鑰
        String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCLNbmKl9/gLn7Bef/xtUkshC1WyrLZLRpXCcFYR1gQi0isWsZBTicC4efBOkkNG3r+1ue0gvtuU/tjREFGf4Y7HaKHGb5tNCOlMNeNjM5YLRwLFqrUSsQyD4rj4eua1ltearr24R0HilnTvnQm6Z/UY0s21vdOUFQBPY0GNAa+0wIDAQAB";
        String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIs1uYqX3+AufsF5//G1SSyELVbKstktGlcJwVhHWBCLSKxaxkFOJwLh58E6SQ0bev7W57SC+25T+2NEQUZ/hjsdoocZvm00I6Uw142MzlgtHAsWqtRKxDIPiuPh65rWW15quvbhHQeKWdO+dCbpn9RjSzbW905QVAE9jQY0Br7TAgMBAAECgYBcYhbzpr5no/Nyqmf0G/6nkEAWbQYrogbs5AhvcUk8EXL1DnirNhYlj42hafC4xhflrvCtlo8NNKaLxewbwN1uuzG8A2jd+ROEXlx5HDh2ZluhtHzL/SmNcJXo684xAl2pCNVBjDcW48PcIBijke/sTVHTDsDCukLKDPUOM/mKIQJBAL96k4+jBscazsJiuZ6C3RFDVtRRDpf1dMgLgxcx63bAXkA2Arau0J49IAYmSVJoDXqDoJKWdXJVh9vHSkhN/48CQQC6Hk1/G0Y0nOylf6NOp0oMgc0A+etnwxHKqwtctPKjEYcJx2fzALzTtCoySLYXX7gLnPIQXpQBTUysG5skBKp9AkEAiSQm6fqu0Q4fRlRlc+VwpnufhgPkOuw/z0OHiaZkajJPjxfgC63bl2paNG1ZmJ8UAEqkSDlhNxmRa9UqG+1ZewJASaQxz6gwCCNLM1SkfjuM/hPh1JAOh9jUUleJQF5MXx9RSho/VBQnorB3vbutaOQzw0yPLtDtSPKX8sVdhkveVQJAIDsJP5X8Tey6zXTUISor7PF0TSiKdE4k0IwKoy9y8HmQ+AU8+xyr/iOt5lvaGxKlBK8N/7yCw5H4qHnJaHT+Bg==";
        
        String str = "你好goldlone, RSA!";
        // 公鑰加密,私鑰解密
        String enStr1 = RSA.encryptByPublic(str, publicKey);
        System.out.println("公鑰加密後:"+enStr1);
        String deStr1 = RSA.decryptByPrivate(enStr1, privateKey);
        System.out.println("私鑰解密後:"+deStr1);
        // 私鑰加密,公鑰解密
        String enStr2 = RSA.encryptByPrivate(str, privateKey);
        System.out.println("私鑰加密後:"+enStr2);
        String deStr2 = RSA.decryptByPublic(enStr2, publicKey);
        System.out.println("公鑰解密後:"+deStr2);
        // 產生簽名  
        String sign = sign(enStr2, privateKey);
        System.out.println("簽名:"+sign);
        // 驗證簽名 
        boolean status = verify(enStr2, publicKey, sign);
        System.out.println("狀態:"+status);
        
    }
    
    //定義加密方式
    public static final String KEY_RSA = "RSA";
    //定義公鑰關鍵詞
    public static final String KEY_RSA_PUBLICKEY = "RSAPublicKey";
    //定義私鑰關鍵詞
    public static final String KEY_RSA_PRIVATEKEY = "RSAPrivateKey";
    //定義簽名算法
    private final static String KEY_RSA_SIGNATURE = "MD5withRSA";
    
    /**
     * 生成公私密鑰對
     */
    public static Map<String, Object> init() {  
        Map<String, Object> map = null;
        try {
            KeyPairGenerator generator = KeyPairGenerator.getInstance(KEY_RSA);
            //設置密鑰對的bit數,越大越安全,但速度減慢,通常使用512或1024
            generator.initialize(1024);
            KeyPair keyPair = generator.generateKeyPair();
            // 獲取公鑰  
            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
            // 獲取私鑰  
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
            // 將密鑰對封裝爲Map
            map = new HashMap<String, Object>();
            map.put(KEY_RSA_PUBLICKEY, publicKey);
            map.put(KEY_RSA_PRIVATEKEY, privateKey);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        
        return map;
    }
    
     /** 
     * 獲取Base64編碼的公鑰字符串
     */
    public static String getPublicKey(Map<String, Object> map) {
        String str = "";
        Key key = (Key) map.get(KEY_RSA_PUBLICKEY);
        str = encryptBase64(key.getEncoded());
        return str;  
    }
  
    /** 
     * 獲取Base64編碼的私鑰字符串 
     */
    public static String getPrivateKey(Map<String, Object> map) {
        String str = "";
        Key key = (Key) map.get(KEY_RSA_PRIVATEKEY);
        str = encryptBase64(key.getEncoded());
        return str;
    }
  
    /** 
     * BASE64 解碼 
     * @param key 須要Base64解碼的字符串 
     * @return 字節數組 
     */  
    public static byte[] decryptBase64(String key) {
        return Base64.getDecoder().decode(key);
    }
  
    /** 
     * BASE64 編碼 
     * @param key 須要Base64編碼的字節數組 
     * @return 字符串 
     */  
    public static String encryptBase64(byte[] key) {
        return new String(Base64.getEncoder().encode(key));
    }
    
    /**
     * 公鑰加密
     * @param encryptingStr
     * @param publicKey
     * @return
     */
    public static String encryptByPublic(String encryptingStr, String publicKeyStr){
        try {
            // 將公鑰由字符串轉爲UTF-8格式的字節數組
            byte[] publicKeyBytes = decryptBase64(publicKeyStr);
            // 得到公鑰  
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
            // 取得待加密數據
            byte[] data = encryptingStr.getBytes("UTF-8");
            KeyFactory factory;
            factory = KeyFactory.getInstance(KEY_RSA);
            PublicKey publicKey = factory.generatePublic(keySpec);
            // 對數據加密  
            Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            // 返回加密後由Base64編碼的加密信息
            return encryptBase64(cipher.doFinal(data));
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return null;
    }
    
    /**
     * 私鑰解密
     * @param encryptedStr
     * @param privateKey
     * @return
     */
    public static String decryptByPrivate(String encryptedStr, String privateKeyStr){
        try {
            // 對私鑰解密  
            byte[] privateKeyBytes = decryptBase64(privateKeyStr);
            // 得到私鑰 
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
            // 得到待解密數據
            byte[] data = decryptBase64(encryptedStr);
            KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
            PrivateKey privateKey = factory.generatePrivate(keySpec);
            // 對數據解密
            Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            // 返回UTF-8編碼的解密信息
            return new String(cipher.doFinal(data), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return null;
    }

    /**
     * 私鑰加密
     * @param encryptingStr
     * @param privateKey
     * @return
     */
    public static String encryptByPrivate(String encryptingStr, String privateKeyStr){
        try {
            byte[] privateKeyBytes = decryptBase64(privateKeyStr);
            // 得到私鑰  
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes); 
            // 取得待加密數據
            byte[] data = encryptingStr.getBytes("UTF-8");
            KeyFactory factory = KeyFactory.getInstance(KEY_RSA);  
            PrivateKey privateKey = factory.generatePrivate(keySpec); 
            // 對數據加密 
            Cipher cipher = Cipher.getInstance(factory.getAlgorithm());  
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            // 返回加密後由Base64編碼的加密信息
            return encryptBase64(cipher.doFinal(data));  
        } catch (Exception e) {
            e.printStackTrace();  
        }
        
        return null;
    }
    
    /**
     * 公鑰解密
     * @param encryptedStr
     * @param privateKey
     * @return
     */
    public static String decryptByPublic(String encryptedStr, String publicKeyStr){
        try {
            // 對公鑰解密  
            byte[] publicKeyBytes = decryptBase64(publicKeyStr);
            // 取得公鑰  
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
            // 取得待加密數據
            byte[] data = decryptBase64(encryptedStr);
            KeyFactory factory = KeyFactory.getInstance(KEY_RSA);  
            PublicKey publicKey = factory.generatePublic(keySpec);
            // 對數據解密  
            Cipher cipher = Cipher.getInstance(factory.getAlgorithm());  
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            // 返回UTF-8編碼的解密信息
            return new String(cipher.doFinal(data), "UTF-8");  
        } catch (Exception e) {  
            e.printStackTrace();  
        }
        
        return null;
    }
    
    /**
     * 用私鑰對加密數據進行簽名
     * @param encryptedStr
     * @param privateKey
     * @return
     */
    public static String sign(String encryptedStr, String privateKey) {
        String str = "";  
        try {
            //將私鑰加密數據字符串轉換爲字節數組
            byte[] data = encryptedStr.getBytes();
            // 解密由base64編碼的私鑰  
            byte[] bytes = decryptBase64(privateKey);  
            // 構造PKCS8EncodedKeySpec對象  
            PKCS8EncodedKeySpec pkcs = new PKCS8EncodedKeySpec(bytes);  
            // 指定的加密算法  
            KeyFactory factory = KeyFactory.getInstance(KEY_RSA);  
            // 取私鑰對象  
            PrivateKey key = factory.generatePrivate(pkcs);  
            // 用私鑰對信息生成數字簽名  
            Signature signature = Signature.getInstance(KEY_RSA_SIGNATURE);  
            signature.initSign(key);  
            signature.update(data);  
            str = encryptBase64(signature.sign());  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return str;  
    }
    
    /**
     * 校驗數字簽名 
     * @param encryptedStr
     * @param publicKey
     * @param sign
     * @return 校驗成功返回true,失敗返回false
     */
    public static boolean verify(String encryptedStr, String publicKey, String sign) {  
        boolean flag = false;
        try {
            //將私鑰加密數據字符串轉換爲字節數組
            byte[] data = encryptedStr.getBytes();
            // 解密由base64編碼的公鑰  
            byte[] bytes = decryptBase64(publicKey);  
            // 構造X509EncodedKeySpec對象  
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);  
            // 指定的加密算法  
            KeyFactory factory = KeyFactory.getInstance(KEY_RSA);  
            // 取公鑰對象  
            PublicKey key = factory.generatePublic(keySpec);  
            // 用公鑰驗證數字簽名  
            Signature signature = Signature.getInstance(KEY_RSA_SIGNATURE);  
            signature.initVerify(key);  
            signature.update(data);  
            flag = signature.verify(decryptBase64(sign));
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return flag;  
    }
}

運行結果:
公鑰加密後:TWWRIh4NIqslqWtT/1R4HbIrpXQRUU5Q4oJxa60+k11TINsxZVr9ox+aPZkjtlKRa5oaUqIsZysOwn4kxiDe6ielxUjQENz/lWc8pp5YpVR5INR3qP33aVXFHiqYHvkkXbhaDUlb4J0jYZDKLPgCUe3aG5vQN+DfdFcYnW2K9+8=
私鑰解密後:你好goldlone, RSA!
私鑰加密後:iND60pcTmbQqx0BcmfXtw+HY8XkCUFS9ifhRqL9IZpeimdRMlB3hPRK6m5ojmG+c836eX6+j1OYsmtp6ZfGbEoYCsiD1II+Xsx9vOfv42uf8yN3jlXXs4L5ybN65oB/LsuSsIvg1df72HU59mbPEQAqP5AHfnHImtRqN9DtE/Dg=
公鑰解密後:你好goldlone, RSA!
簽名:MGZDwjkFGs94MXrwcnhtcq97dnh5g0rGVcL0PuMgsOQfDYSpK129BlpoKCaHrqgXieg9ZfLaCFXaiQi74emAtGIPxODHl4DDiz7UEDABGZ5P+kQwHk0QTOVg5cBpwKkkdz3qka99ECaz1+ufAPX32wc4jcj1XcQPEj2gbnYsyPo=
狀態:truejava

相關文章
相關標籤/搜索