golang版aes-cbc-pkcs7加密解密base64&hex字符串输入输出

文章介绍了在Golang项目中使用AES-CBC-PKCS7算法进行加密和解密,提供了Base64和Hex编码版本的示例代码,包括加密、解密函数以及填充和去除填充的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近项目中golang项目中使用aes加解密,做个记录方便以后使用

aes-cbc-pkcs7加密解密base64输入输出

type AesBase64 struct {
	key []byte // 允许16,24,32字节长度
	iv  []byte // 只允许16字节长度
}

func NewAesBase64(key []byte, iv []byte) *AesBase64 {
	return &AesBase64{
		iv:  iv,
		key: key,
	}
}

func (s *AesBase64) Encrypt(text []byte) (string, error) {
	if len(text) == 0 {
		return "", nil
	}
	//生成cipher.Block 数据块
	block, err := aes.NewCipher(s.key)
	if err != nil {
		return "", err
	}
	//填充内容,如果不足16位字符
	blockSize := block.BlockSize()
	originData := s.pad(text, blockSize)
	//加密方式
	blockMode := cipher.NewCBCEncrypter(block, s.iv)
	//加密,输出到[]byte数组
	crypted := make([]byte, len(originData))
	blockMode.CryptBlocks(crypted, originData)
	return base64.StdEncoding.EncodeToString(crypted), nil
}

func (s *AesBase64) Decrypt(text string) ([]byte, error) {
	if len(text) == 0 {
		return []byte(text), nil
	}
	decodeData, err := base64.StdEncoding.DecodeString(text)
	if err != nil {
		return []byte(text), err
	}
	if len(decodeData) == 0 {
		return []byte(text), nil
	}
	//生成密码数据块cipher.Block
	block, _ := aes.NewCipher(s.key)
	//解密模式
	blockMode := cipher.NewCBCDecrypter(block, s.iv)
	//输出到[]byte数组
	originData := make([]byte, len(decodeData))
	blockMode.CryptBlocks(originData, decodeData)
	//去除填充,并返回
	return s.unPad(originData), nil
}

func (s *AesBase64) pad(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padText := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padText...)
}

func (s *AesBase64) unPad(ciphertext []byte) []byte {
	length := len(ciphertext)
	// 去掉最后一次的padding
	unPadding := int(ciphertext[length-1])
	return ciphertext[:(length - unPadding)]
}

aes-cbc-pkcs7加密解密hex字符串输入输出

type AesHex struct {
	key []byte // 允许16,24,32字节长度
	iv  []byte // 只允许16字节长度
}

func NewAesHex(key []byte, iv []byte) *AesHex {
	return &AesHex{
		iv:  iv,
		key: key,
	}
}

func (s *AesHex) Encrypt(text []byte) (string, error) {
	if len(text) == 0 {
		return "", nil
	}
	//生成cipher.Block 数据块
	block, err := aes.NewCipher(s.key)
	if err != nil {
		return "", err
	}
	//填充内容,如果不足16位字符
	blockSize := block.BlockSize()
	originData := s.pad(text, blockSize)
	//加密方式
	blockMode := cipher.NewCBCEncrypter(block, s.iv)
	//加密,输出到[]byte数组
	crypted := make([]byte, len(originData))
	blockMode.CryptBlocks(crypted, originData)
	return hex.EncodeToString(crypted), nil
}

func (s *AesHex) Decrypt(text string) ([]byte, error) {
	if len(text) == 0 {
		return []byte(text), nil
	}
	decodeData, err := hex.DecodeString(text)
	if err != nil {
		return []byte(text), err
	}
	if len(decodeData) == 0 {
		return []byte(text), nil
	}
	//生成密码数据块cipher.Block
	block, _ := aes.NewCipher(s.key)
	//解密模式
	blockMode := cipher.NewCBCDecrypter(block, s.iv)
	//输出到[]byte数组
	originData := make([]byte, len(decodeData))
	blockMode.CryptBlocks(originData, decodeData)
	//去除填充,并返回
	return s.unPad(originData), nil
}

func (s *AesHex) pad(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padText := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padText...)
}

func (s *AesHex) unPad(ciphertext []byte) []byte {
	length := len(ciphertext)
	// 去掉最后一次的padding
	unPadding := int(ciphertext[length-1])
	return ciphertext[:(length - unPadding)]
}

原文仓库地址:https://github.com/yanue/aes-cbc-pkcs7

在Java中,首先你需要通过`java.util.Base64`库对字符串进行解码,然后再使用`BouncyCastle`或`JSSE`库(因为Java内置库不支持OpenSSL)进行AES-256-CBC模式的解密。以下是一个简单的步骤说明: 1. **Base64解码**: ```java import java.nio.charset.StandardCharsets; import java.util.Base64; String encodedString = "your_base64_encoded_string"; byte[] decodedBytes = Base64.getDecoder().decode(encodedString); ``` 2. **导入必要的加密库** (这里我们使用BouncyCastle): ```java import org.bouncycastle.jce.provider.BouncyCastleProvider; Security.addProvider(new BouncyCastleProvider()); ``` 3. **创建密钥和初始化向量(IV)**。假设你已经有了一个十六进制的密钥和IV: ```java String keyHex = "your_secret_key_in_hex_format"; String ivHex = "your_initialization_vector_in_hex_format"; byte[] key = decodeHex(keyHex.toCharArray()); // 转换为字节数组 byte[] iv = decodeHex(ivHex.toCharArray()); ``` 4. **创建Cipher对象并设置模式和填充模式**,这里是AES-256-CBC: ```java Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC"); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv)); ``` 5. **解密数据**: ```java byte[] decryptedBytes = cipher.doFinal(decodedBytes); ``` 注意:这个例子假设你已经有一个正确的Base64编码的字符串,并且你知道相应的密钥和IV。在实际应用中,密钥管理和安全传输通常更为复杂。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值