密码学-CFB
程序员文章站
2022-06-05 08:58:05
...
CFB算法
密码算法可以分为分组密码和流密码两种,之前所学的DES,3DES和AES都是分组密码。CFB和OFB都是流密码,而CFB和OFB使用方法也基本相同,所以只以CFB进行讲解:
package main
//通过CFB模式进行AES加密
import (
"crypto/aes"
"io"
"crypto/rand"
"crypto/cipher"
"fmt"
)
//加密
func AESEncrypt(plaintext, key []byte) []byte {
//分组秘钥
block, _ := aes.NewCipher(key)
//创建数组,存放加密后的密文
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
//设置内存空间可读
iv := ciphertext[:aes.BlockSize]
io.ReadFull(rand.Reader, iv)
//设置加密方式
stream := cipher.NewCFBEncrypter(block, iv)
//加密(利用ciphertext[aes.BlockSize:]与plaintext做异或)
stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
return ciphertext
}
//解密
func AesDecrypt(ciphertext, key []byte) []byte {
block, _ := aes.NewCipher(key)
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
//设置解密方式
stream := cipher.NewCFBDecrypter(block, iv)
//解密
stream.XORKeyStream(ciphertext, ciphertext)
return ciphertext
}
func main() {
encryptcode := AESEncrypt([]byte("sanyang"), []byte("123456789abcdefg"))
fmt.Printf("%x\n", encryptcode)
decryptcode := AesDecrypt(encryptcode, []byte("123456789abcdefg"))
fmt.Println(string(decryptcode))
//fmt.Println(base64.StdEncoding.EncodeToString(decryptcode))
}