ZBLOG

golang AES加解密,带有iv偏移量

在Golang中进行AES加解密可以使用crypto/aes包和crypto/cipher包。以下是一个示例代码,演示了如何使用AES CBC模式进行加解密,并包含了IV偏移量。

  1. package main
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "encoding/base64"
  6. "fmt"
  7. )
  8. func encrypt(key, iv, plaintext []byte) (string, error) {
  9. block, err := aes.NewCipher(key)
  10. if err != nil {
  11. return "", err
  12. }
  13. paddedPlaintext := pkcs7Padding(plaintext, block.BlockSize())
  14. ciphertext := make([]byte, len(paddedPlaintext))
  15. mode := cipher.NewCBCEncrypter(block, iv)
  16. mode.CryptBlocks(ciphertext, paddedPlaintext)
  17. return base64.StdEncoding.EncodeToString(ciphertext), nil
  18. }
  19. func decrypt(key, iv []byte, ciphertext string) ([]byte, error) {
  20. block, err := aes.NewCipher(key)
  21. if err != nil {
  22. return nil, err
  23. }
  24. decodedCiphertext, err := base64.StdEncoding.DecodeString(ciphertext)
  25. if err != nil {
  26. return nil, err
  27. }
  28. decryptedData := make([]byte, len(decodedCiphertext))
  29. mode := cipher.NewCBCDecrypter(block, iv)
  30. mode.CryptBlocks(decryptedData, decodedCiphertext)
  31. return pkcs7Unpadding(decryptedData), nil
  32. }
  33. // 使用PKCS7填充方式对数据进行填充
  34. func pkcs7Padding(data []byte, blockSize int) []byte {
  35. padding := blockSize - (len(data) % blockSize)
  36. padText := bytes.Repeat([]byte{byte(padding)}, padding)
  37. return append(data, padText...)
  38. }
  39. // 对使用PKCS7填充方式的数据进行去填充
  40. func pkcs7Unpadding(data []byte) []byte {
  41. length := len(data)
  42. unpadding := int(data[length-1])
  43. return data[:(length - unpadding)]
  44. }
  45. func main() {
  46. key := []byte("0123456789ABCDEF") // 16字节密钥
  47. iv := []byte("1234567890ABCDEF") // 16字节IV偏移量
  48. plaintext := []byte("Hello, World!")
  49. ciphertext, err := encrypt(key, iv, plaintext)
  50. if err != nil {
  51. fmt.Println("Encryption error:", err)
  52. return
  53. }
  54. fmt.Println("Ciphertext:", ciphertext)
  55. decryptedText, err := decrypt(key, iv, ciphertext)
  56. if err != nil {
  57. fmt.Println("Decryption error:", err)
  58. return
  59. }
  60. fmt.Println("Decrypted Text:", string(decryptedText))
  61. }

请注意,这里的示例使用了AES-128算法,使用了16字节的密钥和IV偏移量。你可以根据需要调整参数和填充方式。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=8052

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?