对称加密,非对称加密,数字签名工具类

内容

  • 对称AES加密Demo
  • 对称AES解密Demo
  • 非对称RSA加密与解密Demo
  • 整理成工具类

1.对称加密AES简单Demo

//key字节数必须为16
String key = "Q!W#R%G&Q!W#R%G&";
String content = "哈喽";
//算法类型
String algorithm = "AES";
//加密类型
String transformation = "AES";
//获取一个算法对象
Cipher cipher = Cipher.getInstance(transformation);
//指定秘钥规则
//密钥,key的字节数组 长度必须是16位
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), algorithm);
//将加密规则初始化
cipher.init(CipherMode.encrypt.getValue(), secretKeySpec);
byte[] bytes = cipher.doFinal(content.getBytes());
//使用hutool工具类进行编码
System.out.println(Base64.encode(bytes ));

2.对称AES解密Demo

//先运行上面的加密代码
//算法类型
String algorithm = "AES";
//加密类型
String transformation = "AES";
//获取一个算法对象
Cipher cipher = Cipher.getInstance(transformation);
//指定秘钥规则
//密钥,key的字节数组 长度必须是16位
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), algorithm);
//将加密规则初始化
cipher.init(CipherMode.decrypt.getValue(), secretKeySpec);
//bytes加密后的数组
String content =  new String(cipher.doFinal(bytes));
System.out.println(content);

3.非对称RSA加密与解密Demo

       //指定算法
        String algorithm = "RSA";
        //加密内容
        String content ="content";
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
        //获取密钥对
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        //公钥
        PublicKey publicKey = keyPair.getPublic();
        //私钥
        PrivateKey privateKey = keyPair.getPrivate();
        //加密
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE,publicKey);
        byte[] bytes = cipher.doFinal(content.getBytes());
        System.out.println(Base64.encode(bytes));
        //解密
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] bytes1 = cipher.doFinal(bytes);
        System.out.println(new String(bytes1));

4.整理成工具类

public class CipherSecurityUtil {

    /**
     *密钥大小
     */
    public static final int RSA_KEY_PAIR_LENGTH = 2048;
    /**
     * 算法类型
     */
    public static final String AES_KEY_ALGORITHM = "AES";
    /**
     * 加密类型
     */
    public static final String RSA_CIPHER_TYPE = "RSA";
    /**
     * 默认的加密算法:加密算法/模式/填充方案
     */
    public static final String AES_DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
    /**
     * 数字签名
     */
    public static final String SHA256_KEY_ALGORITHM = "SHA256withRSA";


    /**
     * 获取 Cipher
     * @param cipherMode 加密枚举
     * @return Cipher
     */
    public static Cipher getAESCipher(CipherMode cipherMode, String pwdKey) throws Exception {
        byte[] key = pwdKey.getBytes();
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, AES_KEY_ALGORITHM);
        Cipher cipher = Cipher.getInstance(AES_DEFAULT_CIPHER_ALGORITHM);
        cipher.init(cipherMode.getValue(),secretKeySpec);
        return cipher;
    }

    /**
     * 生成随机密钥
     * 获取随机16字符
     * @return 返回随机密钥
     */
    public static String generateAESSecret() {
        String result = UUID.randomUUID().toString().replaceAll("-", "");
        result = result.substring(0,16);
        return result;
    }

    /**
     * 加密
     * @param content 加密内容
     * @param pwdKey 秘钥
     * @return
     */
    public static byte[] encryptAES(String content,String pwdKey) throws Exception {
        Cipher cipher = getAESCipher(CipherMode.encrypt, pwdKey);
        return cipher.doFinal(content.getBytes());
    }

    /**
     * 解密
     * @param content 要解密的内容
     * @param pwdKey 秘钥
     * @return
     */
    public static byte[] decryptAES(byte[] content,String pwdKey) throws Exception {
        Cipher cipher = getAESCipher(CipherMode.decrypt, pwdKey);
        return cipher.doFinal(content);
    }

    /**
     * 加密数据
     * @param content 加密内容
     * @param pwdKey 加密key
     * @return
     */
    public static String encodeAESBase64(String content,String pwdKey) throws Exception {
        return Base64.encode(encryptAES(content,pwdKey));
    }

    /**
     * 解密
     * @param content 解密内容
     * @param pwdKey 解密key
     * @return
     * @throws Exception
     */
    public static String decodeAESBase64(String content,String pwdKey) throws Exception {
        return new String(decryptAES(Base64.decode(content),pwdKey));
    }

    /**
     *
     * @param cipherMode 加密或者解密参数
     * @param key 私钥或者公钥
     * @return Cipher
     * @throws Exception
     */
    public static Cipher getRSACipher(CipherMode cipherMode, Key key) throws Exception {
        Cipher cipher = Cipher.getInstance(RSA_CIPHER_TYPE);
        cipher.init(cipherMode.getValue(),key);
        return cipher;
    }

    /**
     * 获取秘钥对
     * @return KeyPair
     */
    public static KeyPair getKeyPair() throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA_CIPHER_TYPE);
        keyPairGenerator.initialize(RSA_KEY_PAIR_LENGTH);
        return keyPairGenerator.generateKeyPair();
    }

    /**
     * 获取公钥
     * @return
     * @throws Exception
     */
    public static PublicKey getPublicKey(KeyPair keyPair) throws Exception {
        byte[] encoded = keyPair.getPublic().getEncoded();
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_CIPHER_TYPE);
        //创建私钥规则
        X509EncodedKeySpec encodedKeySpec = new X509EncodedKeySpec(encoded);
        return keyFactory.generatePublic(encodedKeySpec);
    }

    /**
     * 获取私钥
     * @return
     * @throws Exception
     */
    public static PrivateKey getPrivateKey(KeyPair keyPair) throws Exception {
        byte[] encoded = keyPair.getPrivate().getEncoded();
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_CIPHER_TYPE);
        //创建私钥规则
        PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(encoded);
        return keyFactory.generatePrivate(encodedKeySpec);
    }

    /**
     * 公钥加密
     * @param content 要加密内容
     * @param publicKey 公钥
     * @return
     */
    public static byte[] cipherRSAByPublicKeyEncrypt(String content, PublicKey publicKey) throws Exception {
        Cipher rsaCipher = getRSACipher(CipherMode.encrypt, publicKey);
        return rsaCipher.doFinal(content.getBytes());
    }

    /**
     * 私钥解密
     * @param content 要解密内容
     * @param privateKey 私钥
     * @return
     */
    public static byte[] cipherRSAByPrivateKeyDecrypt(byte[] content, PrivateKey privateKey) throws Exception {
        Cipher rsaCipher = getRSACipher(CipherMode.decrypt, privateKey);
        return rsaCipher.doFinal(content);
    }

    /**
     * 先加密在 Base64编码
     * @param content 加密内容
     * @param publicKey 公钥
     * @return String
     * @throws Exception
     */
    public static String encodeREABase64(String content,PublicKey publicKey) throws Exception {
        return Base64.encode(cipherRSAByPublicKeyEncrypt(content,publicKey));
    }

    /**
     * 先Base64解码 在解密
     * @param content 要解密内容
     * @param privateKey 私钥
     * @return String
     * @throws Exception
     */
    public static String decodeRSABase64(String content,PrivateKey privateKey) throws Exception {
        return new String(cipherRSAByPrivateKeyDecrypt(Base64.decode(content),privateKey));
    }


    /**
     * 通过私钥获取签名
     * @param content 内容
     * @param algorithm 算法
     * @param privateKey 私钥
     * @return
     */
    public static String getSignature(String content, String algorithm, PrivateKey privateKey) throws Exception {
        algorithm = ObjectUtil.isNotNull(algorithm)?algorithm:"SHA256withRSA";
        Signature instance = Signature.getInstance(algorithm);
        instance.initSign(privateKey);
        instance.update(content.getBytes());
        return Base64.encode(instance.sign());
    }

    /**
     * 校验签名
     * @param content 内容
     * @param algorithm 算法
     * @param publicKey 公钥
     * @param encryptContent 生成的签名
     * @return
     */
    public static Boolean verifySignature(String content, String algorithm,PublicKey publicKey,String encryptContent) throws Exception{
        algorithm = ObjectUtil.isNotNull(algorithm)?algorithm:"SHA256withRSA";
        Signature instance = Signature.getInstance(algorithm);
        instance.initVerify(publicKey);
        instance.update(content.getBytes());
        return instance.verify(Base64.decode(encryptContent));
    }
	
	//测试
    public static void main(String[] args) throws Exception {
          //AES加密
//        String pwdkey = generateAESSecret();
//        System.out.println(pwdkey);
//        String content = encodeAESBase64("哈喽", pwdkey);
//        System.out.println(content);
//        content = decodeAESBase64(content, pwdkey);
//        System.out.println(content);

        //RSA加密
        KeyPair keyPair = getKeyPair();
        PublicKey publicKey = getPublicKey(keyPair);
        PrivateKey privateKey = getPrivateKey(keyPair);
//        String encodeREABase64 = encodeREABase64("哈喽", publicKey);
//        String content = decodeRSABase64(encodeREABase64, privateKey);
//        System.out.println(content);

        //数字签名
        String content = "哈喽";
        String signature = getSignature(content, null, privateKey);
        Boolean aBoolean = verifySignature(content, null, publicKey, signature);
        System.out.println(aBoolean);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值