I am trying to realise encryption, and I have a problem with the byte slice of the original text. In the beginning it has correct value, but after I use encrypt function it is changing and I don't know why. Please help. Here is small part of my code with output:
func main() {
str := "Hello it's me, a Mario!!"
text := []byte(str)
keys := magmaExpandKey([]byte("asdfghjklz,cmvnfkwadmandksjtmdolasdasdf"))
var crypted []byte
//First block just for example
fmt.Printf("Original: %b\n", text[0:8])
crypted = magmaEncrypt(text[0:8], keys)
fmt.Printf("Original: %b\n", text[0:8])
/* Output:
Original: [1001000 1100101 1101100 1101100 1101111 100000 1101001 1110100]
Original: [1001000 1100101 1101100 1101100 11000011 1101001 11001110 1010111]
*/
fmt.Printf("Crypted: %s\n", crypted)
fmt.Printf("Decrypted: %s\n", magmaDecrypt(crypted, keys))
}
func magmaEncrypt(blk []byte, keys []roundKey) []byte {
var crypted []byte
crypted = magmaG(keys[0].Key, blk)
for i := 1; i < 31; i++ {
crypted = magmaG(keys[i].Key, crypted)
}
crypted = magmaG(keys[31].Key, crypted)
return crypted
}
Your function magmaG
returns append(left, right)
, where left
is at that point is pointing to blk[4:8]
. When blk
has enough capacity, this append
overwrites the underlying array of blk
causing the "original" contents to change in the slightly unpredictable way you're seeing.
From your pastebin link, the magmaG
function looks like this:
func magmaG(k []byte, a []byte) []byte {
var left []byte
var right []byte
var G []byte
// Делим 64-битный исходный блок на две части
left = a[0:4]
right = a[4:8]
// Производим преобразование g
G = magma_g(k, right)
// Ксорим результат преобразования g с левой половиной блока
G = magmaAddXor(left, G)
// Пишем в левую половину значение из правой
left = right
// Пишем результат GOST_Magma_Add в правую половину блока
right = G
// Сводим правую и левую части блока в одно целое
return append(left, right...)
}
A simple change would be to replace the final line with return append(append([]byte{}, left...), right...)
which constructs a byte slice from a new empty backing array.
I note that your code can be significantly simplified by removing all the intermediate variables:
func magmaG(k, a []byte) []byte {
G := magma_g(k, a[4:8])
G = magmaAddXor(a[:4], G)
return append(append(make([]byte, 0, 8), a[4:8]...), G...)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.