Java中使用RSA加解密

最近要用RSA和DES加解密,把遇到的问题描述一下

1、密文数据已破坏

报这个错的原因是因为加密后应该使用base64转换一下,不能直接new String()

附上代码:

 以下代码可以直接用

package com.test.util;


import org.apache.commons.codec.binary.Base64;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
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.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

public class SecrteKeyUtil {
    private static Logger log = LogManager.getLogger(SecrteKeyUtil.class);

    public static final String PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhK5CC/0MQqdG9xtMhGP0Cy8qkRw/UK7ktS9cN46V4wsDX5KvlTXyIYDXjiYwKvGVUak2OKZB688Qlz3RRy1E4UNosf8YREGwdNXE5wvG0bf1Qd5RCr/Cr99M3x/Elyp1Z+jFZlFXrbAAQZq/sRh+9l+xn3l8+ChhuTdXKBhpl+8cz4edmGHPWkOuGvoN6lOE8lNzbZtmz5dfbAEtbsOin+/u69ynoIGz4iYL7KnzDrZOOHutZ4++qtiX+Pbhse+h2tPAwgUSOOTKsoEn/zjadOS6XJJ1VeeWnBVSn40jPbYRt3ymApItQcym6mWSnyg+2flLnpdAf7DIQn2Qlqt+VwIDAQAB";
    public static final String PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCErkIL/QxCp0b3G0yEY/QLLyqRHD9QruS1L1w3jpXjCwNfkq+VNfIhgNeOJjAq8ZVRqTY4pkHrzxCXPdFHLUThQ2ix/xhEQbB01cTnC8bRt/VB3lEKv8Kv30zfH8SXKnVn6MVmUVetsABBmr+xGH72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57sHsRmJeaKZhMChll4WFJdreG8zsE5qkImdHy/vkzgjQD+vTwx7qySUWqlTuMLIAomtdSZzhLKmA6LqJmNDOiDgPXZHZAOS779wf8tn+S0jJf8g7mY73ZkpXeUuyoETlicU1CqbemfBQjcEURLBo6Rku8bhqcTtvse5vhAoGAfuHzU9bz++EtQgfo2PPTD76erfjsYHGy4SR+S2WwgCBt04WZEWkbympjvpZQAMdD9WCOv3R1fNGLUIcRzrjlUt+HIAxJtW6tWYhL4i+KM4NqUhF+2TesGzYTPP8x8PSaWGT4ruynKrgxR08XaHyH3L/Htd3OMXTasgTPuZNguIw=";
    public static final String SIGN_NAME = "RSA"; // des dsa

    /**
     * 生成公钥与私钥对
     *
     * @return 公钥Key=publicKey 私钥Key=privateKey
     * @throws Exception
     */
    public static Map<String, String> getKeys() throws Exception {
        int len = 2048;//rsa算法长度,生成秘钥对时用
        // 获得公钥与私钥对
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(SIGN_NAME);
        keyPairGen.initialize(len);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
        Map<String, String> keys = new HashMap<String, String>(2);
        String privateKey = Base64.encodeBase64String(rsaPrivateKey.getEncoded());
        keys.put("privateKey", privateKey);
        RSAPublicKey rsapublicKey = (RSAPublicKey) keyPair.getPublic();
        String publicKey = Base64.encodeBase64String(rsapublicKey.getEncoded());
        keys.put("publicKey", publicKey);
        return keys;
    }

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

    /**
     * 从字符串中加载私钥
     * @param privateKeyStr
     * @return
     * @throws Exception
     */
    public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr) throws Exception {
        try {
            byte[] buffer = Base64.decodeBase64(privateKeyStr);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
        } catch (NoSuchAlgorithmException e) {
            log.error("无此算法",e);
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e) {
            log.error("私钥非法",e);
            throw new Exception("私钥非法");
        } catch (NullPointerException e) {
            log.error("私钥数据为空",e);
            throw new Exception("私钥数据为空");
        }
    }

    /**
     * 公钥加密过程
     *
     * @param publicKey     公钥
     * @param plainTextData 明文数据
     * @return
     * @throws Exception 加密过程中的异常信息
     */
    public static String encrypt(RSAPublicKey publicKey, byte[] plainTextData) throws Exception {
        if (publicKey == null) {
            throw new Exception("加密公钥为空, 请设置");
        }
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(SIGN_NAME);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] output = cipher.doFinal(plainTextData);
            return Base64.encodeBase64String(output);
        } catch (NoSuchAlgorithmException e) {
            log.error("无此加密算法",e);
            throw new Exception("无此加密算法");
        } catch (NoSuchPaddingException e) {
            log.error("NoSuchPaddingException",e);
            return null;
        } catch (InvalidKeyException e) {
            log.error("加密公钥非法,请检查",e);
            throw new Exception("加密公钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            log.error("明文长度非法",e);
            throw new Exception("明文长度非法");
        } catch (BadPaddingException e) {
            log.error("明文数据已损坏",e);
            throw new Exception("明文数据已损坏");
        }
    }

    /**
     * 私钥加密过程
     *
     * @param privateKey    私钥
     * @param plainTextData 明文数据
     * @return
     * @throws Exception 加密过程中的异常信息
     */
    public static String encrypt(RSAPrivateKey privateKey, byte[] plainTextData) throws Exception {
        if (privateKey == null) {
            throw new Exception("加密私钥为空, 请设置");
        }
        Cipher cipher = null;
        try {
            // 使用默认RSA
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            byte[] output = cipher.doFinal(plainTextData);
            return Base64.encodeBase64String(output);
        } catch (NoSuchAlgorithmException e) {
            log.error("无此加密算法",e);
            throw new Exception("无此加密算法");
        } catch (NoSuchPaddingException e) {
            log.error("NoSuchPaddingException",e);
            return null;
        } catch (InvalidKeyException e) {
            log.error("加密私钥非法,请检查",e);
            throw new Exception("加密私钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            log.error("明文长度非法",e);
            throw new Exception("明文长度非法");
        } catch (BadPaddingException e) {
            log.error("明文长度非法",e);
            throw new Exception("明文数据已损坏");
        }
    }

    /**
     * 私钥解密过程
     *
     * @param privateKey 私钥
     * @param cipherData 密文数据
     * @return 明文
     * @throws Exception 解密过程中的异常信息
     */
    public static String decrypt(RSAPrivateKey privateKey, byte[] cipherData) throws Exception {
        if (privateKey == null) {
            throw new Exception("解密私钥为空, 请设置");
        }
        Cipher cipher = null;
        try {
            // 使用默认RSA
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] output = cipher.doFinal(cipherData);
            return new String(output);
        } catch (NoSuchAlgorithmException e) {
            log.error("无此解密算法",e);
            throw new Exception("无此解密算法");
        } catch (NoSuchPaddingException e) {
            log.error("NoSuchPaddingException",e);
            return null;
        } catch (InvalidKeyException e) {
            log.error("解密私钥非法,请检查",e);
            throw new Exception("解密私钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            log.error("密文长度非法",e);
            throw new Exception("密文长度非法");
        } catch (BadPaddingException e) {
            log.error("密文数据已损坏",e);
            throw new Exception("密文数据已损坏");
        }
    }

    /**
     * 公钥解密过程
     *
     * @param publicKey  公钥
     * @param cipherData 密文数据
     * @return 明文
     * @throws Exception 解密过程中的异常信息
     */
    public static String decrypt(RSAPublicKey publicKey, byte[] cipherData) throws Exception {
        if (publicKey == null) {
            throw new Exception("解密公钥为空, 请设置");
        }
        Cipher cipher = null;
        try {
            // 使用默认RSA
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            byte[] output = cipher.doFinal(cipherData);
            return new String(output);
        } catch (NoSuchAlgorithmException e) {
            log.error("无此解密算法",e);
            throw new Exception("无此解密算法");
        } catch (NoSuchPaddingException e) {
            log.error("NoSuchPaddingException",e);
            return null;
        } catch (InvalidKeyException e) {
            log.error("解密公钥非法,请检查",e);
            throw new Exception("解密公钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            log.error("密文长度非法",e);
            throw new Exception("密文长度非法");
        } catch (BadPaddingException e) {
            log.error("密文数据已损坏",e);
            throw new Exception("密文数据已损坏");
        }
    }

    /**
     * 私钥加密
     * @param content 明文
     * @return
     */
    public static String priEncrypt(String content){
        String res = "";
        try {
            //加载私钥
            RSAPrivateKey rsaprikey = loadPrivateKeyByStr(PRIVATE_KEY);
            //私钥加密
            res = encrypt(rsaprikey,content.getBytes());
        } catch (Exception e) {
            log.error("私钥加密出错",e);
        }
        return res;
    }

    /**
     * 公钥加密
     * @param content 明文
     * @return
     */
    public static String pubEncrypt(String content){
        String res = "";
        try {
            //加载公钥
            RSAPublicKey rsapubkey = loadPublicKeyByStr(PUBLIC_KEY);
            //公钥加密
            res = encrypt(rsapubkey,content.getBytes());
        } catch (Exception e) {
            log.error("公钥加密出错",e);
        }
        return res;
    }

    /**
     * 私钥解密
     * @param content 加密后的密文
     */
    public static String priDecrypt(String content) throws Exception{
        String res = "";
        try {
            //加载私钥
            RSAPrivateKey rsaprikey = loadPrivateKeyByStr(PRIVATE_KEY);
            //解密
            res = decrypt(rsaprikey,Base64.decodeBase64(content));
        } catch (Exception e) {
            log.error("私钥解密出错",e);
            throw new Exception(e);
        }
        return res;
    }

    /**
     * 公钥解密
     * @param content 加密后的密文
     */
    public static String pubdecrypt(String content) throws Exception{
        String res = "";
        try {
            //加载公钥
            RSAPublicKey rsapubkey = loadPublicKeyByStr(PUBLIC_KEY);
            //解密
            res = decrypt(rsapubkey,Base64.decodeBase64(content));
        } catch (Exception e) {
            log.error("公钥解密出错",e);
            throw new Exception(e);
        }
        return res;
    }


    public static void main(String[] args) {
        try {
            //生成密钥对
//            Map map = getKeys();
//            System.out.println("私钥:"+map.get("privateKey"));
//            System.out.println("公钥:"+map.get("publicKey"));
            //私钥加密-公钥解密
            String mes = "测试";
            String enc = priEncrypt(mes);
            System.out.println("加密后的密文:"+enc);
            System.out.println("解密后的明文:"+pubdecrypt(enc));

            //公钥加密-私钥解密
            String mes2 = "测试";
            String enc2 = pubEncrypt(mes2);
            System.out.println("加密后的密文:"+enc2);
            System.out.println("解密后的明文:"+priDecrypt(enc2));

        } catch (Exception e) {
            log.error("",e);
        }
    }

}

参考文章: http://blog.csdn.net/qq_18870023/article/details/52596808



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值