AES、RSA、DH加密解密

1. 加密解密工具

1.1 编码方式

base64:严格来说base64并不是一种加密/解密算法,而是一种编码方式。base64不生成密钥,通过base64编码后的密文可以直接翻译成明文。

应用场景:两地的传输。
经过很多路由,不同的路由对不同的字符的处理方式是不一样的,不利于传输,需要传输的字符进行base64的编码,然后传输。
降低错误率
例如,字符串,电子邮件,xml文件等等

总之就是字节数组,字符串和文件

还有一种使用base64编码的情况就是编码在线的图片的地址,然后可以在本地解码。

base64的工具类:Java8将base编码直接弄进了java.utils包下。
也就是Base64类。

1.2 对称加密方式

1.2.1 DES加密

DES是表面64位,实际上是一种基于56位密钥的对称算法,现在的DES已经不是一种安全的算法,已被公开破解,现在DES已经被高级加密标准AES所代替。其余的八位用于奇偶的校验。

主要因为56位的密钥过短。

3DES是DES的一种派生算法。提升了一些安全性。
相当于是对每一个数据块应用了三次DES运算。
密钥必须是24位,向量必须要8位,加解密使用统一的编码方式。

import com.sun.org.apache.xml.internal.security.utils.Base64;

import java.security.Key;


import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class DES3 {
    // 密钥
    private final static String secretKey = "huijin12345@lx100$#365#$";
    // 向量
    private final static String iv = "huijin66";
    // 加解密统一使用的编码方式
    private final static String encoding = "utf-8";

    /**
     * 3DES加密
     *
     * @param plainText 普通文本
     * @return
     * @throws Exception
     */
    public static String encode(String plainText) {
        Key deskey = null;
        try {
            DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
            SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
            deskey = keyfactory.generateSecret(spec);

            Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
            IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
            byte[] encryptData = cipher.doFinal(plainText.getBytes(encoding));
            return Base64.encode(encryptData);
        } catch (Exception e) {
            e.printStackTrace();
            return plainText;
        }
    }

    /**
     * 3DES解密
     *
     * @param encryptText 加密文本
     * @return
     * @throws Exception
     */
    public static String decode(String encryptText) {
        Key deskey = null;
        try {
            DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
            SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
            deskey = keyfactory.generateSecret(spec);
            Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
            IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, deskey, ips);

            byte[] decryptData = cipher.doFinal(Base64.decode(encryptText));
            return new String(decryptData, encoding);
        } catch (Exception e) {
            e.printStackTrace();
            return encryptText;
        }
    }

    public static void main(String[] args) {
        try {
            System.out.println(encode("13003221671"));
            System.out.println(decode("5uyfs4qr2bNRADXRGYxGnw=="));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

1.2.2 AES加密

AES是现在最流行的对称加密算法之一。
必须是16位的密钥

package com.itdong.utils;

import com.mysql.cj.x.protobuf.MysqlxDatatypes;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class Base64AndAesUtils {
    /**
     * 密钥
     */
    private static final String KEY = "abcdefgabcdefg12"; //必须是16位的密钥

    /**
     * 算法
     */
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";


    public static void main(String[] args) throws Exception {
        /*String content = "我爱你";
        System.out.println("加密前:" + content);

        System.out.println("加密密钥和解密密钥:" + KEY);

        String encrypt = aesEncrypt(content, KEY);
        System.out.println("加密后:" + encrypt);

        String decrypt = aesDecrypt("zNeujvgAjFHfNZWk3cYoMw==", KEY);
        System.out.println("解密后:" + decrypt);*/
        String data = "这是一条测试base64的文字";
        String base64dataStr = base64Encode(data.getBytes());
        System.out.println(base64dataStr);

        byte[] datas = base64Decode(base64dataStr);
        String data1 = new String(datas);
        System.out.println(data1);

        String dateAES = "这是一条测试AES的文字";
        String aesEncrypt = aesEncrypt(dateAES, KEY);
        System.out.println(aesEncrypt);
        String data2 = aesDecrypt(aesEncrypt, KEY);
        System.out.println(data2);
    }


    /**
     * base 64 encode
     * @param bytes 待编码的byte[]
     * @return 编码后的base 64 code
     */
    public static String base64Encode(byte[] bytes){
        return Base64.getEncoder().encodeToString(bytes);
        //return Base64.encodeBase64String(bytes);
    }

    /**
     * base 64 decode
     * @param base64Code 待解码的base 64 code
     * @return 解码后的byte[]   new BASE64Decoder().decodeBuffer(base64Code)
     * @throws Exception
     */
    public static byte[] base64Decode(String base64Code) throws Exception{
        //return StringUtils.isEmpty(base64Code) ? null :Base64.decodeBase64(base64Code);
        return Base64.getDecoder().decode(base64Code);
    }


    /**
     * AES加密
     * @param content 待加密的内容
     * @param encryptKey 加密密钥
     * @return 加密后的byte[]
     * @throws Exception
     */
    public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
        return cipher.doFinal(content.getBytes("utf-8"));
    }


    /**
     * AES加密为base 64 code
     * @param content 待加密的内容
     * @param encryptKey 加密密钥
     * @return 加密后的base 64 code
     * @throws Exception
     */
    public static String aesEncrypt(String content, String encryptKey) throws Exception {
        // aesEncryptToBytes(content, encryptKey)  这个方法相当于对内容使用指定的密钥进行了一次hash内容返回
        // base64Encode  -》  Base64.encodeBase64String(bytes);  使用hash后的内容使用 base64进行加密
        return base64Encode(aesEncryptToBytes(content, encryptKey));
    }

    /**
     * AES解密
     * @param encryptBytes 待解密的byte[]
     * @param decryptKey 解密密钥
     * @return 解密后的String
     * @throws Exception
     */
    public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }


    /**
     * 将base 64 code AES解密
     * @param encryptStr 待解密的base 64 code
     * @param decryptKey 解密密钥
     * @return 解密后的string
     * @throws Exception
     */
    public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {
        // base64Decode(encryptStr) base64加密
        // aesDecryptByBytes  aes解密
        //return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
        if (encryptStr != null && !encryptStr.equals("")){
            return  aesDecryptByBytes(Base64.getDecoder().decode(encryptStr), decryptKey);
        }else{
            return null;
        }
    }

}

1.2.3 公钥私钥方式 RSA

严格来说,这一种非对称的方式,因为加密解密使用的是不同的密钥。

1.3 非对称加密方式

1.3.1 公钥私钥方式 RSA

公钥是公开的,公开出去,让所有人都可以用来加密。但是只有持有私钥的人才能正确解密。
一般来说私钥放在服务器里,数据经过公钥加密就只能被私钥解密;数据经过私钥加密,就只能被公钥解密。

以下就是算法的过程简介:
在这里插入图片描述
在这里插入图片描述
公钥中的E来自T
私钥中的D来自公钥中E和T
所以,很明显,T很重要,当N很大时,两个质数是没那么好求的,所以就算(E,N)公开也没法轻易的得到T。

package com.itdong.utils;
import org.apache.commons.codec.binary.Base64;  //commons-codec
import org.apache.commons.io.IOUtils;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
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.Date;
import java.util.HashMap;
import java.util.Map;

public class RSAUtils {
    public static final String CHARSET = "UTF-8";
    public static final String RSA_ALGORITHM = "RSA";


    public static void main (String[] args) throws Exception {
        Date date = new Date();
        long time = date.getTime();
        System.out.println(time+"");
        String publicK = time + "";
        String privateK = "privateKey";
        Map<String, String> keyMap = RSAUtils.createKeys(1024,publicK,privateK);
        String  publicKey = keyMap.get(publicK);
        String  privateKey = keyMap.get(privateK);
        System.out.println("公钥: \n\r" + publicKey);
        System.out.println("私钥: \n\r" + privateKey);

        System.out.println("公钥加密——私钥解密");
        String str = "卫军,事先没有接到\n" +
                "有关的命令,但看到大批盛装的?";
        System.out.println("\r明文:\r\n" + str);
        System.out.println("\r明文大小:\r\n" + str.getBytes().length);
        String encodedData = RSAUtils.publicEncrypt(str, RSAUtils.getPublicKey(publicKey));
        System.out.println("密文:\r\n" + encodedData);
        String decodedData = RSAUtils.privateDecrypt(encodedData, RSAUtils.getPrivateKey(privateKey));
        System.out.println("解密后文字: \r\n" + decodedData);

        System.out.println("-----------------------------------------------");
    }


    public static Map<String, String> createKeys(int keySize,String publicK,String privateK){
        //为RSA算法创建一个KeyPairGenerator对象
        KeyPairGenerator kpg;
        try{
            kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM);
        }catch(NoSuchAlgorithmException e){
            throw new IllegalArgumentException("No such algorithm-->[" + RSA_ALGORITHM + "]");
        }

        //初始化KeyPairGenerator对象,密钥长度
        kpg.initialize(keySize);
        //生成密匙对
        KeyPair keyPair = kpg.generateKeyPair();
        //得到公钥
        Key publicKey = keyPair.getPublic();
        String publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded());
        //得到私钥
        Key privateKey = keyPair.getPrivate();
        String privateKeyStr = Base64.encodeBase64URLSafeString(privateKey.getEncoded());
        Map<String, String> keyPairMap = new HashMap<String, String>();
        keyPairMap.put(publicK, publicKeyStr);
        keyPairMap.put(privateK, privateKeyStr);

        return keyPairMap;
    }

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

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

    /**
     * 公钥加密
     * @param data
     * @param publicKey
     * @return
     */
    public static String publicEncrypt(String data, RSAPublicKey publicKey){
        try{
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), publicKey.getModulus().bitLength()));
        }catch(Exception e){
            throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * 私钥解密
     * @param data
     * @param privateKey
     * @return
     */

    public static String privateDecrypt(String data, RSAPrivateKey privateKey){
        try{
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), privateKey.getModulus().bitLength()), CHARSET);
        }catch(Exception e){
            throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * 私钥加密
     * @param data
     * @param privateKey
     * @return
     */

    public static String privateEncrypt(String data, RSAPrivateKey privateKey){
        try{
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), privateKey.getModulus().bitLength()));
        }catch(Exception e){
            throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * 公钥解密
     * @param data
     * @param publicKey
     * @return
     */

    public static String publicDecrypt(String data, RSAPublicKey publicKey){
        try{
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), publicKey.getModulus().bitLength()), CHARSET);
        }catch(Exception 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){
            throw new RuntimeException("加解密阀值为["+maxBlock+"]的数据时发生异常", e);
        }
        byte[] resultDatas = out.toByteArray();
        IOUtils.closeQuietly(out);
        return resultDatas;
    }

}

1.3.2 DH算法

应用于建立连接时生成对称密钥。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
这个过程就是DH算法的核心,也就是生成一个对称密钥。
在这里插入图片描述
这里的随机幂指数 6和15就是所谓的私钥,而母点(G)5和 质数 23就是公钥
当然了,实际上的随机数和质数并没有那么简单,通常都建议直到要有2048比特的长度,
7 %(mod) 1 = 7
公钥是7和1,此时的质数都是1,很简单就能通过余数知道随机数也是1,
但是如果随机数和质数都大一些
7 的 x次方 mod 28 = 7
就没那么容易知道x = 3了
在这里插入图片描述
这其实就是要解决离散对数问题。正向计算简单,逆向计算困难。

1.3.2 单项加密

1.3.2.1 MD5
1.3.2.2 SHA
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值