0
点赞
收藏
分享

微信扫一扫

常用的加密有哪些?在Java中如何实现?(MD5、AES、RSA)

修炼之士 2022-03-12 阅读 28

参考:
https://blog.csdn.net/qq_41570658/article/details/107694782
https://blog.csdn.net/qq_30054961/article/details/82456069
https://www.html.cn/qa/other/21683.html

一、MD5加密

1、使用spirng自带MD5进行加密

// secureRandom是比Random安全的随机数
SecureRandom sr1 = new SecureRandom();
// 生成6位随机数,sr1.nextInt(900000)是生成900000以内的随机数
String salt = String.valueOf(sr1.nextInt(900000) + 100000);
// spring自带的md5加密,加入随机盐,使得密文不重复,记得把盐保存到用户表中
System.out.println(DigestUtils.md5DigestAsHex(("swp123"+salt).getBytes()));

二、对称加密

采用单钥密码系统的加密方法,同一个密钥可以同时用作信息的加密和解密,这种加密方法称为对称加密,也称为单密钥加密。

1、DES
已破解,不再安全,基本没有企业在用了
是对称加密算法的基石,具有学习价值
密钥长度56(JDK)、56/64(BC)
2、DESede(三重DES)
早于AES出现来替代DES
计算密钥时间太长、加密效率不高,所以也基本上不用
密钥长度112/168(JDK)、128/192(BC)
3、AES
最常用的对称加密算法
密钥建立时间短、灵敏性好、内存需求低(不管怎样,反正就是好)
实际使用中,使用工作模式为CTR(最好用BC去实现),此工作模式需要引入IV参数(16位的字节数组)
密钥长度128/192/256,其中192与256需要配置无政策限制权限文件(JDK6)
填充模式最常用的两种PKCS5Padding和PKCS7Padding,其中后者只有BC独有。

1、AES加解密

package com.example.demo.config;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * @Filename: ASEUtils
 * @Author: sheng
 * <li>Date: 2022/3/9 10:24</li>
 * <li>Version: 1.0</li>
 * <li>Content: create</li>
 */
public class ASEUtils {

    // 长度为16字节 ,自己定义(采用密钥长度128位,所以是16字节)
    private static final String KEY = "xxxxxxxxxxxxxxxx";

    //参数分别代表 算法名称/加密模式/数据填充方式
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";

    /**
     * 加密
     *
     * @param content    加密的字符串
     * @param encryptKey key值
     * @return
     * @throws Exception
     */
    public static String encrypt(String content, String encryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
        byte[] b = cipher.doFinal(content.getBytes("utf-8"));
        // 采用base64算法进行转码,避免出现中文乱码
        return Base64.encodeBase64String(b);

    }

    /**
     * 解密
     *
     * @param encryptStr 解密的字符串
     * @param decryptKey 解密的key值
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptStr, String decryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
        // 采用base64算法进行转码,避免出现中文乱码
        byte[] encryptBytes = Base64.decodeBase64(encryptStr);
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }

    public static String encrypt(String content) throws Exception {
        return encrypt(content, KEY);
    }

    public static String decrypt(String encryptStr) throws Exception {
        return decrypt(encryptStr, KEY);
    }


    public static void main(String[] args) throws Exception {
        Map map = new HashMap<String, String>();
        map.put("key", "value");
        map.put("中文", "汉字");
        String content = JSONObject.toJSONString(map);
        System.out.println("加密前:" + content);

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

        String decrypt = decrypt(encrypt, KEY);
        System.out.println("解密后:" + decrypt);
    }
}

三、非对称加密

非对称加密算法需要两个密钥:公开密钥(publickey:简称公钥)和私有密钥(privatekey:简称私钥)。公钥与私钥是一对,如果用公钥对数据进行加密,只有用对应的私钥才能解密。因为加密和解密使用的是两个不同的密钥,所以这种算法叫作非对称加密算法。非对称加密常用的是RSA

1、RSA加解密

package com.example.demo.config;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import javax.crypto.Cipher;

/**
 * @Filename: ASEUtils
 * @Author: sheng
 * <li>Date: 2022/3/9 10:24</li>
 * <li>Version: 1.0</li>
 * <li>Content: create</li>
 */
public class RSAUtils {


        /** 指定加密算法为DESede */
        private static String ALGORITHM = "RSA";
        /** 指定key的大小 */
        private static int KEYSIZE = 1024;
        /** 指定公钥存放文件 */
        private static String PUBLIC_KEY_FILE = "public.keystore";
        /** 指定私钥存放文件 */
        private static String PRIVATE_KEY_FILE = "private.keystore";

        /**
         * 生成密钥对
         */
        private static void generateKeyPair() throws Exception {
            /** RSA算法要求有一个可信任的随机数源 */
            SecureRandom sr = new SecureRandom();
            /** 为RSA算法创建一个KeyPairGenerator对象 */
            KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGORITHM);
            /** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */
            kpg.initialize(KEYSIZE, sr);
            /** 生成密匙对 */
            KeyPair kp = kpg.generateKeyPair();
            /** 得到公钥 */
            Key publicKey = kp.getPublic();
            /** 得到私钥 */
            Key privateKey = kp.getPrivate();
            /** 用对象流将生成的密钥写入文件 */
            ObjectOutputStream oos1 = new ObjectOutputStream(new FileOutputStream(PUBLIC_KEY_FILE));
            ObjectOutputStream oos2 = new ObjectOutputStream(new FileOutputStream(PRIVATE_KEY_FILE));
            oos1.writeObject(publicKey);
            oos2.writeObject(privateKey);
            /** 清空缓存,关闭文件输出流 */
            oos1.close();
            oos2.close();
        }

        /**
         * 加密方法 source: 源数据
         */
        public static String encrypt(String source) throws Exception {
            generateKeyPair();
            /** 将文件中的公钥对象读出 */
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_FILE));
            Key key = (Key) ois.readObject();
            ois.close();

            /** 得到Cipher对象来实现对源数据的RSA加密 */
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] b = source.getBytes();
            /** 执行加密操作 */
            byte[] b1 = cipher.doFinal(b);
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(b1);
        }

        /**
         * 解密算法 cryptograph:密文
         */
        public static String decrypt(String cryptograph) throws Exception {
            /** 将文件中的私钥对象读出 */
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE));
            Key key = (Key) ois.readObject();

            /** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key);
            BASE64Decoder decoder = new BASE64Decoder();

            byte[] b1 = decoder.decodeBuffer(cryptograph);
            /** 执行解密操作 */
            byte[] b = cipher.doFinal(b1);
            return new String(b);
        }

        public static void main(String[] args) throws Exception {
            String source = "非对称加密RSA";// 要加密的字符串
            System.out.println("加密前--->" +source);
            String cryptograph = encrypt(source);// 生成的密文
            System.out.println("加密后--->" +cryptograph);
            String target = decrypt(cryptograph);// 解密密文
            System.out.println("解密后--->" + target);
        }

}

四、Base64编码

Base 64 Encoding有什么用?举个简单的例子,你使用SMTP协议 (Simple Mail Transfer Protocol 简单邮件传输协议)来发送邮件。因为这个协议是基于文本的协议,所以如果邮件中包含一幅图片,我们知道图片的存储格式是二进制数据(binary data),而非文本格式,我们必须将二进制的数据编码成文本格式,这时候Base 64 Encoding就派上用场了。

public void testJDKBase64(){
    String encoderStr = java.util.Base64.getEncoder().encodeToString(s.getBytes());
    System.out.println("encode :"+encoderStr);
 
    String decodeStr = new String(java.util.Base64.getDecoder().decode(encoderStr));
    System.out.println("decodeStr :"+decodeStr);
}
 
public void testCodecBase64(){
    String encoderStr = org.apache.commons.codec.binary.Base64.encodeBase64String(s.getBytes());
    System.out.println("encode :"+encoderStr);
 
    String decodeStr = new String(org.apache.commons.codec.binary.Base64.decodeBase64(encoderStr));
    System.out.println("decodeStr :"+decodeStr);
}

五、应用场景

  1. Base64应用场景:图片转码(应用于邮件,img标签,http加密)
  2. MD5应用场景:密码加密、imei加密、文件校验
  3. 非对称加密:电商订单付款、银行相关业务
举报

相关推荐

0 条评论