MD5、AES、RSA三种加密算法的使用

一、简介 

工作之后,发现加密算法的使用非常频繁,加密算法可以保护数据免受未经授权的访问或监视、可以确保数据在传输过程中不被篡改、可以验证数据传输的双方身份。

二、MD5算法

1、介绍

MD5信息摘要算法,一种不可逆的加密算法,MD5算法的输出是一个128位(16字节)的散列值,通常用32位十六进制数表示。由于是不可逆算法,所以解密只能进行枚举。

2、主要代码

public class MD5Untils {
    public static String encryptByMD5(String text){
        if(StringUtils.isEmpty(text)){
            return null;
        }
        try {
            //使用MD5算法创建MessageDigest对象
            MessageDigest md = MessageDigest.getInstance("MD5");
            //更新MessageDigest对象中的字节数据
            md.update(text.getBytes());
            //对更新后的数据计算哈希值,存储在byte数组中
            byte[] digest = md.digest();
            //将byte数组转化为十六进制字符串
            StringBuffer buffer = new StringBuffer();
            for(byte b : digest){
                buffer.append(String.format("%02x",b & 0xff));
            }
            return Convert.toStr(buffer);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

 三、AES加密算法

1、介绍

AES加密算法是一种对称加密算法,支持三种长度的密钥:128位,192位,256位。其加密解密都是用同一个密钥,需要传输密钥,不太安全,但速度快。秘钥固定在客户端代码和后端代码中,登录时使用固定密码将明文密码加密传输到后端,后端使用相同的固定秘钥解密,然后查询用户存储在数据库的密码,进行对比认证。

2、主要代码

public class AesUtil {

    private static final String DEFAULT_CHARSET = "UTF-8";
    /**
     * 解密
     *
     * @param content    内容
     * @param aesTextKey 文本密钥
     * @return byte[]
     */

    public static byte[] decrypt(byte[] content, String aesTextKey) throws Exception {
        return decrypt(content, Objects.requireNonNull(aesTextKey).getBytes(DEFAULT_CHARSET));
    }


    public static String decryptStr(String encrypted, String aesTextKey)  {
        try {
            byte[] content = Base64.getDecoder().decode(encrypted);
            byte[] decryptStr = decrypt(content, aesTextKey);
            return new String(decryptStr, DEFAULT_CHARSET);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    
    /**
     * 解密
     *
     * @param encrypted 内容
     * @param aesKey    密钥
     * @return byte[]
     */

    public static byte[] decrypt(byte[] encrypted, byte[] aesKey) {
        return Pkcs7Encoder.decode(aes(encrypted, aesKey, Cipher.DECRYPT_MODE));
    }


    /**
     * 加密
     *
     * @param content 内容
     * @param aesKey  密钥
     * @return byte[]
     */
    public static byte[] encrypt(byte[] content, byte[] aesKey) {
        return aes(Pkcs7Encoder.encode(content), aesKey, Cipher.ENCRYPT_MODE);
    }
    
    public static String encryptStr(String content, String aesTextKey) {
        try {
            byte[] bytes = encrypt(content.getBytes(), aesTextKey.getBytes());
            return Base64.getEncoder().encodeToString(bytes);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("加密失败");
            return null;
        }
    }


    /**
     * ase加密
     *
     * @param encrypted 内容
     * @param aesKey    密钥
     * @param mode      模式
     * @return byte[]
     */
    private static byte[] aes(byte[] encrypted, byte[] aesKey, int mode) {
        Assert.isTrue(aesKey.length == 32, "IllegalAesKey, aesKey's length must be 32");
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
            IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16));
            cipher.init(mode, keySpec, iv);
            return cipher.doFinal(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 提供基于PKCS7的填充算法.
     */
    private static class Pkcs7Encoder {
        private static final int BLOCK_SIZE = 32;

        private static byte[] encode(byte[] src) {
            int count = src.length;
            // 计算需要填充的位数
            int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE);
            // 获得补位所用的字符
            byte pad = (byte) (amountToPad & 0xFF);
            byte[] pads = new byte[amountToPad];
            for (int index = 0; index < amountToPad; index++) {
                pads[index] = pad;
            }
            int length = count + amountToPad;
            byte[] dest = new byte[length];
            System.arraycopy(src, 0, dest, 0, count);
            System.arraycopy(pads, 0, dest, count, amountToPad);
            return dest;
        }

        private static byte[] decode(byte[] decrypted) {
            int pad = decrypted[decrypted.length - 1];
            if (pad < 1 || pad > BLOCK_SIZE) {
                pad = 0;
            }
            if (pad > 0) {
                return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad);
            }
            return decrypted;
        }
    }
}

四、RSA加密算法

1、介绍

RSA加密算法是一种非对称加密算法,有公钥和私钥,公钥加密,私钥解密,安全,速度慢。在后端使用非对称算法RSA生成一对公私钥,公钥固定存储在客户端代码中,私钥存储在后端代码中,登录时对输入的密码使用公钥加密传输,后端收到加密的秘钥后,使用私钥进行解密,然后查询该账号对应的密码,进行对比。

2、主要代码

public class RSAUntil {

    private static final String ALGORITHM = "RSA";

    //加密方法
    public static String encrypt(String plainText, PublicKey publicKey) throws Exception{
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE,publicKey);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    //解密方法
    public static String decrypt(String encryptedText, PrivateKey privateKey) throws Exception{
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE,privateKey);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes);
    }

    //生成公钥和秘钥
    public static Map<String,String> generateKeyPair(){
        HashMap<String,String> map = new HashMap<>();
        try{
            //创建KeyPairGenerator对象,指定算法为RSA
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
            //设置秘钥长度为1024位数
            keyPairGenerator.initialize(1024);
            //生成Keypair对象,即公钥和密钥
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            //获取公钥和密钥
            PublicKey publicKey = keyPair.getPublic();
            PrivateKey privateKey = keyPair.getPrivate();
            //将公钥和密钥转换成字符串格式
            String publicKeyStr = Base64.getEncoder().encodeToString(publicKey.getEncoded());
            String privateKeyStr = Base64.getEncoder().encodeToString(privateKey.getEncoded());

            map.put("publicKey",publicKeyStr);
            map.put("privateKey",privateKeyStr);
        }catch(Exception e){
            e.printStackTrace();
        }
        return map;
    }

    //从字符串格式的公钥创建PublicKey对象
    public static PublicKey getPublicKeyFromStr(String publicKeyStr)throws Exception{
        byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyStr);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        return keyFactory.generatePublic(keySpec);
    }

    //从字符串格式的密钥创建PrivateKey对象
    public static PrivateKey getPrivateKeyFromStr(String privateKeyStr)throws Exception{
        byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyStr);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        return keyFactory.generatePrivate(keySpec);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值