RSA和AES加密解密

1.RSA加密

会生成一个公钥和一个私钥,一般都是用公钥加密,私钥解密

该工具类提供公钥加密解密,私钥加密解密

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.crypto.Cipher;

public class RSAUtils {

    private static String PRIVATE_KEY;
    private static String PUBLIC_KEY;

    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    /**
     * 加密算法RSA
     */
    private static final String KEY_ALGORITHM = "RSA";

    /**
     * 初始化
     */
    public static void init() throws Exception {
        String[] keys = getKeys();
        RSAUtils.setPublicKey(keys[0]);
        RSAUtils.setPrivateKey(keys[1]);
    }

    public static String getPrivateKey() {
        return PRIVATE_KEY;
    }


    public static void setPrivateKey(String privateKey) {
        PRIVATE_KEY = privateKey;
    }

    public static String getPublicKey() {
        return PUBLIC_KEY;
    }

    public static void setPublicKey(String publicKey) {
        PUBLIC_KEY = publicKey;
    }

    /**
     * 生成公钥和私钥
     *
     * @throws Exception return {公钥,私钥}
     */
        public static String[] getKeys() throws Exception {
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
            keyPairGen.initialize(1024);
       KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

        String publicKeyStr = getPublicKeyStr(publicKey);
        String privateKeyStr = getPrivateKeyStr(privateKey);

        return new String[]{publicKeyStr, privateKeyStr};

    }

    /**
     * 使用模和指数生成RSA公钥
     * 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA
     * /None/NoPadding】
    *
     * @param modulus  模
     * @param exponent 公钥指数
     * @return
     */
    public static RSAPublicKey getPublicKey(String modulus, String exponent) {
        try {
            BigInteger b1 = new BigInteger(modulus);
            BigInteger b2 = new BigInteger(exponent);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
            return (RSAPublicKey) keyFactory.generatePublic(keySpec);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 使用模和指数生成RSA私钥
     * 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA
     * /None/NoPadding】
     *
     * @param modulus  模
     * @param exponent 指数
     * @return
     */
    public static RSAPrivateKey getPrivateKey(String modulus, String exponent) {
        try {
            BigInteger b1 = new BigInteger(modulus);
            BigInteger b2 = new BigInteger(exponent);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2);
            return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 公钥加密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static String encryptByPublicKey(String data) throws Exception {
        byte[] dataByte = data.getBytes();
        byte[] keyBytes = Base64Utils.decode(PUBLIC_KEY);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicK = keyFactory.generatePublic(x509KeySpec);
        // 对数据加密
        // Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, publicK);
        int inputLen = dataByte.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(dataByte, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(dataByte, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return Base64Utils.encode(encryptedData);
    }

    /**
     * 私钥加密
    */
    public static String encryptByPrivateKey(String data) throws Exception {
        byte[] dataByte = data.getBytes();
        byte[] keyBytes = Base64Utils.decode(PRIVATE_KEY);

        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        // 对数据加密
        // Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, privateK);
        int inputLen = dataByte.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
       int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(dataByte, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(dataByte, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return Base64Utils.encode(encryptedData);
    }

    /**
     * 私钥解密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static String decryptByPrivateKey(String data) throws Exception {
        byte[] encryptedData = Base64Utils.decode(data);
        byte[] keyBytes = Base64Utils.decode(PRIVATE_KEY);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        // Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

        cipher.init(Cipher.DECRYPT_MODE, privateK);
        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher
                        .doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher
                        .doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return new String(decryptedData);
    }

    /**
     * 公钥解密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static String decryptByPublicKey(String data) throws Exception {
        byte[] encryptedData = Base64Utils.decode(data);
        byte[] keyBytes = Base64Utils.decode(PUBLIC_KEY);

        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicK = keyFactory.generatePublic(x509KeySpec);

        // Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

        cipher.init(Cipher.DECRYPT_MODE, publicK);
        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher
                        .doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher
                        .doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return new String(decryptedData);
    }

    /**
     * 获取模数和密钥
    *
     * @return
     */
    public static Map getModulusAndKeys() {

        Map map = new HashMap();

        try {
            InputStream in = RSAUtils.class
                    .getResourceAsStream("/rsa.properties");
            Properties prop = new Properties();
            prop.load(in);

            String modulus = prop.getProperty("modulus");
            String publicKey = prop.getProperty("publicKey");
            String privateKey = prop.getProperty("privateKey");

            in.close();

            map.put("modulus", modulus);
            map.put("publicKey", publicKey);
            map.put("privateKey", privateKey);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return map;
    }

    /**
     * 从字符串中加载公钥
    *
     * @param publicKeyStr 公钥数据字符串
     * @throws Exception 加载公钥时产生的异常
     */
    public static PublicKey loadPublicKey(String publicKeyStr) throws Exception {
        try {
            byte[] buffer = Base64Utils.decode(publicKeyStr);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
            return (RSAPublicKey) keyFactory.generatePublic(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("公钥非法");
        } catch (NullPointerException e) {
            throw new Exception("公钥数据为空");
        }
    }

    /**
     * 从字符串中加载私钥
* 加载时使用的是PKCS8EncodedKeySpec(PKCS#8编码的Key指令)。 * * @param privateKeyStr * @return * @throws Exception */ public static PrivateKey loadPrivateKey(String privateKeyStr) throws Exception { try { byte[] buffer = Base64Utils.decode(privateKeyStr); // X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return (RSAPrivateKey) keyFactory.generatePrivate(keySpec); } catch (NoSuchAlgorithmException e) { throw new Exception("无此算法"); } catch (InvalidKeySpecException e) { throw new Exception("私钥非法"); } catch (NullPointerException e) { throw new Exception("私钥数据为空"); } } public static String getPrivateKeyStr(PrivateKey privateKey) throws Exception { return new String(Base64Utils.encode(privateKey.getEncoded())); } public static String getPublicKeyStr(PublicKey publicKey) throws Exception { return new String(Base64Utils.encode(publicKey.getEncoded())); } }

1.AES工具类

会生成密匙,原文加密,可以根据密匙进行解密

import java.util.UUID;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES工具类,密钥必须是16位字符串
 */
public class AESUtils {

	/**偏移量,必须是16位字符串*/
    private static final String IV_STRING = "16-Bytes--String";

    /**
     * 默认的密钥
     */
    public static final String DEFAULT_KEY = "1bd83b249a414036";


    /**
     * 产生随机密钥(这里产生密钥必须是16位)
     */
    public static String generateKey() {
        String key = UUID.randomUUID().toString();
        key = key.replace("-", "").substring(0, 16);// 替换掉-号
        return key;
    }

    public static String encryptData(String key, String content) {
        byte[] encryptedBytes = new byte[0];
        try {
            byte[] byteContent = content.getBytes("UTF-8");
            // 注意,为了能与 iOS 统一
            // 这里的 key 不可以使用 KeyGenerator、SecureRandom、SecretKey 生成
            byte[] enCodeFormat = key.getBytes();
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
            byte[] initParam = IV_STRING.getBytes();
            IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
            // 指定加密的算法、工作模式和填充方式
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
            encryptedBytes = cipher.doFinal(byteContent);
            // 同样对加密后数据进行 base64 编码
            return Base64Utils.encode(encryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String decryptData(String key, String content) {
        try {
            // base64 解码
            byte[] encryptedBytes = Base64Utils.decode(content);
            byte[] enCodeFormat = key.getBytes();
            SecretKeySpec secretKey = new SecretKeySpec(enCodeFormat, "AES");
            byte[] initParam = IV_STRING.getBytes();
            IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
            byte[] result = cipher.doFinal(encryptedBytes);
            return new String(result, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static void main(String[] args) {
		String plainText = AESUtils.decryptData("F431E6FF9051DA07", "q8jHYk6LSbwC2K4zmr/wRZo8mlH0VdMzPEcAzQadTCpSrPQ/ZnTmuIvQxiLOnUXu");
		System.out.println("aes加密后: " + plainText);
	}
    
}

用到的工具类Base64Utils

import org.apache.commons.codec.binary.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/** */
/**
 * 

* BASE64编码解码工具包 *

*

* 依赖 * * commons-codec * commons-codec * 1.9 * *

* * @author jun * @date 2012-5-19 * @version 1.0 */ public class Base64Utils { /** */ /** * 文件读取缓冲区大小 */ private static final int CACHE_SIZE = 1024; /** */ /** *

* BASE64字符串解码为二进制数据 *

* * @param base64 * @return * @throws Exception */ public static byte[] decode(String base64) throws Exception { //解密 return Base64.decodeBase64(base64.getBytes()); } public static String decode(byte[] b) { //解密 return new String(Base64.decodeBase64(b)); } /** */ /** *

* 二进制数据编码为BASE64字符串 *

* * @param bytes * @return * @throws Exception */ public static String encode(byte[] bytes) throws Exception { //加密 return new String(Base64.encodeBase64Chunked(bytes)); } /** */ /** *

* 将文件编码为BASE64字符串 *

*

* 大文件慎用,可能会导致内存溢出 *

* * @param filePath * 文件绝对路径 * @return * @throws Exception */ public static String encodeFile(String filePath) throws Exception { byte[] bytes = fileToByte(filePath); return encode(bytes); } /** */ /** *

* BASE64字符串转回文件 *

* * @param filePath * 文件绝对路径 * @param base64 * 编码字符串 * @throws Exception */ public static void decodeToFile(String filePath, String base64) throws Exception { byte[] bytes = decode(base64); byteArrayToFile(bytes, filePath); } /** */ /** *

* 文件转换为二进制数组 *

* * @param filePath * 文件路径 * @return * @throws Exception */ public static byte[] fileToByte(String filePath) throws Exception { byte[] data = new byte[0]; File file = new File(filePath); if (file.exists()) { FileInputStream in = new FileInputStream(file); ByteArrayOutputStream out = new ByteArrayOutputStream(2048); byte[] cache = new byte[CACHE_SIZE]; int nRead = 0; while ((nRead = in.read(cache)) != -1) { out.write(cache, 0, nRead); out.flush(); } out.close(); in.close(); data = out.toByteArray(); } return data; } /** */ /** *

* 二进制数据写文件 *

* * @param bytes * 二进制数据 * @param filePath * 文件生成目录 */ public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception { InputStream in = new ByteArrayInputStream(bytes); File destFile = new File(filePath); if (!destFile.getParentFile().exists()) { destFile.getParentFile().mkdirs(); } destFile.createNewFile(); OutputStream out = new FileOutputStream(destFile); byte[] cache = new byte[CACHE_SIZE]; int nRead = 0; while ((nRead = in.read(cache)) != -1) { out.write(cache, 0, nRead); out.flush(); } out.close(); in.close(); } }

 

测试

import com.mqtt.demo.util.rsa.AESUtils;
import com.mqtt.demo.util.rsa.RSAUtils;
import org.springframework.util.Base64Utils;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;


//@RunWith(SpringRunner.class)
//@SpringBootTest
public class Test{


    //测试
    @org.junit.Test
    public void test0()throws Exception {
//        RSAUtils.init();
        RSAUtils.setPublicKey("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCWLwvzYCpVlt0zd8MDNWk6Y2r+8pGKiEdy7gJK\n" +
                "G6LYRpxGMQg3nT245FTCkEXvhRTkRUlqGRenXQ2wTlMiv07qHVDUx8trmHEuPDO9juP/R9ezqeg0\n" +
                "oJiAha5N+pRnqU9fFqlmG/4FT9RR7GfGliksixaBxlDzlau9NUPozwDvdQIDAQAB\n");
        RSAUtils.setPrivateKey("MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJYvC/NgKlWW3TN3wwM1aTpjav7y\n" +
"kYqIR3LuAkobothGnEYxCDedPbjkVMKQRe+FFORFSWoZF6ddDbBOUyK/TuodUNTHy2uYcS48M72O\n" +             "4/9H17Op6DSgmICFrk36lGepT18WqWYb/gVP1FHsZ8aWKSyLFoHGUPOVq701Q+jPAO91AgMBAAEC\n" +           "gYEAgXMR4Pht5RJBngBHpjdeeUaCTjh0/KyUsVq3vHrvtW2/e7z9sTomnnypFn9W2KqkJFIYgowY\n" +            "WFkb2HDateOiN05mFwIzrG8LoKfIke6ETfIvPlaUYPXmoQmIFjbWY21mhD/KMT45ZBThi4QCBtMK\n" +           "EtPH6TpGEkDiVu+//VXFaGECQQDwoAUcmj3ulAWmcI/CIkr5ze3nTMTxeMbFniE2EQNwh/8FwmIB\n" +           "qePuqG1fPhSKQqVfiskpls3q3mIHzU6JughJAkEAn8emYK5HAcbviBfjv7jTBil+PT64mtrT/AO4\n" +           "9NaWCpvHx9sf0VqT7O+CL1sENW93uxD5zVfxp8ELPotQFKflzQJAMQBFSjfW2Njn9acCf4RARHK9\n" +           "OdcWXB4+TEwRc1MvoiDvvBqDntccBaPi8fxQbn938ebvZDrDoEq9J92VWtK5kQJATcXEenLaJUdL\n" +          "+JaISR4RuYIg7HbHLLkvThARyztYNTm2eNV0G1dXgZDjcWGAHvJu+SM+NHGGMv2IF52AEU3YUQJA\n" +            "YGqyUssmnNft2fvcqtE6u4ZE9n9GwWIot2nve/BJeln1xpmoEvl/kKJ8XMXD1epmeH6mU3KAEpwY\n" +
                "nthFJHPyHA==\n");
        //加密
        String encryptText = RSAUtils.encryptByPrivateKey("I love Beyound");
        System.out.println("密文:"+encryptText);
        //解密
        String decryptText = RSAUtils.decryptByPublicKey(encryptText);
        System.out.println(decryptText);
    }

    //RSA加密解密测试
    @org.junit.Test
    public void test()throws Exception {
//        RSAUtils.init();
        RSAUtils.setPublicKey("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCWLwvzYCpVlt0zd8MDNWk6Y2r+8pGKiEdy7gJK\n" +
                "G6LYRpxGMQg3nT245FTCkEXvhRTkRUlqGRenXQ2wTlMiv07qHVDUx8trmHEuPDO9juP/R9ezqeg0\n" +
                "oJiAha5N+pRnqU9fFqlmG/4FT9RR7GfGliksixaBxlDzlau9NUPozwDvdQIDAQAB\n");
        RSAUtils.setPrivateKey("MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJYvC/NgKlWW3TN3wwM1aTpjav7y\n" +
                "kYqIR3LuAkobothGnEYxCDedPbjkVMKQRe+FFORFSWoZF6ddDbBOUyK/TuodUNTHy2uYcS48M72O\n" +
                "4/9H17Op6DSgmICFrk36lGepT18WqWYb/gVP1FHsZ8aWKSyLFoHGUPOVq701Q+jPAO91AgMBAAEC\n" +
                "gYEAgXMR4Pht5RJBngBHpjdeeUaCTjh0/KyUsVq3vHrvtW2/e7z9sTomnnypFn9W2KqkJFIYgowY\n" +
                "WFkb2HDateOiN05mFwIzrG8LoKfIke6ETfIvPlaUYPXmoQmIFjbWY21mhD/KMT45ZBThi4QCBtMK\n" +
                "EtPH6TpGEkDiVu+//VXFaGECQQDwoAUcmj3ulAWmcI/CIkr5ze3nTMTxeMbFniE2EQNwh/8FwmIB\n" +
                "qePuqG1fPhSKQqVfiskpls3q3mIHzU6JughJAkEAn8emYK5HAcbviBfjv7jTBil+PT64mtrT/AO4\n" +
                "9NaWCpvHx9sf0VqT7O+CL1sENW93uxD5zVfxp8ELPotQFKflzQJAMQBFSjfW2Njn9acCf4RARHK9\n" +
                "OdcWXB4+TEwRc1MvoiDvvBqDntccBaPi8fxQbn938ebvZDrDoEq9J92VWtK5kQJATcXEenLaJUdL\n" +
                "+JaISR4RuYIg7HbHLLkvThARyztYNTm2eNV0G1dXgZDjcWGAHvJu+SM+NHGGMv2IF52AEU3YUQJA\n" +
                "YGqyUssmnNft2fvcqtE6u4ZE9n9GwWIot2nve/BJeln1xpmoEvl/kKJ8XMXD1epmeH6mU3KAEpwY\n" +
                "nthFJHPyHA==\n");
        //加密
        String encryptText = RSAUtils.encryptByPublicKey("I love Beyound");
        System.out.println("密文:"+encryptText);
        //解密
       String decryptText = RSAUtils.decryptByPrivateKey("FCKgUjO/d9OkpKEqvQ/k8EU6ADZm4XLWRxNxsxVVjEZsBK/QkVvuZgtlLNuLo2WT4zP5pdx3n+EdmtO88RzQde46mDoCDdmx3wrQkVfh+Or9e++uN4hjObhv3uDS7IJpy+1ddzeVaQKFGxV44iD4Iub3asFP/laLtsLKeluj+5Q=\n");
        System.out.println(decryptText);
    }


    //AES加密
    @org.junit.Test
    public void test1()throws Exception {
        //加密
        String key = AESUtils.generateKey();
        String text = "I love Beyound";
        String encryptTest = AESUtils.encryptData(key, text);
        System.out.println("密匙:"+key);
        System.out.println("密文:"+encryptTest);
        //解密
        text = AESUtils.decryptData(key, encryptTest);
        System.out.println("原文:"+text);
    }

    //RSA+AES加密
    @org.junit.Test
    public void test2()throws Exception {
       //随机产生一个AES密钥
        String key = AESUtils.generateKey();
        
        String name = "陈好文";
        String idCard = "112233**************";
        
        //使用AES对重要信息进行加密
        String encryptName = AESUtils.encryptData(key, name);
        String encryptIdCard = AESUtils.encryptData(key, idCard);

        //使用RSA对产生的密钥进行加密
        String encrpytKey = RSAUtils.encryptByPublicKey(key);

        System.out.println("使用RSA加密后的AES密钥:"+encrpytKey);
        System.out.println("AES加密后的真实姓名:"+encryptName);
        System.out.println("AES加密后的身份证号:"+encryptIdCard);
    }

    //RSA+AES解密
    @org.junit.Test
    public void test3()throws Exception {
        String encryptKey = "U8t42jPDsMZdSGBzMY+WVrEpNuGtbmzplRw6X+ugLAujYvDVS6MhvD4+0Ie62O8z33hR+oEaoQF2\n" +        "eFNjx83yRjbKgr1al0SYIczgMw5ZJ4tRBB8WmPyhl13U7vlPwxQXWAizwsGLXYCx9NcTIX4EWLZ6\n" +
                "2ffdHE3fMSdbeiPrpVM=";
        String encryptName = "r1RMAxBgI4IyPYJBIqvZ4Q==";
        String encryptIdCard = "Fw7+Oa62/FPe26U0K/flvsTEPIeEpD4lhR+nCaG4zQU=";

        //使用AES对重要信息进行加密
        String key = RSAUtils.decryptByPrivateKey(encryptKey);
        String name = AESUtils.decryptData(key,encryptName);
        String idCard = AESUtils.decryptData(key,encryptIdCard);

        System.out.println("密钥:"+key);
        System.out.println("真实姓名:"+name);
        System.out.println("身份证号:"+idCard);
    }

    /**
     * 生成公钥和私钥
     *
     * @throws Exception
     */
    @org.junit.Test
    public void getKeys() throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        keyPairGen.initialize(1024);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

        String publicKeyStr = getPublicKeyStr(publicKey);
        String privateKeyStr = getPrivateKeyStr(privateKey);

        System.out.println("公钥\r\n" + publicKeyStr);
        System.out.println("私钥\r\n" + privateKeyStr);
    }

    public static String getPrivateKeyStr(PrivateKey privateKey)
           throws Exception {
        return new String(Base64Utils.encode(privateKey.getEncoded()));
    }

    public static String getPublicKeyStr(PublicKey publicKey) throws Exception {
        return new String(Base64Utils.encode(publicKey.getEncoded()));
    }
}

 

 

 

 

 

 

 

你可能感兴趣的:(java,后端,工具)