欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

加密工具(md5、SHA1、SHA256、RSA、AES、DES)

程序员文章站 2022-03-14 23:20:04
...

自己写的加密util

import cn.hutool.core.lang.Assert;
import org.springframework.util.DigestUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * @author zhang
 */
public class EncryptUtil {

    public static final String RSA = "RSA";
    public static final String AES = "AES";
    public static final String DES = "DES";
    public static final String BASE_64 = "base64";

    public static String md5(String data) {
        return DigestUtils.md5DigestAsHex(data.getBytes());
    }

    public static String sha1(String data) {
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(data.getBytes(StandardCharsets.UTF_8));
            return new BigInteger(1, crypt.digest()).toString(16);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String sha256(String data) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(data.getBytes(StandardCharsets.UTF_8));
            byte[] bytes = messageDigest.digest();
            return parseByte2HexStr(bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String rsaSHA1(String data, String privateKey, String outputEncoding) {
        try {
            byte[] keyBytes = Base64.getDecoder().decode(privateKey.getBytes());
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
            PrivateKey priKey = KeyFactory.getInstance(RSA).generatePrivate(keySpec);
            Signature signature = Signature.getInstance("SHA1withRSA");
            signature.initSign(priKey);
            signature.update(data.getBytes(StandardCharsets.UTF_8));
            byte[] signs = signature.sign();
            if (BASE_64.equals(outputEncoding)) {
                return Base64.getEncoder().encodeToString(signs);
            }
            return parseByte2HexStr(signs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String rsaSHA256(String data, String privateKey, String outputEncoding) {
        try {
            byte[] keyBytes = Base64.getDecoder().decode(privateKey.getBytes());
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
            PrivateKey priKey = KeyFactory.getInstance(RSA).generatePrivate(keySpec);
            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initSign(priKey);
            signature.update(data.getBytes(StandardCharsets.UTF_8));
            byte[] signs = signature.sign();
            if (BASE_64.equals(outputEncoding)) {
                return Base64.getEncoder().encodeToString(signs);
            }
            return parseByte2HexStr(signs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String rsaPublicEncrypt(String publicKey, String data, String outputEncoding) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(RSA);
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey));
            RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
            Cipher cipher = Cipher.getInstance(RSA);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] bytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
            if (BASE_64.equals(outputEncoding)) {
                return Base64.getEncoder().encodeToString(bytes);
            }
            return parseByte2HexStr(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String rsaPublicDecrypt(String publicKey, String data, String inputEncoding) {
        try {
            byte[] dataBytes;
            if (BASE_64.equals(inputEncoding)) {
                dataBytes = Base64.getDecoder().decode(data);
            } else {
                dataBytes = parseHexStr2Byte(data);
            }

            KeyFactory keyFactory = KeyFactory.getInstance(RSA);
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey));
            RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
            Cipher cipher = Cipher.getInstance(RSA);
            cipher.init(Cipher.DECRYPT_MODE, key);
            return new String(cipher.doFinal(dataBytes));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String rsaPrivateEncrypt(String privateKey, String data, String outputEncoding) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(RSA);
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));
            RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
            Cipher cipher = Cipher.getInstance(RSA);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] bytes = cipher.doFinal(data.getBytes());
            if (BASE_64.equals(outputEncoding)) {
                return Base64.getEncoder().encodeToString(bytes);
            }
            return parseByte2HexStr(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String rsaPrivateDecrypt(String privateKey, String data, String inputEncoding) {
        try {
            byte[] dataBytes;
            if (BASE_64.equals(inputEncoding)) {
                dataBytes = Base64.getDecoder().decode(data);
            } else {
                dataBytes = parseHexStr2Byte(data);
            }
            KeyFactory keyFactory = KeyFactory.getInstance(RSA);
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));
            RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
            Cipher cipher = Cipher.getInstance(RSA);
            cipher.init(Cipher.DECRYPT_MODE, key);
            return new String(cipher.doFinal(dataBytes));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String aesEncrypt(String data, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance(AES);
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(password.getBytes());
            kgen.init(128, random);
            Cipher cipher = Cipher.getInstance(AES);
            cipher.init(Cipher.ENCRYPT_MODE, kgen.generateKey());
            return Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String aesDecrypt(String data, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance(AES);
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(password.getBytes());
            kgen.init(128, random);
            Cipher cipher = Cipher.getInstance(AES);
            cipher.init(Cipher.DECRYPT_MODE, kgen.generateKey());
            return new String(cipher.doFinal(Base64.getDecoder().decode(data)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String desEncrypt(String data, String password) {
        try {
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
            Cipher cipher = Cipher.getInstance(DES);
            cipher.init(Cipher.ENCRYPT_MODE, keyFactory.generateSecret(new DESKeySpec(password.getBytes())), new SecureRandom());
            return Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String desDecrypt(String data, String password) {
        try {
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
            Cipher cipher = Cipher.getInstance(DES);
            cipher.init(Cipher.DECRYPT_MODE, keyFactory.generateSecret(new DESKeySpec(password.getBytes())), new SecureRandom());
            return new String(cipher.doFinal(Base64.getDecoder().decode(data.getBytes())));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String parseByte2HexStr(byte[] buf) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return new byte[0];
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    private static boolean verifyWhenSha1Sign(String content, String sign, PublicKey publicKey) throws Exception {
        byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8);
        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initVerify(publicKey);
        signature.update(contentBytes);
        return signature.verify(Base64.getDecoder().decode(sign));
    }

    private static boolean verifyWhenSha256Sign(String content, String sign, PublicKey publicKey) throws Exception {
        byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8);
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initVerify(publicKey);
        signature.update(contentBytes);
        return signature.verify(Base64.getDecoder().decode(sign));
    }

    public static void main(String[] args) throws Exception {
        String data = "123456";
        String password = "aaaaaaaaa";
        //MD5
        Assert.isTrue("e10adc3949ba59abbe56e057f20f883e".equalsIgnoreCase(md5(data)));
        //sha1
        Assert.isTrue("7c4a8d09ca3762af61e59520943dc26494f8941b".equalsIgnoreCase(sha1(data)));
        //sha256
        Assert.isTrue("8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92".equalsIgnoreCase(sha256(data)));

        //创建rsa公钥私钥
        KeyPairGenerator ****** = KeyPairGenerator.getInstance(RSA);
        KeyPair keyPair = ******.generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();
        String privateKeyStr = new String(Base64.getEncoder().encode(privateKey.getEncoded()), StandardCharsets.UTF_8);
        String publicKeyStr = new String(Base64.getEncoder().encode(publicKey.getEncoded()), StandardCharsets.UTF_8);

        //sh1签名
        String sha1Sign = rsaSHA1(data, privateKeyStr, BASE_64);
        Assert.isTrue(verifyWhenSha1Sign(data, sha1Sign, publicKey));

        //sh256签名
        String sha256Sign = rsaSHA256(data, privateKeyStr, BASE_64);
        Assert.isTrue(verifyWhenSha256Sign(data, sha256Sign, publicKey));

        //aes加解密
        Assert.isTrue(data.equalsIgnoreCase(aesDecrypt(aesEncrypt(data, password), password)));

        //des加解密
        Assert.isTrue(data.equalsIgnoreCase(desDecrypt(desEncrypt(data, password), password)));

        //公钥加密私钥解密
        String pass = rsaPublicEncrypt(publicKeyStr, data, BASE_64);
        String dePass2 =  rsaPrivateDecrypt(privateKeyStr, pass, BASE_64);
        Assert.isTrue(data.equalsIgnoreCase(dePass2));

        //私钥加密公钥解密
        String pass2 = rsaPrivateEncrypt(privateKeyStr, data, BASE_64);
        String dePass = rsaPublicDecrypt(publicKeyStr, pass2, BASE_64);
        Assert.isTrue(data.equalsIgnoreCase(dePass));

    }
}