您的当前位置:首页正文

AES CBC-NoPadding-128位加解密 Java和C#

2024-11-13 来源:个人技术集锦

#JAVA 加密# 

private final static String CIPHER_MODEL =  "";//16个字节

/**
     * 加密
     *
     * @param key 密钥
     * @param content 待加密内容
     * @param encryptKeyType 密钥类型,若为AES,
     * @return 返回结果为Base64处理过后的字符串
     */
    @Override
    public String encrypt(String key, String content, String encryptKeyType) throws EncryptException {
        try {
            String keyAlgorithm = attribute.keyAlgorithm;

            byte[] keys = Base64.getDecoder().decode(key);

            byte[] contentBytes = content.getBytes(Charset.forName("utf-8"));
            //转base64字符串
            return Base64.getEncoder().encodeToString(AESHelper.encrypt(contentBytes, keys, keyAlgorithm));
        } catch (Exception e) {
            throw new EncryptException(e);
        }
}

/**
     * 加密
     * @param content 明文
     * @param key 密钥
     * @param keyAlgorithm 算法名称
     * @return 密文二进制
     * @throws Exception
     */
    public static byte[] encrypt(byte[] content, byte[] key, String keyAlgorithm) throws Exception{

        Cipher cipher = Cipher.getInstance(keyAlgorithm + CIPHER_MODEL);
        int blockSize = cipher.getBlockSize();

        int plaintextLength = content.length;
        if (plaintextLength % blockSize != 0) {
            plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
        }

        byte[] plaintext = new byte[plaintextLength];
        System.arraycopy(content, 0, plaintext, 0, content.length);

        SecretKeySpec keyspec = new SecretKeySpec(key, keyAlgorithm);
        IvParameterSpec ivspec = new IvParameterSpec(key);

        cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
        byte[] encrypted = cipher.doFinal(plaintext);
        }

#JAVA 解密#


    /**
     * 解密
     *
     * @param key 密钥
     * @param content 加密内容,为密文
     * @param encryptKeyType 密钥类型,若为AES,
     * @return 返回结果为明文,Base64处理
     */
    @Override
    public String decrypt(String key, String content, String encryptKeyType) throws EncryptException{
        try {
            String keyAlgorithm = attribute.keyAlgorithm;

            byte[] keys = Base64.getDecoder().decode(key);

            //转base64字节码
            byte[] contentBytes = Base64.getDecoder().decode(content);
            byte[] result = AESHelper.decrypt(contentBytes, keys, keyAlgorithm);

            return new String(result, Charset.forName("utf-8")).trim();
        } catch (Exception e) {
            throw new EncryptException(e);
        }

}

/**
     * 解密
     * @param content 密文
     * @param key  密钥
     * @param keyAlgorithm 算法名称
     * @return 明文二进制
     * @throws Exception
     */
    public static byte[] decrypt(byte[] content, byte[] key,String keyAlgorithm) throws Exception{

        Cipher cipher = Cipher.getInstance(keyAlgorithm + CIPHER_MODEL);
        SecretKeySpec keyspec = new SecretKeySpec(key, keyAlgorithm);
        IvParameterSpec ivspec = new IvParameterSpec(key);

        cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

        byte[] original = cipher.doFinal(content);

        return original;
    }

#C#加密#

private static String HEXADECIMAL =  "";//16个字节
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="content"></param>
        /// <param name="keys"></param>
        /// <returns></returns>
        public static string AESEncrypt(string content, string keys)
        {
            var key = Convert.FromBase64String(keys);
            RijndaelManaged rijndaelCipher = new RijndaelManaged();
            rijndaelCipher.Mode = CipherMode.CBC;
            rijndaelCipher.Padding = PaddingMode.Zeros;
            rijndaelCipher.KeySize = 128;
            rijndaelCipher.BlockSize = 128;
            byte[] pwdBytes = key;// System.Text.Encoding.UTF8.GetBytes(KEY);
            byte[] keyBytes = new byte[16];
            int len = pwdBytes.Length;
            if (len > keyBytes.Length)
                len = keyBytes.Length;
            System.Array.Copy(pwdBytes, keyBytes, len);
            rijndaelCipher.Key = keyBytes;
            rijndaelCipher.IV = key;
            ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
            byte[] plainText = Encoding.UTF8.GetBytes(content);
            byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
            return Convert.ToBase64String(cipherBytes);
        }

#C#解密#

/// <summary>
        /// 解密
        /// </summary>
        /// <param name="content"></param>
        /// <param name="keys"></param>
        /// <returns></returns>
        public static string AESDecrypt(string content, string keys)
        {
            var key = Convert.FromBase64String(keys);
            RijndaelManaged rijndaelCipher = new RijndaelManaged();
            rijndaelCipher.Mode = CipherMode.CBC;
            rijndaelCipher.Padding = PaddingMode.Zeros;
            rijndaelCipher.KeySize = 128;
            rijndaelCipher.BlockSize = 128;
            byte[] encryptedData = Convert.FromBase64String(content);
            byte[] pwdBytes = key;// System.Text.Encoding.UTF8.GetBytes(key);
            byte[] keyBytes = new byte[16];
            int len = pwdBytes.Length;
            if (len > keyBytes.Length)
                len = keyBytes.Length;
            System.Array.Copy(pwdBytes, keyBytes, len);
            rijndaelCipher.Key = keyBytes;
            rijndaelCipher.IV = key;// Encoding.UTF8.GetBytes(iv);
            ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
            byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
            return Encoding.UTF8.GetString(plainText);
        }

 

显示全文