• AES256,ECC加解密


    1、AES256对称加密:

    import org.apache.commons.codec.binary.Base64;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.SecretKeySpec;
    import java.security.Provider;
    import java.security.SecureRandom;
    import java.security.Security;
    import java.util.Arrays;
    /**
     * @Description:
     * @author: caib
     * @Date: 2021/12/31/10:06
     */
    public class AESUtils {
    
        /***默认向量常量  初始向量IV的长度规定为128位16个字节**/
        public static final String IV = "c551aq0YQ92QALbc";
        private final static Logger logger = LoggerFactory.getLogger(AESUtils.class);
    
        /**
         * 使用PKCS7Padding填充必须添加一个支持PKCS7Padding的Provider
         * 类加载的时候就判断是否已经有支持256位的Provider,如果没有则添加进去
         */
        static {
            if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
                Security.addProvider(new BouncyCastleProvider());
            }
        }
    
        /**
         * 加密 128位
         *
         * @param content 需要加密的原内容
         * @param pkey    密匙
         * @return
         */
        public static byte[] aesEncrypt(String content, String pkey) {
            try {
                //SecretKey secretKey = generateKey(pkey);
                //byte[] enCodeFormat = secretKey.getEncoded();
                SecretKeySpec skey = new SecretKeySpec(pkey.getBytes(), "AES");
                // "算法/加密/填充"
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
                IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
                //初始化加密器
                cipher.init(Cipher.ENCRYPT_MODE, skey, iv);
                return cipher.doFinal(content.getBytes("UTF-8"));
            } catch (Exception e) {
                logger.info("aesEncrypt() method error:", e);
            }
            return null;
        }
    
        /**
         * 获得密钥
         *
         * @param secretKey
         * @return
         * @throws Exception
         */
        private static SecretKey generateKey(String secretKey) throws Exception {
            //防止linux下 随机生成key
            Provider p = Security.getProvider("SUN");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG", p);
            secureRandom.setSeed(secretKey.getBytes());
            KeyGenerator kg = KeyGenerator.getInstance("AES");
            kg.init(secureRandom);
            // 生成密钥
            return kg.generateKey();
        }
    
        /**
         * @param content 加密前原内容
         * @param pkey    长度为16个字符,128位
         * @return base64EncodeStr   aes加密完成后内容
         * @throws
         * @Title: aesEncryptStr
         * @Description: aes对称加密
         */
        public static String aesEncryptStr(String content, String pkey) {
            byte[] aesEncrypt = aesEncrypt(content, pkey);
            System.out.println("加密后的byte数组:" + Arrays.toString(aesEncrypt));
            String base64EncodeStr = Base64.encodeBase64String(aesEncrypt);
            System.out.println("加密后 base64EncodeStr:" + base64EncodeStr);
            return base64EncodeStr;
        }
    
        /**
         * @param content base64处理过的字符串
         * @param pkey    密匙
         * @return String    返回类型
         * @throws Exception
         * @throws
         * @Title: aesDecodeStr
         * @Description: 解密 失败将返回NULL
         */
        public static String aesDecodeStr(String content, String pkey) throws Exception {
            try {
                System.out.println("待解密内容:" + content);
                byte[] base64DecodeStr = Base64.decodeBase64(content);
                System.out.println("base64DecodeStr:" + Arrays.toString(base64DecodeStr));
                byte[] aesDecode = aesDecode(base64DecodeStr, pkey);
                System.out.println("aesDecode:" + Arrays.toString(aesDecode));
                if (aesDecode == null) {
                    return null;
                }
                String result;
                result = new String(aesDecode, "UTF-8");
                System.out.println("aesDecode result:" + result);
                return result;
            } catch (Exception e) {
                System.out.println("Exception:" + e.getMessage());
                throw new Exception("解密异常");
            }
        }
    
        /**
         * 解密 128位
         *
         * @param content 解密前的byte数组
         * @param pkey    密匙
         * @return result  解密后的byte数组
         * @throws Exception
         */
        public static byte[] aesDecode(byte[] content, String pkey) throws Exception {
            //SecretKey secretKey = generateKey(pkey);
            //byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec skey = new SecretKeySpec(pkey.getBytes(), "AES");
            IvParameterSpec iv = new IvParameterSpec(IV.getBytes("UTF-8"));
            // 创建密码器
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            // 初始化解密器
            cipher.init(Cipher.DECRYPT_MODE, skey, iv);
            // 解密
            byte[] result = cipher.doFinal(content);
            return result;
        }public static void main(String[] args) throws Exception {
           //32 位加密密钥 不满32位,以"0" 补充
            String pkey = "abcddadccaedcae";
            System.out.println(pkey);
            //明文
            String content = "hello world-----";
            //密匙 密钥为32为
            System.out.println("待加密报文:" + content);
            System.out.println("密匙:" + pkey);
            String aesEncryptStr = aesEncryptStr(content, pkey);
            System.out.println("加密报文:" + aesEncryptStr);
            String aesDecodeStr = aesDecodeStr(aesEncryptStr, pkey);
            System.out.println("解密报文:" + aesDecodeStr);
            System.out.println("加解密前后内容是否相等:" + aesDecodeStr.equals(content));
        }
    
    }
    
     

     2、ECC非对称加密

    参考:
    https://blog.csdn.net/zhouqilong970/article/details/78126319 https://www.cnblogs.com/xinzhao/p/8963724.html

    注:初始化Cipher时使用
    Cipher cipher = new NullCipher();
    import cn.hutool.core.codec.Base64Decoder;
    import org.bouncycastle.jce.interfaces.IESKey;
    import sun.misc.BASE64Decoder;
    
    import javax.crypto.Cipher;
    import javax.crypto.NullCipher;
    import java.io.File;
    import java.io.FileInputStream;
    import java.security.*;
    import java.security.cert.CertificateFactory;
    import java.security.cert.X509Certificate;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;
    import java.util.Base64;
    import java.security.interfaces.ECPrivateKey;
    import java.security.interfaces.ECPublicKey;
    
    public class EccSecurityUtils {
    
        private final static String ALGORITHM = "EC";
        private final static String PROVIDER= "BC";
        private final static String PUBLIC_KEY="PUBLIC_KEY";
        private final static String PRIVATE_KEY="PRIVATE_KEY";
    
    
        /**
         * @see org.bouncycastle.jcajce.provider.asymmetric.ec.KeyPairGeneratorSpi.ecParameters (line #173)
         * 192, 224, 239, 256, 384, 521
         * */
        private final static int KEY_SIZE = 256;
        private final static String SIGNATURE = "SHA256withECDSA";
    
        static {
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        }
    
        private static void printProvider() {
            Provider provider = new org.bouncycastle.jce.provider.BouncyCastleProvider();
            for (Provider.Service service : provider.getServices()) {
                System.out.println(service.getType() + ": "
                        + service.getAlgorithm());
            }
        }
    
        //生成秘钥对
        public static KeyPair getKeyPair() throws Exception {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC", "BC");//BouncyCastle
            keyPairGenerator.initialize(KEY_SIZE, new SecureRandom());
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            return keyPair;
        }
    
        //获取公钥(Base64编码)
        public static String getPublicKey(KeyPair keyPair) {
            ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic();
            byte[] bytes = publicKey.getEncoded();
            return Base64.getEncoder().encodeToString(bytes);
        }
    
        //获取私钥(Base64编码)
        public static String getPrivateKey(KeyPair keyPair) {
            ECPrivateKey privateKey = (ECPrivateKey) keyPair.getPrivate();
            byte[] bytes = privateKey.getEncoded();
            return Base64.getEncoder().encodeToString(bytes);
        }
    
    
        /**
         * 公钥字符串加密
         * @param data
         * @param publicKey
         * @return
         * @throws Exception
         */
        public static byte[] encrypt(byte[] data, String publicKey)
                throws Exception {
            byte[] keyBytes = Base64Decoder.decode(publicKey);
    
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
    
            ECPublicKey pubKey = (ECPublicKey) keyFactory
                    .generatePublic(x509KeySpec);
    
            Cipher cipher = new NullCipher();
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            return cipher.doFinal(data);
        }
    
    
        /**
         * 公钥加密
         * @param content
         * @param pubKey
         * @return
         * @throws Exception
         */
        public static byte[] encrypt(byte[] content, ECPublicKey pubKey) throws Exception {
            // Cipher cipher = Cipher.getInstance("ECIES", "BC");
            Cipher cipher = new NullCipher();
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            return cipher.doFinal(content);
        }
    
    
        /**
         * 私钥解密
         * @param data
         * @param privateKey
         * @return
         * @throws Exception
         */
        public static byte[] decrypt(byte[] content, ECPrivateKey priKey) throws Exception {
            // Cipher cipher = Cipher.getInstance("ECIES", "BC");
            Cipher cipher = new NullCipher();
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            return cipher.doFinal(content);
        }
    
        /**
         * 私钥字符串解密
         * @param data
         * @param privateKey
         * @return
         * @throws Exception
         */
        public static byte[] decrypt(byte[] data, String privateKey) throws Exception {
            byte[] keyBytes = Base64Decoder.decode(privateKey);
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
            ECPrivateKey priKey = (ECPrivateKey) keyFactory
                    .generatePrivate(pkcs8KeySpec);
    
            Cipher cipher = new NullCipher();
            cipher.init(Cipher.DECRYPT_MODE, priKey);
    
            return cipher.doFinal(data);
        }
    
    
        //私钥签名
        public static byte[] sign(String content, ECPrivateKey priKey) throws Exception {
            //这里可以从证书中解析出签名算法名称
            //Signature signature = Signature.getInstance(getSigAlgName(pubCert));
            Signature signature = Signature.getInstance(SIGNATURE);
            signature.initSign(priKey);
            signature.update(content.getBytes());
            return signature.sign();
        }
    
        //公钥验签
        public static boolean verify(String content, byte[] sign, ECPublicKey pubKey) throws Exception {
            //这里可以从证书中解析出签名算法名称
            //Signature signature = Signature.getInstance(getSigAlgName(priCert));
            Signature signature = Signature.getInstance(SIGNATURE);
            signature.initVerify(pubKey);
            signature.update(content.getBytes());
            return signature.verify(sign);
        }
    
        /**
         * 解析证书的签名算法,单独一本公钥或者私钥是无法解析的,证书的内容远不止公钥或者私钥
         * */
        private static String getSigAlgName(File certFile) throws Exception {
            CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
            X509Certificate x509Certificate = (X509Certificate) cf.generateCertificate(new FileInputStream(certFile));
            return x509Certificate.getSigAlgName();
        }
    
    
        public static void main(String[] args) {
            try {
                KeyPair keyPair = getKeyPair();
                ECPublicKey pubKey = (ECPublicKey) keyPair.getPublic();
                ECPrivateKey priKey = (ECPrivateKey) keyPair.getPrivate();
                System.out.println("[pubKey]:\n" + getPublicKey(keyPair));
                System.out.println("[priKey]:\n" + getPrivateKey(keyPair));
    
                //测试文本
                String content = "abcdefg";
    
                //加密
                byte[] cipherTxt = encrypt(content.getBytes(), pubKey);
    
                //解密
                byte[] clearTxt = decrypt(cipherTxt, priKey);
                //打印
                System.out.println("content:" + content);
                System.out.println("cipherTxt["+cipherTxt.length+"]:" + new String(cipherTxt));
                System.out.println("clearTxt:" + new String(clearTxt));
    
                //签名
                byte[] sign = sign(content, priKey);
                //验签
                boolean ret = verify(content, sign, pubKey);
                //打印
                System.out.println("content:" + content);
                System.out.println("sign["+sign.length+"]:" + new String(sign));
                System.out.println("verify:" + ret);
    
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("[main]-Exception:" + e.toString());
            }
        }
    }
  • 相关阅读:
    【c++】流状态的查询和控制
    【c++】iostreeam中的类为何不可以直接定义一个无参对象呢
    异步操作超出页面超时时间
    sql转Linq的工具
    用离职换来的领悟:人生没有最佳时机
    Log4Net日志记录两种方式
    C# FileStream复制大文件
    C#常用的集合类型(ArrayList类、Stack类、Queue类、Hashtable类、SortedList类)
    C# 读取 timestamp 时间戳 值为byte[] 类型时转换为时间戳字符串
    IIS7错误:“Web服务器被配置为不列出此目录的内容”的解决办法
  • 原文地址:https://www.cnblogs.com/luyilan/p/15767613.html
Copyright © 2020-2023  润新知