当我尝试运行以下代码时(我正在尝试加密字符串的字节数组表示,在CFB模式下使用AES)我得到无效的内存地址或nil指针解除引用错误,在 sEnc.XORKeyStream(msgB,msgB)行上。文档说XORKeyStream的源和目标可以是相同的字节数组(也尝试使用单独的目标,但没有骰子),但我无法弄清楚导致错误的原因。我在OS X Lion上使用最新版本的Go App Engine SDK。
由于此时我仍然试图让代码只是加密某些东西,我只是生成一个随机密钥而不打算存储它。
func generateKey(w http.ResponseWriter, r *http.Request) {
key := make([]byte, 32)
n, err := rand.Read(key)
err = err
if(err != nil) {
fmt.Fprint(w, err)
return
}
if(n != 32) {
fmt.Fprint(w, "Not enough bytes read.")
return
}
c, err := aes.NewCipher(key)
if(err != nil) {
fmt.Fprint(w, err)
}
iv := make([]byte, 32)
n, err = rand.Read(iv)
err = err
if(err != nil) {
fmt.Fprint(w, err)
return
}
if(n != 32) {
fmt.Fprint(w, "Not enough bytes read.")
return
}
sEnc := cipher.NewCFBEncrypter(c, iv)
msg := "text to be encrypted"
msgR := strings.NewReader(msg)
msgB := make([]byte, msgR.Len())
n, err = msgR.Read(msgB)
if(err != nil) {
fmt.Fprint(w, err)
return
}
if(n == 0) {
fmt.Fprint(w, "No bytes read.")
return
}
fmt.Fprint(w, msgB)
fmt.Fprint(w, "<br>")
sEnc.XORKeyStream(msgB, msgB)
fmt.Fprint(w, msgB)
}
错误消息:
2011/08/15 15:15:58 http:恐慌服务:运行时错误:无效 内存地址或零指针解引用runtime.panic /private/tmp/appengine/google_appengine/goroot/src/pkg/runtime/proc.c:1041 runtime.panicstring /private/tmp/appengine/google_appengine/goroot/src/pkg/runtime/runtime.c:116 runtime.sigpanic /private/tmp/appengine/google_appengine/goroot/src/pkg/runtime/darwin/thread.c:470 server.generateKey server / server.go:66 http.HandlerFunc·ServeHTTP /private/tmp/appengine/google_appengine/goroot/src/pkg/http/server.go:589 HTTP。* ServeMux·ServeHTTP /private/tmp/appengine/google_appengine/goroot/src/pkg/http/server.go:790 appengine_internal.handleFilteredHTTP /private/tmp/appengine/google_appengine/goroot/src/pkg/appengine_sdk/go_appengine_sdk/appengine_internal/api_dev.go:58 http.HandlerFunc·ServeHTTP /private/tmp/appengine/google_appengine/goroot/src/pkg/http/server.go:589 HTTP。*康恩·服务 /private/tmp/appengine/google_appengine/goroot/src/pkg/http/server.go:555 runtime.goexit /private/tmp/appengine/google_appengine/goroot/src/pkg/runtime/proc.c:178 INFO 2011-08-15 15:15:58,310 dev_appserver.py:4248]“GET / genkey / aes256 HTTP / 1.1“500 -
我发布了the rest of the code来粘贴bin,但它只是include / init函数,没有什么有趣的。
答案 0 :(得分:3)
sEnc
为nil
。对于cipher.NewCFBEncrypter
,“iv必须与Block的块长度相同。” AES块大小是128位还是16位?例如,
iv := make([]byte, c.BlockSize())