java-加密解密

金飞
2023-12-01

1、Base64

package ai.saas.framework.common.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Base64Util {

	// 
    public static byte[] decryBASE64ToByteArr(String key) throws Exception{
        return (new BASE64Decoder()).decodeBuffer(key);
    }


    public static String encryptBASE64(byte[] key) throws Exception{
        return (new BASE64Encoder()).encode(key);
    }


}

2、AES

  • AES算法作为DES算法和MD5算法的替代产品,10轮循环到目前为止还没有被破解。
    一般多数人的意见是:它是目前可获得的最安全的加密算法。
    AES与目前使用广泛的加密算法─DES算法的差别在于,
    如果一秒可以解DES,则仍需要花费1490000亿年才可破解AES,由此可知AES的安全性。
    AES 已被列为比任何现今其它对称加密算法更安全的一种算法。
package ai.saas.framework.common.util;

import ai.saas.framework.common.constant.CommonConstant;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import org.yaml.snakeyaml.util.ArrayUtils;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * 2020-12-05
 * AES算法作为DES算法和MD5算法的替代产品,10轮循环到目前为止还没有被破解。
 * 一般多数人的意见是:它是目前可获得的最安全的加密算法。
 * AES与目前使用广泛的加密算法─DES算法的差别在于,
 * 如果一秒可以解DES,则仍需要花费1490000亿年才可破解AES,由此可知AES的安全性。
 * AES 已被列为比任何现今其它对称加密算法更安全的一种算法。
 * 2020-12-05
 */
public class AESUtil {


    public static void main(String[] args) throws Exception {
        // 加密
        String str = "2023-01-01 23:59:59";

        String reEnStr = encryptAes(str, CommonConstant.AES_KEY);
        // vGLm7x0DR8XC4vsa/ljXoAUHEsgAiW2Y5JVsvAnHXkE=
        System.out.println(reEnStr);
        String reDeStr = decryptAes(reEnStr, CommonConstant.AES_KEY);
        System.out.println(reDeStr);
    }






    public static final String algorithm = "AES";
    // AES/CBC/NOPaddin
    // AES 默认模式
    // 使用CBC模式, 在初始化Cipher对象时, 需要增加参数, 初始化向量IV : IvParameterSpec iv = new
    // IvParameterSpec(key.getBytes());
    // NOPadding: 使用NOPadding模式时, 原文长度必须是8byte的整数倍   ECB模式是可重复解密的
    public static final String transformation = "AES/ECB/NOPadding";


    /**
     * AES加密
     *
     * @param str
     *            将要加密的内容
     * @param key
     *            密钥
     * @return 已经加密的字节数组内容 再 base64 之后的字符串
     */
    public static String encryptAes(String str, String key) throws Exception {
        byte[] data = str.getBytes("UTF-8");
        byte[] keyByte = key.getBytes("UTF-8");
        //不足16字节,补齐内容为差值
        int len = 16 - data.length % 16;
        for (int i = 0; i < len; i++) {
            byte[] bytes = { (byte) len };
            data = concat(data, bytes);
        }
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(keyByte, "AES");
            Cipher cipher = Cipher.getInstance(transformation);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] resultByte = cipher.doFinal(data);
            return Base64Util.encryptBASE64(resultByte);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * AES解密
     *
     * @param base64Str
     *            将要解密的字节数组内容 的 base64编码后的字符串
     * @param key
     *            密钥
     * @return 已经解密的内容
     */
    public static String decryptAes(String base64Str, String key) throws Exception {

        try {
            byte[] data = Base64Util.decryBASE64ToByteArr(base64Str);
            data = noPadding(data, -1);
            byte[] keyByte = key.getBytes("UTF-8");
            SecretKeySpec skeySpec = new SecretKeySpec(keyByte, "AES");
            Cipher cipher = Cipher.getInstance(transformation);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] decryptData = cipher.doFinal(data);
            int len = 2 + byteToInt(decryptData[4]) + 3;
            byte[] resultByte = noPadding(decryptData, len);
            String resultStr = new String(resultByte);
            return resultStr.trim();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 合并数组
     *
     * @param firstArray
     *            第一个数组
     * @param secondArray
     *            第二个数组
     * @return 合并后的数组
     */
    public static byte[] concat(byte[] firstArray, byte[] secondArray) {
        if (firstArray == null || secondArray == null) {
            return null;
        }
        byte[] bytes = new byte[firstArray.length + secondArray.length];
        System.arraycopy(firstArray, 0, bytes, 0, firstArray.length);
        System.arraycopy(secondArray, 0, bytes, firstArray.length,
                secondArray.length);
        return bytes;
    }




    /**
     * 去除数组中的补齐
     *
     * @param paddingBytes
     *            源数组
     * @param dataLength
     *            去除补齐后的数据长度
     * @return 去除补齐后的数组
     */
    public static byte[] noPadding(byte[] paddingBytes, int dataLength) {
        if (paddingBytes == null) {
            return null;
        }

        byte[] noPaddingBytes = null;
        if (dataLength > 0) {
            if (paddingBytes.length > dataLength) {
                noPaddingBytes = new byte[dataLength];
                System.arraycopy(paddingBytes, 0, noPaddingBytes, 0, dataLength);
            } else {
                noPaddingBytes = paddingBytes;
            }
        } else {
            int index = paddingIndex(paddingBytes);
            if (index > 0) {
                noPaddingBytes = new byte[index];
                System.arraycopy(paddingBytes, 0, noPaddingBytes, 0, index);
            }
        }

        return noPaddingBytes;
    }



    /**
     * 获取补齐的位置
     *
     * @param paddingBytes
     *            源数组
     * @return 补齐的位置
     */
    private static int paddingIndex(byte[] paddingBytes) {
        for (int i = paddingBytes.length - 1; i >= 0; i--) {
            if (paddingBytes[i] != 0) {
                return i + 1;
            }
        }
        return -1;
    }



    public static int byteToInt(byte b) {
        return (b) & 0xff;
    }






}


3、RSA

非对称加密 唯一广泛接受并实现 数据加密&数字签名 公钥加密、私钥解密 私钥加密、公钥解密

package ai.saas.framework.common.util;

import java.io.UnsupportedEncodingException;
import java.nio.charset.CharsetDecoder;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import ai.saas.framework.common.constant.CommonConstant;
import lombok.SneakyThrows;
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;

/**
 * 非对称加密 唯一广泛接受并实现 数据加密&数字签名 公钥加密、私钥解密 私钥加密、公钥解密
 *
 * @author jjs
 */
public class RSAUtil {

    private static String src = "li123123LS";

    private static RSAPublicKey rsaPublicKey;
    private static RSAPrivateKey rsaPrivateKey;


    static {
        // 1、初始化密钥
        KeyPairGenerator keyPairGenerator;
        try {
            keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(1024);// 64的整倍数
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
            rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();

            System.out.println("Public Key  " + Base64.encodeBase64String(rsaPublicKey.getEncoded()));

            System.out.println("Private Key : " + Base64.encodeBase64String(rsaPrivateKey.getEncoded()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }


    /**
     * 私钥 解密
     *
     * @param ciphertext 密文
     */
    @SneakyThrows
    public static String privateKeyEncryption(String ciphertext) {
        // base64 解码
        //
        byte[] base64 = Base64.decodeBase64(ciphertext);
//        String priKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBALEXi2bqonTQqF9lWS5vOBLOcW5UCrDm8/eYxQt+Pfcdw/1eNR23GybC0NAAGBIt2KHAK2WIYFuWx+Sht5DEkS3IAsQJ3W7exTxAlqtIYJlkGAP5jas1B5MpyY/Taog3wVLfLzWODAvfbVJyviut9FscDSFrH0Cn1/khQGktZf7nAgMBAAECgYAoIfHRjPLsDi1aERm40DOg72/9VMZneK9pORHOnPll+zTjQmo/JbPdgODZgmvyErm5TleHVvSfTPhX894pzKIpoViT/dK/1W8eaJwD5r1l6pVptgm8yjHz5wcTdfB3Pu4OFgkciKKbMkinhx7GdBPcT5kyHUsJ4rLb4xvXy7RC4QJBANjJxkNcnsuWq6pzZnO+ktdRqtSoNTnTswqa0NYdXUnvkBilzFqzfzu7SZkN61picjYxE0bGdsnQGSIKfxemuD0CQQDRH6ormeGD7Z6WXyzKIW2gOrm/jcfSi61/czyGOziXRL8wULE4UyymYw8g3vhdmKjsqMxS3bt/E/cPavQXDmHzAkABdJlYKm8GfuR4KH4vmL/zoiC7fMWetcUl9RQh2+CcdndJMxPEKCBajk9YL7e8y5xosLuoZfy2Lid9CwT/a6chAkBdDCHDVKyq7sdpUN+08Dq+2GJdgNAwNkX0N2nur9r2M3h+Huk7joaHYfwRPCR2QL6ozlJbbJ1IZbHAAm6o85VRAkBQYUGoP40qE8eKUsZfTLyrOGy6FUiX8p+kJRv9RoYVa/aQDxisdo1+lwe9rhnpWkyjE3jRm3XDKScEhl6MAMnN";

        // String 转 私钥
        PrivateKey rsaPrivateKey = getPrivateKey(CommonConstant.priKey);
        //私钥解密
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] result = cipher.doFinal(base64);
        System.out.println("公钥加密,私钥解密 --解密: " + new String(result));
        return new String(result);

    }
    /**
     * 公钥加密,私钥解密
     *
     * @author jijs
     */
    @SneakyThrows
    public static void pubEn2PriDe() {

        String pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxF4tm6qJ00KhfZVkubzgSznFuVAqw5vP3mMULfj33HcP9XjUdtxsmwtDQABgSLdihwCtliGBblsfkobeQxJEtyALECd1u3sU8QJarSGCZZBgD+Y2rNQeTKcmP02qIN8FS3y81jgwL321Scr4rrfRbHA0hax9Ap9f5IUBpLWX+5wIDAQAB";
        String priKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBALEXi2bqonTQqF9lWS5vOBLOcW5UCrDm8/eYxQt+Pfcdw/1eNR23GybC0NAAGBIt2KHAK2WIYFuWx+Sht5DEkS3IAsQJ3W7exTxAlqtIYJlkGAP5jas1B5MpyY/Taog3wVLfLzWODAvfbVJyviut9FscDSFrH0Cn1/khQGktZf7nAgMBAAECgYAoIfHRjPLsDi1aERm40DOg72/9VMZneK9pORHOnPll+zTjQmo/JbPdgODZgmvyErm5TleHVvSfTPhX894pzKIpoViT/dK/1W8eaJwD5r1l6pVptgm8yjHz5wcTdfB3Pu4OFgkciKKbMkinhx7GdBPcT5kyHUsJ4rLb4xvXy7RC4QJBANjJxkNcnsuWq6pzZnO+ktdRqtSoNTnTswqa0NYdXUnvkBilzFqzfzu7SZkN61picjYxE0bGdsnQGSIKfxemuD0CQQDRH6ormeGD7Z6WXyzKIW2gOrm/jcfSi61/czyGOziXRL8wULE4UyymYw8g3vhdmKjsqMxS3bt/E/cPavQXDmHzAkABdJlYKm8GfuR4KH4vmL/zoiC7fMWetcUl9RQh2+CcdndJMxPEKCBajk9YL7e8y5xosLuoZfy2Lid9CwT/a6chAkBdDCHDVKyq7sdpUN+08Dq+2GJdgNAwNkX0N2nur9r2M3h+Huk7joaHYfwRPCR2QL6ozlJbbJ1IZbHAAm6o85VRAkBQYUGoP40qE8eKUsZfTLyrOGy6FUiX8p+kJRv9RoYVa/aQDxisdo1+lwe9rhnpWkyjE3jRm3XDKScEhl6MAMnN";

        // String 转 公钥
        PublicKey rsaPublicKey = getPublicKey(pubKey);

        //公钥加密
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] result = cipher.doFinal(src.getBytes());
        System.out.println("公钥加密,私钥解密 --加密: " + Base64.encodeBase64String(result));

        // String 转 私钥
        PrivateKey rsaPrivateKey = getPrivateKey(priKey);

        //私钥解密
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
        keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        result = cipher.doFinal(result);
        System.out.println("公钥加密,私钥解密 --解密: " + new String(result));
    }


    /**
     * String转公钥PublicKey
     *
     * @param key
     * @return
     * @throws Exception
     */
    public static PublicKey getPublicKey(String key) throws Exception {
        byte[] keyBytes;
        keyBytes = (new BASE64Decoder()).decodeBuffer(key);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }

    /**
     * String转私钥PrivateKey
     *
     * @param key
     * @return
     * @throws Exception
     */
    public static PrivateKey getPrivateKey(String key) throws Exception {
        byte[] keyBytes;
        keyBytes = (new BASE64Decoder()).decodeBuffer(key);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }



    /**
     * 私钥加密,公钥解密
     *
     * @author jijs
     */
    @SneakyThrows
    public static void priEn2PubDe() {

        //私钥加密
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        byte[] result = cipher.doFinal(src.getBytes());
        System.out.println("私钥加密,公钥解密 --加密 : " + Base64.encodeBase64String(result));

        //公钥解密
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());
        keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
        cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        result = cipher.doFinal(result);
        System.out.println("私钥加密,公钥解密   --解密: " + new String(result));
    }

    public static void main(String[] args) {
        pubEn2PriDe();  //公钥加密,私钥解密
        priEn2PubDe();  //私钥加密,公钥解密
    }
}

4、 MD5

不可解密

// MD5加密
    public static String MD5(String inStr){

        MessageDigest md5 = null;
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(inStr.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException var7) {
            throw new RuntimeException("MD5 should be supported?", var7);
        } catch (UnsupportedEncodingException var8) {
            throw new RuntimeException("UTF-8 should be supported?", var8);
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        byte[] var6 = hash;
        int var5 = hash.length;

        for(int var4 = 0; var4 < var5; ++var4) {
            byte b = var6[var4];
            if((b & 255) < 16) {
                hex.append("0");
            }

            hex.append(Integer.toHexString(b & 255));
        }
        System.out.println(hex.toString());
        return hex.toString();

    }

5、sha - 256

 MessageDigest messageDigest;

        String encodeStr = "";

        try {
            messageDigest = MessageDigest.getInstance("SHA-256");

            messageDigest.update(参数.getBytes("UTF-8"));

            encodeStr = byte2Hex(messageDigest.digest());

        } catch (Exception e) {
            System.out.println("getSHA256 is error" + e.getMessage());

        }
        System.out.println("sha256:"+encodeStr);
        return encodeStr;
    }

    private static String byte2Hex(byte[] bytes) {
        StringBuilder builder = new StringBuilder();

        String temp;

        for (int i = 0; i < bytes.length; i++) {
            temp = Integer.toHexString(bytes[i] & 0xFF);

            if (temp.length() == 1) {
                builder.append("0");

            }

            builder.append(temp);

        }

        return builder.toString();

    }

 类似资料: