请教如下的示例代码,没有 IV (初始化向量)
来源: https://www.developer.com/languages/cryptography-in-go/
上面文章提到的案例是:
~~~
package main
import (
"crypto/aes"
"encoding/hex"
"fmt"
)
func encryptMessage(key string, message string) string {
c, err := aes.NewCipher([]byte(key))
if err != nil {
fmt.Println(err)
}
msgByte := make([]byte, len(message))
c.Encrypt(msgByte, []byte(message))
return hex.EncodeToString(msgByte)
}
func decryptMessage(key string, message string) string {
txt, _ := hex.DecodeString(message)
c, err := aes.NewCipher([]byte(key))
if err != nil {
fmt.Println(err)
}
msgByte := make([]byte, len(txt))
c.Decrypt(msgByte, []byte(txt))
msg := string(msgByte[:])
return msg
}
func main() {
plainText := "This is a secret"
key := "this_must_be_of_32_byte_length!!"
emsg := encryptMessage(key, plainText)
dmesg := decryptMessage(key, emsg)
fmt.Println("Encrypted Message: ", emsg)
fmt.Println("Decrypted Message: ", dmesg)
}
~~~
请教下:aes 的默认的加密模式是什么? [比如 cbc 之类的加密模式是哪一种?] 没有 openSSL 里的那种初始化变量 IV ,是有个默认值?还是说 go 标准库里默认的初始化 iv=key ?
请教 go 标准库 aes 的默认的加密模式是什么?没有 openSSL 里的那种初始化变量 IV,是有个默认值?还是说 go 标准库里默认的初始化 iv=key ?
xiaoyanbot · · 1283 次点击目测代码有问题
我的代码是这样的
``` go
//AESEncrypt aes encrypt with given data,key and iv.
//Data will be padding with PKCS7Padding
//Return encrytped data and any error if raised.
func AESEncrypt(unencrypted []byte, key []byte, iv []byte) (encrypted []byte, err error) {
defer func() {
r := recover()
if r != nil {
err = r.(error)
}
}()
cryptKey := formatKey(key, aes.BlockSize)
block, err := aes.NewCipher(cryptKey)
if err != nil {
return
}
data := PKCS7Padding(unencrypted, aes.BlockSize)
crypter := cipher.NewCBCEncrypter(block, iv)
encrypted = make([]byte, len(data))
crypter.CryptBlocks(encrypted, data)
return
}
// AESNonceEncrypt aes encrypt data with given key and random bytes as IV.
//Data will be padding with PKCS7Padding
//Random IV will prefix encryped data
//return encrypted data and any error if raisd.
func AESNonceEncrypt(unencrypted []byte, key []byte) (encrypted []byte, err error) {
defer func() {
r := recover()
if r != nil {
err = r.(error)
}
}()
var rawEncrypted []byte
var IV = make([]byte, IVSize)
_, err = rand.Read(IV)
if err != nil {
return
}
rawEncrypted, err = AESEncrypt(unencrypted, key, IV)
if err != nil {
return
}
encrypted = make([]byte, len(rawEncrypted)+int(IVSize))
copy(encrypted[:IVSize], IV)
copy(encrypted[IVSize:], rawEncrypted)
return
}
```
#1
更多评论
你给的代码是 ECB 模式的,ECB模式是没有IV的。
具体的可以看这个 https://github.com/deatil/go-cryptobin/blob/main/cryptobin/encryption_cipher.go#L45
#2