DES和RSA混合加密&解密

Posted qigc_0529

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DES和RSA混合加密&解密相关的知识,希望对你有一定的参考价值。

        关于DES和RSA各自单独加密的弊端大家自行学习吧,本文使用对称式加密算法DES和非对称式加密算法RSA结合做数据加密的方式,先进行DES加密,将DES加密后的内容进行base64编码,再将base64编码的DES进行RSA加密,本文分别创建DES和RSA工具类,便于单独使用,也可混合使用。具体步骤如下:

1、POM文件添加相关jar包


        <!-- DES -->
        <dependency>
            <groupId>javax.xml.rpc</groupId>
            <artifactId>javax.xml.rpc-api</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!-- RSA -->
        <dependency>
            <groupId>org.apache.axis</groupId>
            <artifactId>axis</artifactId>
            <version>1.4</version>
        </dependency>
        <!-- base64 -->
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.10</version>
        </dependency>

2、自定义一个DES密钥,最好是8位,放在配置文件里面

3、生成一对RSA公钥和私钥,也放在配置文件里面

生成代码:

 /**
     * 生成RSA密钥对
     */
    protected static Map<String, String> genKeyPairMap() 
        Map<String, String> keyPairMap = new HashMap<>(2);
        // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
        KeyPairGenerator keyPairGen = null;
        try 
            keyPairGen = KeyPairGenerator.getInstance("RSA");
            // 初始化密钥对生成器,密钥大小为96-1024位
            keyPairGen.initialize(1024, new SecureRandom());
            // 生成一个密钥对,保存在keyPair中
            KeyPair keyPair = keyPairGen.generateKeyPair();
            // 得到私钥
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
            // 得到公钥
            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
            // 得到公钥字符串
            String publicKeyString = getKeyString(publicKey);
            // 得到私钥字符串
            String privateKeyString = getKeyString(privateKey);
            keyPairMap.put("publicKey", publicKeyString);
            keyPairMap.put("privateKey", privateKeyString);
         catch (Exception e) 
            logger.error("[RsaUtil]-生成密钥对失败! ---------------", e);
            throw new PlatException("[RsaUtil]-生成密钥对失败!");
        
        return keyPairMap;
    

配置文件

desKey = dev-2022
RSA_public_key = MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDylxBFYYsoc9sfyWJ9sdWlsJj13aOcqDhaX5FLAyZP4mz7Jz4cGzDQkY1iGBKHl5NC24dD0f7y1KUncE/8qAgoPiX1T5uK6CC5d/AxLK+ElrhiTp+mtkuGZKAQ9oO+bzqNMH0yP80LXVGXQlIOPjP5/lduG+X1JwsOLyCpPvhCTQIDAQAB
RSA_private_key = MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAPKXEEVhiyhz2x/JYn2x1aWwmPXdo5yoOFpfkUsDJk/ibPsnPhwbMNCRjWIYEoeXk0Lbh0PR/vLUpSdwT/yoCCg+JfVPm4roILl38DEsr4SWuGJOn6a2S4ZkoBD2g75vOo0wfTI/zQtdUZdCUg4+M/n+V24b5fUnCw4vIKk++EJNAgMBAAECgYEAhfEEidpOtFornYRavh3nYaF9AxuKD6AN5VAo76rgh3D0TUOglnIo5K/IyWWTLYxyQZLmP3r98mOYgIsRjuXUAhkCUqSvMrNZ+jSSpCo3ceey+Cd3JJQigv24oRvYvA7rgmmUOQ1FojyVva43Bm5w6Om8oh0LMSKH7h4xv/XjgSECQQD7iHNQieUWJ9J4feRCwqILSnpXiAtQOk9oq46R8FoSOO7NVmbsNGEoS2aYH3gDeMaMPIZGyQtP/DMZOeOB6CjJAkEA9uX0q8dqq96zWSX8ptTEKFWI3P+YUbg4dg+dKt46vrY037DnNGRO3tjEruPnZuAUQ0CQyXc6foYqvUUVum9TZQJAbNXEt5OC+UwvyI0IaE6ZGPOX7iniY0tnsq2Qmdr6zimuQlDhZdDgPTQq5yWuoynuFx3VJ+mzqF9CqOagZ0RR6QJBAJxKaR2seLwfl4yhXVQGb73Ql3i+W5+vbB5gN++BCdLb6JCJnXIu5TZwJeFH553ZzznbT0wZK3AYYkm5x81i13kCQFyJP2FzPiyEFhisPWQi0bXZQQlwMCimZJknl75OAZCDgDNouBH2jSu7g7zBPRU15X9fmMNdeF3Wl3srUNkRHoI=

4、创建DES加解密工具类

import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

/**
 * @author qigc
 * @Description ES和RSA混合加密,先进行DES加密,将DES加密后的内容进行base64编码,再将base64编码的DES进行RSA加密
 * @createTime 2021年08月23日 15:42:00
 */
public class DEUtil 

    private static final Logger logger = LoggerFactory.getLogger(DEUtil.class);
    /**
     * 编码格式
     */

    private static final String DES_KEY = "desKey";
    private static final String PUBLIC_KEY = "RSA_public_key";
    private static final String PRIVATE_KEY = "RSA_private_key";

    /**
     * 加密
     *
     * @param content 加密内容
     * @return
     */
    public static String encrypt(String content) 
        String rsaContent = null;
        try 
            //从配置文件获取des密钥8位
            String desKey = PlatApplicationContext.getProperties(DES_KEY);
            //DES加密
            String desContent  = DesUtil.encrypt(content, desKey);
            //从配置文件获取公钥key
            String pubKey = PlatApplicationContext.getProperties(PUBLIC_KEY);
            //根据公钥key获取公钥
            RSAPublicKey publicKey = RsaUtil.getPublicKey(pubKey);
            //RSA加密
            rsaContent = RsaUtil.publicEncrypt(desContent, publicKey);
         catch (Exception e) 
            logger.error("[DEUtil]-加密失败! ---------------", e);
            throw new PlatException("[DEUtil]-加密失败!");
        
        return rsaContent;
    

    /**
     * @return java.lang.String
     * @author qigc
     * 解密
     * @date 2021/8/23
     */
    public static String decode(String rsaContent) 
        String content = null;
        try 
            //从配置文件获取des密钥8位
            String desKey = PlatApplicationContext.getProperties(DES_KEY);
            String priKey = PlatApplicationContext.getProperties(PRIVATE_KEY);
            //获取私钥
            RSAPrivateKey privateKey = RsaUtil.getPrivateKey(priKey);
            //RSA解密
            String contentRsa = RsaUtil.privateDecryptToString(rsaContent,privateKey);
            //DES解密
            content = DesUtil.decrypt(contentRsa,desKey);
         catch (Exception e) 
            logger.error("[DEUtil]-解密失败! ---------------", e);
            throw new PlatException("[DEUtil]-解密失败!");
        
        return content;
    




5、创建RSA加密解密工具类RsaUtil

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

import javax.crypto.Cipher;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.FileWriter;
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;

/**
 * @author qigc
 * @Description RSA工具类
 * @createTime 2021年08月23日 15:14:00
 */
class RsaUtil 

    private static final Logger logger = LoggerFactory.getLogger(RsaUtil.class);
    /**
     * 编码格式
     */
    private static final String E_CODE_TYPE = "UTF-8";

    /**
     * 转密钥字符串(base64编码)
     *
     * @return
     */
    private static String getKeyString(Key key) throws Exception 
        byte[] keyBytes = key.getEncoded();
        return new String(Base64.encodeBase64(keyBytes));
    

    /**
     * 得到公钥
     *
     * @param publicKey 密钥字符串(经过base64编码)
     * @throws Exception
     */
    protected static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException 
        //通过X509编码的Key指令获得公钥对象
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
        return (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
    

    /**
     * 得到私钥
     *
     * @param privateKey 密钥字符串(经过base64编码)
     * @throws Exception
     */
    protected static RSAPrivateKey getPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException 
        //通过PKCS#8编码的Key指令获得私钥对象
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
        return (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
    

   

    /**
     * 公钥加密
     *
     * @param data      需要加密的内容
     * @param publicKey 公钥
     * @return
     */
    protected static String publicEncrypt(String data, RSAPublicKey publicKey) 
        try 
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return new String(Base64.encodeBase64(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(E_CODE_TYPE), publicKey.getModulus().bitLength())));
         catch (Exception e) 
            logger.error("[RsaUtil]-公钥加密失败! ---------------", e);
            throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
        
    

    /**
     * 私钥解密
     *
     * @param data       需要加密的内容
     * @param privateKey 私钥
     * @return
     */

    protected static String privateDecryptToString(String data, RSAPrivateKey privateKey) 
        try 
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), privateKey.getModulus().bitLength()), E_CODE_TYPE);
         catch (Exception e) 
            logger.error("[RsaUtil]-私钥解密失败! ---------------", e);
            throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
        
    

    /**
     * 私钥解密
     *
     * @param data       需要加密的内容
     * @param privateKey 私钥
     * @return
     */

    protected static byte[] privateDecrypt(String data, RSAPrivateKey privateKey) 
        try 
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), privateKey.getModulus().bitLength());
         catch (Exception e) 
            logger.error("[RsaUtil]-私钥解密失败! ---------------", e);
            throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
        
    

    private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize) 
        int maxBlock = 0;
        if (opmode == Cipher.DECRYPT_MODE) 
            maxBlock = keySize / 8;
         else 
            maxBlock = keySize / 8 - 11;
        
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] buff;
        int i = 0;
        try 
            while (datas.length > offSet) 
                if (datas.length - offSet > maxBlock) 
                    buff = cipher.doFinal(datas, offSet, maxBlock);
                 else 
                    buff = cipher.doFinal(datas, offSet, datas.length - offSet);
                
                out.write(buff, 0, buff.length);
                i++;
                offSet = i * maxBlock;
            
         catch (Exception e) 
            logger.error("[RsaUtil]-加解密失败! ---------------", e);
            throw new RuntimeException("加解密阀值为[" + maxBlock + "]的数据时发生异常", e);
        
        byte[] resultDatas = out.toByteArray();
        IOUtils.closeQuietly(out);
        return resultDatas;
    

6、创建DES+RSA混合加解密工具类DEUtil

import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

/**
 * @author qigc
 * @Description ES和RSA混合加密,先进行DES加密,将DES加密后的内容进行base64编码,再将base64编码的DES进行RSA加密
 * @createTime 2021年08月23日 15:42:00
 */
public class DEUtil 

    private static final Logger logger = LoggerFactory.getLogger(DEUtil.class);
    /**
     * 编码格式
     */

    private static final String DES_KEY = "desKey";
    private static final String PUBLIC_KEY = "RSA_public_key";
    private static final String PRIVATE_KEY = "RSA_private_key";

    /**
     * 加密
     *
     * @param content 加密内容
     * @return
     */
    public static String encrypt(String content) 
        String rsaContent = null;
        try 
            //从配置文件获取des密钥8位
            String desKey = PlatApplicationContext.getProperties(DES_KEY);
            //DES加密
            String desContent  = DesUtil.encrypt(content, desKey);
            //从配置文件获取公钥key
            String pubKey = PlatApplicationContext.getProperties(PUBLIC_KEY);
            //根据公钥key获取公钥
            RSAPublicKey publicKey = RsaUtil.getPublicKey(pubKey);
            //RSA加密
            rsaContent = RsaUtil.publicEncrypt(desContent, publicKey);
         catch (Exception e) 
            logger.error("[DEUtil]-加密失败! ---------------", e);
            throw new PlatException("[DEUtil]-加密失败!");
        
        return rsaContent;
    

    /**
     * @return java.lang.String
     * @author qigc
     * 解密
     * @date 2021/8/23
     */
    public static String decode(String rsaContent) 
        String content = null;
        try 
            //从配置文件获取des密钥8位
            String desKey = PlatApplicationContext.getProperties(DES_KEY);
            String priKey = PlatApplicationContext.getProperties(PRIVATE_KEY);
            //获取私钥
            RSAPrivateKey privateKey = RsaUtil.getPrivateKey(priKey);
            //RSA解密
            String contentRsa = RsaUtil.privateDecryptToString(rsaContent,privateKey);
            //DES解密
            content = DesUtil.decrypt(contentRsa,desKey);
         catch (Exception e) 
            logger.error("[DEUtil]-解密失败! ---------------", e);
            throw new PlatException("[DEUtil]-解密失败!");
        
        return content;
    




以上是关于DES和RSA混合加密&解密的主要内容,如果未能解决你的问题,请参考以下文章

DES和RSA混合加密&解密

混合加密算法(RSA和DES)

利用RSACryptoServiceProvider进行RSA加密解密

对称加密 & 非对称加密

des和aes 加解密算法具体步骤?有例子最好

php使用openssl进行Rsa长数据加密(117)解密(128) 和 DES 加密解密