RSA加密java工具


import javax.crypto.Cipher;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class RSAUtils {

    private static String ALGORITHM = "RSA";
    private static int KEY_SIZE = 1024;
    private static String SEED = "msat";

    /**
     * 生成公鑰、私鑰
     * @return 公鑰私鑰
     */
    public static String[] generateKeys() throws NoSuchAlgorithmException {
        //1.初始化密鑰對生成器
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
        keyPairGenerator.initialize(KEY_SIZE,new SecureRandom(Base64Utils.encrypt(SEED.getBytes()).getBytes()));
        //2.生成密鑰對
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        //3.base64編碼公鑰、私鑰 返回
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();
        String[] result = new String[2];
        result[0] = Base64Utils.encrypt(publicKey.getEncoded());//公鑰
        result[1] = Base64Utils.encrypt(privateKey.getEncoded());
        return result;
    }

    /**
     * 私鑰加密
     * @param content 被加密內容
     * @param keyPrivateBase64 私鑰(base64加密)
     */
    public static String encryptByPrivate(String content,String keyPrivateBase64) throws Exception {
        RSAPrivateKey privateKey = obtainPrivateKey(keyPrivateBase64);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE,privateKey);
        byte[] encoded = cipher.doFinal(content.getBytes("UTF-8"));
        return Base64Utils.encrypt(encoded);
    }

    /**
     * 私鑰解密
     * @param encodedContent
     * @param keyPrivateBase64
     * @return
     */
    public static String decryptByPrivate(String encodedContent,String keyPrivateBase64) throws Exception {
        RSAPrivateKey privateKey = obtainPrivateKey(keyPrivateBase64);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE,privateKey);
        byte[] bytes = cipher.doFinal(Base64Utils.decrypt(encodedContent));
        return new String(bytes);
    }

    private static RSAPrivateKey obtainPrivateKey(String keyPrivateBase64) throws Exception {
        byte[] keyBytes = Base64Utils.decrypt(keyPrivateBase64);
        return (RSAPrivateKey) KeyFactory.getInstance(ALGORITHM)
                .generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
    }

    /**
     * 公鑰加密
     * @param content 被加密內容
     * @param keyPublicBase64 公鑰(base64加密)
     * @return
     */
    public static String encryptByPublic(String content,String keyPublicBase64) throws Exception {
        RSAPublicKey publicKey = obtainPublicKey(keyPublicBase64);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE,publicKey);
        byte[] encoded = cipher.doFinal(content.getBytes("utf-8"));
        return Base64Utils.encrypt(encoded);
    }

    /**
     * 公鑰解密
     * @param encodedContent
     * @param keyPublicBase64
     * @return
     */
    public static String decryptByPublic(String encodedContent,String keyPublicBase64) throws Exception {
        RSAPublicKey publicKey = obtainPublicKey(keyPublicBase64);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE,publicKey);
        return new String(cipher.doFinal(Base64Utils.decrypt(encodedContent)));
    }

    private static RSAPublicKey obtainPublicKey(String keyPublicBase64) throws Exception {
        byte[] keyBytes = Base64Utils.decrypt(keyPublicBase64);
        return (RSAPublicKey) KeyFactory.getInstance(ALGORITHM)
                .generatePublic(new X509EncodedKeySpec(keyBytes));
    }

    /**
     * 存儲key到文件
     * @param filePath 文件路徑
     * @param keyBase64  base64編碼的key
     * @return true
     */
    public static boolean storeKey(String filePath,String keyBase64) throws IOException {
        File target = new File(filePath);
        if (target.isDirectory())
            throw new RuntimeException("filePath should not be a dir path");
        if (!target.exists())
            target.createNewFile();
        Files.write(target.toPath(),keyBase64.getBytes());
        return true;
    }

    /**
     * 從文件讀取key
     * @param filePath
     * @return
     * @throws IOException
     */
    public static String readKey(String filePath) throws IOException {
        return new String(Files.readAllBytes(new File(filePath).toPath()));
    }
}

測試:

@Test
public void test() throws Exception {
    String content = "aaabbbccc";
    String[] generateKeys = RSAUtils.generateKeys();
    String publicKey = generateKeys[0];
    String privateKey = generateKeys[1];
    System.out.println("原始內容:" + content);
    System.out.println("pubicKey:" + publicKey);
    System.out.println("privateKey:" + privateKey);
    //私鑰加密
    String encoded = RSAUtils.encryptByPrivate(content, privateKey);
    System.out.println("私鑰加密後:" + encoded);
    System.out.println("公鑰解密後:" + RSAUtils.decryptByPublic(encoded,publicKey));
    //公鑰加密
    String pubEncoded = RSAUtils.encryptByPublic(content,publicKey);
    System.out.println("公鑰加密後:" + pubEncoded);
    System.out.println("私鑰解密後:" + RSAUtils.decryptByPrivate(pubEncoded,privateKey));
    //將key寫入文件
    RSAUtils.storeKey("id_rsa",privateKey);//私鑰
    RSAUtils.storeKey("id_rsa.pub",publicKey);//公鑰
    System.out.println("讀取到公鑰:" + RSAUtils.readKey("id_rsa.pub"));
    System.out.println("讀取到私鑰:" + RSAUtils.readKey("id_rsa"));
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章