AES加密


JAVA

/** * 对字符串进行加密,根据指定的密码 * * @param content 需要加密的字符串 * @return 返回加密完成之后的十六进制字符串 * */ 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; } /** * 对字符串进行解密,根据指定的密码 * * @param content 需要加密的字符串 * @return 返回解密之后的字符串 * */ 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; } /** * 根据密码获得一个AES类型的key * * @param sourceKey 密码 * @return SecretKeySpec 返回生成的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"); } /** * 加密 * * @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加密方法 * @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); /** * 填充算法 * @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

// AES/ECB/PKCS7模式加密--签名加密方式 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) // 加PKCS7填充 content := PKCS7Padding(dataByte, block.BlockSize()) encryptData := make([]byte, len(content)) // 生成加密数据 ecb.CryptBlocks(encryptData, content) base64Str := base64.StdEncoding.EncodeToString(encryptData) return base64Str, nil } // ecb加密方法 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