[英]Byte slice is changing by self
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.
一开始它的值是正确的,但是在我使用 encrypt function 之后它正在改变,我不知道为什么。 Please help.
请帮忙。 Here is small part of my code with output:
这是我的 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]
.您的 function
magmaG
返回append(left, right)
,其中left
指向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.当
blk
有足够的容量时,这个append
覆盖blk
的底层数组,导致“原始”内容以您所看到的稍微不可预测的方式发生变化。
From your pastebin link, the magmaG
function looks like this:从您的 pastebin 链接,
magmaG
function 看起来像这样:
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.一个简单的更改是用
return append(append([]byte{}, left...), right...)
替换最后一行,它从一个新的空后备数组构造一个字节切片。
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...)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.