使用AES进行加解密

今天来使用aes对sk(一个字段)进行加解密,要求秘钥一半在配置文件,一般写死

aes就是一个加解密的工具,有加密和解密二个方法,是可逆的

首先给大家来一个工具类,其中的密钥字段不得超过 private static final Integer IV_SIZE = 16;

​
package com.huawei.koophone.openpower.common.utils.algo;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.*;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;

@Slf4j
public class AESUtil
{
   private AESUtil ()
   {
   }

   private static final String AES = "AES";
   private static final String ALGORITHM = "AES/GCM/NoPadding";
   private static final Integer IV_SIZE = 16;

   /**
    * AES/GCM/NoPadding 加密
    *
    * @param data    待加密的数据
    * @param workKey 工作密钥
    * @return 加密后的字符串
    */
   public static String encrypt (String data, String workKey)
   {
      try
      {
         SecureRandom sr = SecureRandom.getInstance ("SHA1PRNG");
         byte[] iv = new byte[IV_SIZE];
         sr.nextBytes (iv);

         Cipher cipher = Cipher.getInstance (ALGORITHM);
         SecretKey secretKey = new SecretKeySpec (workKey.getBytes (), AES);
         //128 bit auth tag length
         AlgorithmParameterSpec parameterSpec = new GCMParameterSpec (128, iv);
         cipher.init (Cipher.ENCRYPT_MODE, secretKey, parameterSpec);

         byte[] cipherText = cipher.doFinal (data.getBytes (StandardCharsets.UTF_8));
         ByteBuffer byteBuffer = ByteBuffer.allocate (iv.length + cipherText.length);
         byteBuffer.put (iv);
         byteBuffer.put (cipherText);
         return Hex.encodeHexString (byteBuffer.array ());
      }
      catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException |
            InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e)
      {
         log.error ("AES failed to encrypt: ", e);
      }
      return null;
   }

   /**
    * AES/GCM/NoPadding解密
    *
    * @param encrypted 加密后的密码敏文
    * @param workKey   工作秘钥
    * @return 解密后的字节数组
    */
   public static String decryptEnd (String encrypted, String workKey)
   {
      //截取iv向量
      String ivStr = encrypted.substring (0, 32);
      //截取真正的密文
      String encodeSource = encrypted.substring (32);
      byte[] result;
      try
      {
         result = decrypt (encodeSource, Hex.decodeHex (ivStr), workKey, ALGORITHM);
         if (result == null)
         {
            return null;
         }
      }
      catch (DecoderException e)
      {
         log.error ("AES failed to decryptEnd: ", e);
         return null;
      }
      return new String (result, StandardCharsets.UTF_8);
   }

   /**
    * @param source    密文
    * @param iv        vi12进制数组
    * @param workKey   工作秘钥
    * @param algorithm 算法 如:AES/GCM/NoPadding
    * @return 解密后的字节数组
    */
   public static byte[] decrypt (String source, byte[] iv, String workKey, String algorithm)
   {
      try
      {
         SecretKeySpec skey = new SecretKeySpec (workKey.getBytes (), AES);
         Cipher cipher = Cipher.getInstance (algorithm);
         GCMParameterSpec ivP = new GCMParameterSpec (128, iv);
         cipher.init (Cipher.DECRYPT_MODE, skey, ivP);
         return cipher.doFinal (Hex.decodeHex (source));
      }
      catch (BadPaddingException | IllegalBlockSizeException | NoSuchAlgorithmException | NoSuchPaddingException |
            InvalidAlgorithmParameterException | InvalidKeyException | DecoderException e)
      {
         log.error ("AES failed to decrypt: ", e);
      }
      return new byte[0];
   }
}

​

然后我们需要去创建一个密钥

这里一半在配置类里边,一半写死在我需要调用的地方

也就是说这个密钥是

+

接着我们就可以调用方法了

 

好的,我可以为您介绍一下如何在 Python使用 AES 进行加解密。 首先,需要安装 PyCryptodome 库,它是一个 Python 加密库,支持大部分加密算法,包括 AES。 安装命令如下: ``` pip install pycryptodome ``` 接下来,我们来看一个简单的 AES 加密和解密的示例代码: ```python from Crypto.Cipher import AES from Crypto.Random import get_random_bytes # 加密函数 def encrypt(plain_text, key): # 生成随机的初始向量 iv = get_random_bytes(16) # 创建 AES 加密器 cipher = AES.new(key, AES.MODE_CBC, iv) # 对明文进行补齐 padded_text = plain_text + (AES.block_size - len(plain_text) % AES.block_size) * chr(AES.block_size - len(plain_text) % AES.block_size) # 加密 cipher_text = cipher.encrypt(padded_text.encode('utf-8')) # 返回加密后的密文和初始向量 return cipher_text, iv # 解密函数 def decrypt(cipher_text, key, iv): # 创建 AES 解密器 cipher = AES.new(key, AES.MODE_CBC, iv) # 解密 plain_text = cipher.decrypt(cipher_text).decode('utf-8') # 去除明文的补齐字符 return plain_text[:-ord(plain_text[-1])] # 测试代码 key = b'Sixteen byte key' plain_text = 'Hello, AES!' cipher_text, iv = encrypt(plain_text, key) print('Cipher text:', cipher_text) print('IV:', iv) decrypted_text = decrypt(cipher_text, key, iv) print('Decrypted text:', decrypted_text) ``` 运行代码后,输出结果如下: ``` Cipher text: b'\xb7\x8f\xd5\x9d\x00\xee\xd6\x7f\x84\xfa\x8e\x87\x4c\x0f\x5e\x6f\x3c\x92\x0e\x6c\x66\x07\x4c\x0c\x2c' IV: b'\x88`!\xf2\xd6\xbf\x82j\x1f\xf2\x01\x03\x1d\x9a\xa3\xfa' Decrypted text: Hello, AES! ``` 上述代码中,我们使用了 CBC 模式进行加密,使用了随机的初始向量,通过补齐明文的方式,使其长度为 AES 块大小的倍数。在解密时,需要将明文的补齐字符去除。 您可以根据实际需要修改代码,进行自定义的加解密操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值