AES Encryption


JAVA

/** * Encrypts the string according to the specified key * * @param content The string that needs to be encrypted * @return Returns the hexadecimal string after encryption * */ public static String encrypt(String content, String key) { try { Cipher cipher = Cipher.getInstance("AES"); byte[] byteContent = content.getBytes(CHARSTER_ENCODING); cipher.init(Cipher.ENCRYPT_MODE, genKey(key)); byte[] result = cipher.doFinal(byteContent); return HexUtils.toHexStr(result); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return null; } /** * Decrypts the string according to the specified key * * @param content String to be decrypted * @return Returns the decrypted string * */ public static String decrypt(String content, String key) { try { byte[] decryptFrom = HexUtils.toByte(content); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, genKey(key)); byte[] result = cipher.doFinal(decryptFrom); return new String(result); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return null; } /** * Get a key of AES type according to the sourceKey * * @param sourceKey * @return SecretKeySpec Returns the generated key * */ private static SecretKeySpec genKey(String sourceKey) { byte[] enCodeFormat = {0}; try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); secureRandom.setSeed(sourceKey.getBytes()); kgen.init(128, secureRandom); SecretKey secretKey = kgen.generateKey(); enCodeFormat = secretKey.getEncoded(); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return new SecretKeySpec(enCodeFormat, "AES"); } /** * encryption * * @return */ public static byte[] encrypt(byte[] data, byte[] key) { if(key.length!=16){ throw new RuntimeException("Invalid AES key length (must be 16 bytes)"); } try { SecretKeySpec secretKey = new SecretKeySpec(key, "AES"); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec seckey = new SecretKeySpec(enCodeFormat,"AES"); Cipher cipher = Cipher.getInstance(CipherConfigure.AES_ALGORITHM);// 创建密码器 cipher.init(Cipher.ENCRYPT_MODE, seckey);// 初始化 byte[] result = cipher.doFinal(data); return result; // 加密 } catch (Exception e){ throw new RuntimeException("encrypt fail!", e); } }

PHP

/** * AES encryption method * @param string $str * @return string */ $screct_key = $rands; $str = trim($str); $str = $this->addPKCS7Padding($str); $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_ECB),MCRYPT_RAND); $encrypt_str = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $screct_key, $str, MCRYPT_MODE_ECB, $iv); $date = base64_encode($encrypt_str); /** * padding algorithm * @param string $source * @return string */ function addPKCS7Padding($source){ $source = trim($source); $block = mcrypt_get_block_size('rijndael-128', 'ecb'); $pad = $block - (strlen($source) % $block); if ($pad <= $block) { $char = chr($pad); $source .= str_repeat($char, $pad); } return $source; }

C#

public static string Encrypt(string plainText, string aesKey) { byte[] keyArray = UTF8Encoding.UTF8.GetBytes(aesKey); byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(plainText); RijndaelManaged rDel = new RijndaelManaged(); rDel.Key = keyArray; rDel.Mode = CipherMode.ECB; rDel.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = rDel.CreateEncryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Convert.ToBase64String(resultArray, 0, resultArray.Length); }

GOLang

func AesECBEncrypt(data string, key string) (string, error) { newKey := []byte(key) dataByte := []byte(data) block, err := aes.NewCipher(newKey) if err != nil { return "", err } ecb := NewECBEncryptEr(block) content := PKCS7Padding(dataByte, block.BlockSize()) encryptData := make([]byte, len(content)) ecb.CryptBlocks(encryptData, content) base64Str := base64.StdEncoding.EncodeToString(encryptData) return base64Str, nil } type ecb struct { b cipher.Block blockSize int } func newECB(b cipher.Block) *ecb { return &ecb{ b: b, blockSize: b.BlockSize(), } } type ecbEncryptEr ecb func NewECBEncryptEr(b cipher.Block) cipher.BlockMode { return (*ecbEncryptEr)(newECB(b)) } func (x *ecbEncryptEr) BlockSize() int { return x.blockSize } func (x *ecbEncryptEr) CryptBlocks(dst, src []byte) { if len(src)%x.blockSize != 0 { panic("crypto/cipher: input not full blocks") } if len(dst) < len(src) { panic("crypto/cipher: output smaller than input") } for len(src) > 0 { x.b.Encrypt(dst, src[:x.blockSize]) src = src[x.blockSize:] dst = dst[x.blockSize:] } }

Python

def aes_cipher(key, aes_str): aes = AES.new(key.encode('utf-8'), AES.MODE_ECB) pad_pkcs7 = pad(aes_str.encode('utf-8'), AES.block_size, style='pkcs7') encrypt_aes = aes.encrypt(pad_pkcs7) encrypted_text = str(base64.encodebytes(encrypt_aes), encoding='utf-8') encrypted_text_str = encrypted_text.replace("\n", "") return encrypted_text_str