I'm doing AES encryption using Go, I found that the source bytes changed after encryption. Seems that XORKeyStream function does the change if cap(source) > len(source), what it exactly does to the src []byte?
go version go1.12.5 darwin/amd64
func main() {
byte1 := []byte("123abc")
fmt.Println("content1:", byte1, "len1:", len(byte1), "cap1:", cap(byte1)) // content1: [49 50 51 97 98 99] len1: 6 cap1: 6
buf := bytes.NewBuffer([]byte("123abc"))
byte2, _ := ioutil.ReadAll(buf)
fmt.Println("content2:", byte2, "len2:", len(byte2), "cap2:", cap(byte2)) // content2: [49 50 51 97 98 99] len2: 6 cap2: 1536
_, _, _, err := crypt.AESEnc(byte1)
if err != nil {
log.Fatal(err)
}
fmt.Println("content1:", byte1, "len1:", len(byte1), "cap1:", cap(byte1)) // content1: [49 50 51 97 98 99] len1: 6 cap1: 6
_, _, _, err = crypt.AESEnc(byte2)
if err != nil {
log.Fatal(err)
}
fmt.Println("content2:", byte2, "len2:", len(byte2), "cap2:", cap(byte2)) // content2: [132 200 7 200 195 8] len2: 6 cap2: 1536
}
func AESEnc(data []byte) ([]byte, []byte, string, error) {
key := make([]byte, 16)
iv := make([]byte, 16)
_, err := io.ReadFull(rand.Reader, key)
if err != nil {
return nil, nil, "", err
}
_, err = io.ReadFull(rand.Reader, iv)
if err != nil {
return nil, nil, "", err
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, nil, "", err
}
pdata := pckspadding(data, block.BlockSize())
stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(pdata, pdata)
return key, iv, base64.StdEncoding.EncodeToString(pdata), nil
}
func pckspadding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
byte2 changes after encryption, what happened?
I'm not familiar a crypto/cypher-XORKeyStream but I can tell you what XOR does to bits if that is helpfull. I have some Electronic experience and here is the truth table to an XOR gate:
Inputs X and Y represent two bits. The output Z is the result of XOR-ing X and Y.
In English you would say to yourself "Inputs, either one or the other but not both" results in an output of "True".
Don't know how much help this will be or how to apply it to more than two input bits with a crypto/cypher-XORKeyStream. But here would be an example:
X = 00110001010
Y = 11111111111
Z = 11001110101
Good Luck!