RSA加密解密

package utils;

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

/**
 * RSA加密解密类
 */
public class RSASecurityCode {
    // 非对称加密密钥算法
    private static final String ALGORITHM="RSA";

    // 密钥长度,用来初始化
    private static final int KEY_SIZE=1024;

    // 公钥
    private final byte[] publicKey;

    // 私钥
    private final byte[] privateKey;

    /**
     *
     * 构造函数,在其中生成公钥和私钥
     */
    public RSASecurityCode() throws Exception{
        // 得到密钥对生成器
        KeyPairGenerator kpg=KeyPairGenerator.getInstance(ALGORITHM);
        kpg.initialize(KEY_SIZE);

        // 得到密钥对
        KeyPair kp=kpg.generateKeyPair();

        // 得到公钥
        RSAPublicKey keyPublic=(RSAPublicKey)kp.getPublic();
        publicKey=keyPublic.getEncoded();

        // 得到私钥
        RSAPrivateKey keyPrivate=(RSAPrivateKey)kp.getPrivate();
        privateKey=keyPrivate.getEncoded();
    }

    /**
     *
     * 用公钥对字符串进行加密
     */
    public byte[] getEncryptArray(String originalString, byte[] publicKeyArray) throws Exception{
        // 得到公钥
        X509EncodedKeySpec keySpec=new X509EncodedKeySpec(publicKeyArray);
        KeyFactory kf=KeyFactory.getInstance(ALGORITHM);
        PublicKey keyPublic=kf.generatePublic(keySpec);
        // 加密数据
        Cipher cp=Cipher.getInstance(ALGORITHM);
        cp.init(Cipher.ENCRYPT_MODE, keyPublic);
        return cp.doFinal(originalString.getBytes());
    }


    /**
     *
     * 使用私钥进行解密
     */
    public String getDecryptString(byte[] encryptedDataArray) throws Exception{
        // 得到私钥
        PKCS8EncodedKeySpec keySpec=new PKCS8EncodedKeySpec(privateKey);
        KeyFactory kf=KeyFactory.getInstance(ALGORITHM);
        PrivateKey keyPrivate=kf.generatePrivate(keySpec);
        // 解密数据
        Cipher cp=Cipher.getInstance(ALGORITHM);
        cp.init(Cipher.DECRYPT_MODE, keyPrivate);
        byte[] arr=cp.doFinal(encryptedDataArray);
        // 得到解密后的字符串
        return new String(arr);
    }

    public byte[] getPublicKey() {
        return publicKey;
    }

    public static void main(String[] arr) throws Exception{
        String str="你好,世界! Hello,world!";
        System.out.println("准备用公钥加密的字符串为:"+str);

        // 用公钥加密
        RSASecurityCode rsaCoder=new RSASecurityCode();
        byte[] publicKey=rsaCoder.getPublicKey();
        byte[] encryptArray=rsaCoder.getEncryptArray(str, publicKey);

        System.out.print("用公钥加密后的结果为:");
        for(byte b:encryptArray){
            System.out.print(b);
        }
        System.out.println();

        // 用私钥解密
        String str1=rsaCoder.getDecryptString(encryptArray);
        System.out.println("用私钥解密后的字符串为:"+str1);
    }
}

原文地址:https://www.cnblogs.com/zhouheblog/p/12883122.html