golang基础学习-AES加密
2012 年 5 月 5 日
高级加密标准(AES全称Advanced Encryption Standard),AES加密数据块分组长度必须为128bit(byte[16]),密钥长度可以是128bit、192bit、256bit中的任意一个。
ps:本文中PKCS7填充函数是从别的地方找的,具体地方不记得了。后续找到链接会补上参考地址。
ps:本文中PKCS7填充函数是从别的地方找的,具体地方不记得了。后续找到链接会补上参考地址。
AES实现的方式:
- 1.电码本模式(Electronic Codebook Book (ECB))
- 2.密码分组链接模式(Cipher Block Chaining (CBC))
- 3.计算器模式(Counter (CTR))
- 4.密码反馈模式(Cipher FeedBack (CFB))
- 5.输出反馈模式(Output FeedBack (OFB))
1.AES加解密原理
P:明文 K:密钥 C:密文
1.1 加密
把明文P和密钥K传给加密函数,生成密文C
C = Encrypter(P,K)
1.2 解密
把密文C和密钥K传给解密函数,生成明文P
P =Decrypter(C,K)
若第三方拿到密钥K,他就可以破解你的密码;实际
2.Golang-AES
采用密码分组链接模式(Cipher Block Chaining (CBC))进行加解密。因为明文的长度不一定总是128的整数倍,所以要进行补位,这里采用的是PKCS7填充方式.
CBC模式的运行原理: 将明文分组与前一个密文分组进行XOR运算,然后再进行加密。每个分组的加解密都依赖于前一个分组。而第一个分组没有前一个分组,因此需要一个初始化向量
2.1 Golang使用AES(CBC)
需要引入 “crypto/aes” ,”crypto/cipher”
这两个package;
2.2 Golang使用AES(CBC)代码
方法一:
package main import ( "bytes" "crypto/aes" "crypto/cipher" "encoding/base64" "encoding/hex" "fmt" ) // func PKCS7Padding(ciphertext []byte, blockSize int) []byte { padding := blockSize - len(ciphertext)%blockSize padtext := bytes.Repeat([]byte{byte(padding)}, padding) return append(ciphertext, padtext...) } func PKCS7UnPadding(origData []byte) []byte { length := len(origData) unpadding := int(origData[length-1]) return origData[:(length - unpadding)] } //AesEncrypt 加密函数 func AesEncrypt(plaintext []byte, key, iv []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } blockSize := block.BlockSize() plaintext = PKCS7Padding(plaintext, blockSize) blockMode := cipher.NewCBCEncrypter(block, iv) crypted := make([]byte, len(plaintext)) blockMode.CryptBlocks(crypted, plaintext) return crypted, nil } // AesDecrypt 解密函数 func AesDecrypt(ciphertext []byte, key, iv []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } blockSize := block.BlockSize() blockMode := cipher.NewCBCDecrypter(block, iv[:blockSize]) origData := make([]byte, len(ciphertext)) blockMode.CryptBlocks(origData, ciphertext) origData = PKCS7UnPadding(origData) return origData, nil } func main() { key, _ := hex.DecodeString("6368616e676520746869732070617373") plaintext := []byte("hello ming") c := make([]byte, aes.BlockSize+len(plaintext)) iv := c[:aes.BlockSize] //加密 ciphertext, err := AesEncrypt(plaintext, key, iv) if err != nil { panic(err) } //打印加密base64后密码 fmt.Println(base64.StdEncoding.EncodeToString(ciphertext)) //解密 plaintext, err = AesDecrypt(ciphertext, key, iv) if err != nil { panic(err) } //打印解密明文 fmt.Println(string(plaintext)) }