拥有以下代码
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"io"
"log"
)
func main() {
decrypt(
"Zff9c+F3gZu/lsARvPhpMau50KUkMAie4j8MYfb12HMWhkLqZreTk8RPbtRB7RDG3QFw7Y0FXJsCq/EBEAz//XoeSZmqZXoyq2Cx8ZV+/Rw=",
"u9CV7oR2w+IIk8R0hppxaw==",
"~NB8CcOL#J!H?|Yr",
)
text, iv := encrypt(
`{"data":{"value":300}, "SEQN":700 , "msg":"IT WORKS!! }"`,
"~NB8CcOL#J!H?|Yr",
)
println("Encrypted", text, iv)
decrypt(
text,
iv,
"~NB8CcOL#J!H?|Yr",
)
}
func encrypt(textString, keyString string) (string, string) {
key := []byte(keyString)
text := []byte(textString)
encodedText := []byte(base64.StdEncoding.EncodeToString(text))
block, err := aes.NewCipher(key)
check(err, "location 5 ")
textWithPadding := addPadding(encodedText, aes.BlockSize)
iv := make([]byte, 16)
_, err = io.ReadFull(rand.Reader, iv)
check(err, "location 6 ")
mode := cipher.NewCBCEncrypter(block, iv)
encrypted := make([]byte, len(textWithPadding))
mode.CryptBlocks(encrypted, textWithPadding)
encodedResult := base64.StdEncoding.EncodeToString(encrypted)
encodedIv := base64.StdEncoding.EncodeToString(iv)
return encodedResult, encodedIv
}
func check(err error, where string) {
if err != nil {
log.Panic(where, err)
}
}
func decrypt(ciphertext, iv, password string) {
decodedText, err := base64.StdEncoding.DecodeString(ciphertext)
check(err, "location 1 ")
decodedIv, err := base64.StdEncoding.DecodeString(iv)
decodedIv = removeBadPadding(decodedIv)
check(err, "location 2 ")
newCipher, err := aes.NewCipher([]byte(password))
check(err, "location 3 ")
cfbdec := cipher.NewCBCDecrypter(newCipher, decodedIv)
cfbdec.CryptBlocks(decodedText, decodedText)
decodedText = removeBadPadding(decodedText)
data, err := base64.RawStdEncoding.DecodeString(string(decodedText))
check(err, "location 4 ")
println("Decrypted", string(data))
}
func removeBadPadding(b64 []byte) []byte {
last := b64[len(b64)-1]
if last > 16 {
return b64
}
return b64[:len(b64)-int(last)]
}
func addPadding(src []byte, blockSize int) []byte {
if len(src)%blockSize == 0 {
return src
}
padding := blockSize - len(src)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(src, padtext...)
}
引发
2017/03/30 12:20:09 location 4 illegal base64 data at input byte 75
panic: location 4 illegal base64 data at input byte 75
goroutine 1 [running]:
log.Panic(0xc420045df0, 0x2, 0x2)
但是,如果我改变
text, iv := encrypt(
`{"data":{"value":300}, "SEQN":700 , "msg":"IT WORKS!! }"`,
"~NB8CcOL#J!H?|Yr",
)
要
text, iv := encrypt(
`{"data":{"value":300}, "SEQN":700 , "msg":"IT WORKS!!"`,
"~NB8CcOL#J!H?|Yr",
)
代码有效。区别在于}
- 空格和}
。解密的相关问题是this one。我认为当前案例中的问题是加密