前言
go 和java 的 AES CFB加密略有不同
java 版本
加密
private static byte[] encrypt(byte[] encoded_payload, byte[] key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, ShortBufferException, IllegalBlockSizeException, BadPaddingException {
SecureRandom rand = new SecureRandom(); // or .getInstance* as you prefer
SecretKeySpec key_spec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
int block_size = cipher.getBlockSize();
byte[] buffer = new byte[block_size];
rand.nextBytes(buffer);
IvParameterSpec iv = new IvParameterSpec(buffer);
buffer = Arrays.copyOf(buffer, block_size + encoded_payload.length);
cipher.init(Cipher.ENCRYPT_MODE, key_spec, iv);
cipher.doFinal(encoded_payload, 0, encoded_payload.length, buffer, block_size);
return buffer;
}
解密
private static byte[] decrypt(byte[] payload, byte[] key) throws NoSuchPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, InvalidKeyException {
SecretKeySpec key_spec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
int block_size = cipher.getBlockSize();
IvParameterSpec iv = new IvParameterSpec(Arrays.copyOf(payload, block_size));
byte[] decryption_data = Arrays.copyOfRange(payload, block_size, payload.length);
cipher.init(Cipher.DECRYPT_MODE, key_spec, iv);
return cipher.doFinal(decryption_data);
}
go 版本
go加密
func Encrypt(payload []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
ciphertext := make([]byte, aes.BlockSize+len(payload))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
cipher.NewCFBEncrypter(block, iv).XORKeyStream(ciphertext[aes.BlockSize:],
payload)
return ciphertext, nil
}
go解密
func Decrypt(payload []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
if len(payload) < aes.BlockSize {
return nil, errors.New("ciphertext too short")
}
iv := payload[:aes.BlockSize]
payload = payload[aes.BlockSize:]
cipher.NewCFBDecrypter(block, iv).XORKeyStream(payload, payload)
return payload, nil
}
本博客所有文章除特别声明外,均采用: 署名-非商业性使用-禁止演绎 4.0 国际协议,转载请保留原文链接及作者。