I have the following function which encodes the string using Blowfish.If I put just a string to byte array it works. The problem is with line 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+"
")
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()))
}
I don't understand the problem
Looks like I found what's wrong. cypher.Encrypt accepts byte array of length 8. But the length of byte array []byte(str+" ") is 4. That's why I get an index out of range. If I have an array []byte("My str to encode"+" "). It's len is len of 2 strings. The solution for now is to add more chars to have the length of array str+" .... " >=than 8
While this may result in an error using Go Blowfish, it is correct. Blowfish is a 64-bit (read 8-byte) block cipher. As you've discovered, not only does your string have to be 8 bytes with padding, but any data you wish to encrypt must be padded so that all blocks are equal to eight bytes.
To do so, you should be checking the modulus of your data, and padding the remainder so that the length of the data is a multiple of 8, like so.
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
}