A-A+
python、go 语言编写的aes加解密脚本

【注意:此文章为博主原创文章!转载需注意,请带原文链接,至少也要是txt格式!】
以下内容来源openai
python aes加解密脚本
import base64
from Crypto.Cipher import AES
from Crypto import Random
# 需要提前指定加密的密钥
key = b'1234567890123456'
# 要加密的文本
plaintext = 'Hello World!'
# 填充文本,使其长度为16的整数倍
plaintext = plaintext + (16 - len(plaintext) % 16) * ' '
# 生成随机的初始化向量
iv = Random.new().read(AES.block_size)
# 创建AES加密器
cipher = AES.new(key, AES.MODE_CFB, iv)
# 加密文本
ciphertext = iv + cipher.encrypt(plaintext.encode())
# 对加密后的文本进行base64编码
ciphertext = base64.b64encode(ciphertext)
# 解密文本
decoded = base64.b64decode(ciphertext)
iv = decoded[:16]
cipher = AES.new(key, AES.MODE_CFB, iv)
decrypted = cipher.decrypt(decoded[16:]).decode().strip()
print('原文:', plaintext)
print('密文:', ciphertext)
print('解密后:', decrypted)
go aes加解密脚本
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"fmt"
)
// 需要提前指定加密的密钥
var key = []byte("1234567890123456")
// 要加密的文本
var plaintext = "Hello World!"
// 填充文本,使其长度为16的整数倍
func padding(src []byte) []byte {
padNum := aes.BlockSize - len(src)%aes.BlockSize
pad := bytes.Repeat([]byte{byte(padNum)}, padNum)
return append(src, pad...)
}
// 去掉填充
func unpadding(src []byte) []byte {
length := len(src)
unpadNum := int(src[length-1])
return src[:(length - unpadNum)]
}
// 加密
func encrypt(key, plaintext []byte) []byte {
block, _ := aes.NewCipher(key)
plaintext = padding(plaintext)
ciphertext := make([]byte, len(plaintext))
for i := 0; i < len(plaintext); i += aes.BlockSize {
block.Encrypt(ciphertext[i:i+aes.BlockSize], plaintext[i:i+aes.BlockSize])
}
return ciphertext
}
// 解密
func decrypt(key, ciphertext []byte) []byte {
block, _ := aes.NewCipher(key)
plaintext := make([]byte, len(ciphertext))
for i := 0; i < len(ciphertext); i += aes.BlockSize {
block.Decrypt(plaintext[i:i+aes.BlockSize], ciphertext[i:i+aes.BlockSize])
}
return unpadding(plaintext)
}
func main() {
// 加密文本
ciphertext := encrypt(key, []byte(plaintext))
// 对加密后的文本进行base64编码
ciphertext = []byte(base64.StdEncoding.EncodeToString(ciphertext))
// 解密文本
decrypted := decrypt(key, ciphertext)
fmt.Println("原文:", plaintext)
fmt.Println("密文:", ciphertext)
fmt.Println("解密后:", string(decrypted))
}
布施恩德可便相知重
微信扫一扫打赏
支付宝扫一扫打赏