转到河豚怪异的东西
我有以下功能使用Blowfish.If编码字符串,我把只是一个字符串到字节数组它的工作原理。问题是与线 cipher.Encrypt(ENC [0:],SRC)转到河豚怪异的东西
func BlowFish(str string){
key := []byte("super secret key")
cipher,err := blowfish.NewCipher(key)
if err != nil {
log.Fatal(err)
}
//very weird that I get index out of range if I insert a var
src :=[]byte(str+"\n\n\n")
var enc [512]byte
cipher.Encrypt(enc[0:],src)
fmt.Println("Encoded",enc)
var decrypt[8] byte
cipher.Decrypt(decrypt[0:],enc[0:])
result:=bytes.NewBuffer(nil)
result.Write(decrypt[0:8])
fmt.Println(string(result.Bytes()))
}
我不明白的问题
看起来像我发现了什么问题。 cypher.Encrypt接受长度为8的字节数组。但字节数组[]字节(str +“\ n \ n \ n”)的长度为4.这就是为什么我的索引超出范围。如果我有一个数组[]字节(“我的str编码”+“\ n \ n \ n”)。它是len是2个字符串的len。对于现在的解决方案是增加等等\ n字符为具有阵列STR +的长度“\ n .... \ n”个> =大于8
虽然这可能导致使用围棋的Blowfish错误,它是正确的。 Blowfish是一个64位(读取8字节)的分组密码。正如你发现的那样,你的字符串不仅需要8个字节的填充,而且你希望加密的任何数据都必须填充以便所有的块都等于8个字节。
要做到这一点,你应该检查你的数据的模量和填充剩余,使数据的长度为8的倍数,像这样。
func blowfishChecksizeAndPad(pt []byte) []byte {
// calculate modulus of plaintext to blowfish's cipher block size
// if result is not 0, then we need to pad
modulus := len(pt) % blowfish.BlockSize
if modulus != 0 {
// how many bytes do we need to pad to make pt to be a multiple of
//blowfish's block size?
padlen := blowfish.BlockSize - modulus
// let's add the required padding
for i := 0; i < padlen; i++ {
// add the pad, one at a time
pt = append(pt, 0)
}
}
// return the whole-multiple-of-blowfish.BlockSize-sized plaintext
// to the calling function
return pt
}
最好不要使用null填充,它与二进制数据不兼容。请使用{PKCS#7填充](https://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS7)。 – zaph
在问题的上下文中,当他编码一个字符串时,没有二进制数据,并且可以将空字符作为空格删除。 –
Downvoting是因为我不同意字符串需要PKCS7填充,特别是在应该保持简单的示例代码的上下文中,只是让你看起来很小气。 :| –
请告诉我们你的断码的,不是你的工作代码。 – Flimzy
这里是破碎版本 –
你得到了什么_exact_错误?没有理由你的'src:='行应该失败。参见[游乐场](https://play.golang.org/p/N4h7onxGq7)。 – Flimzy