dosryjij88555
2013-12-31 04:58
浏览 58
已采纳

Golang AES加密

I am new to Go and I am trying out the crypto package.

My code looks like:

package main

import "fmt"
import . "crypto/aes"

func main() {
    block, _ := NewCipher([]byte("randomkey"))

    var dst = []byte{}
    var src = []byte("senstive")

    block.Encrypt(dst, src)
    fmt.Println(string(src))
}

I get the following error:

panic: runtime error: invalid memory address or nil pointer dereference.

What am I doing wrong?

My code can be found at the Go playground here

图片转代码服务由CSDN问答提供 功能建议

我是Go的新手,我正在尝试使用加密软件包。

我的代码如下:

 包main 
 
import“ fmt” 
import。  “ crypto / aes” 
 
func main(){
块,_:= NewCipher([] byte(“ randomkey”))
 
 var dst = [] byte {} 
 var src = [] 字节(“敏感”)
 
块。加密(dst,src)
 fmt.Println(string(src))
} 
   
 
 

I 出现以下错误:

 恐慌:运行时错误:无效的内存地址或nil指针取消引用。
   
 
 

什么 我做错了吗?

可以在Go游乐场找到我的代码 这里

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • drcrc28428 2013-12-31 05:26
    已采纳

    I fixed it:

    package main
    
    import "fmt"
    import "crypto/aes"
    
    func main() {
        bc, err := aes.NewCipher([]byte("key3456789012345"))
        if (err != nil) {
            fmt.Println(err);
        }
        fmt.Printf("The block size is %d
    ", bc.BlockSize())
    
        var dst = make([]byte, 16)
        var src = []byte("sensitive1234567")
    
        bc.Encrypt(dst, src)
        fmt.Println(dst)
    }
    

    In general, you should be checking error codes and carefully reading documentation of every function you call. Also, this is a block cypher so it requires blocks of bytes that are a specific size.

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongzen7263 2017-07-04 09:33

    You could check this answer: Golang, encrypting a string with AES and Base64

    there's a good example and an official example from golang.org

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题