Golang AES加密

huangapple go评论75阅读模式
英文:

Golang AES encryption

问题

我是你的中文翻译助手,以下是你要翻译的内容:

我刚开始学习Go语言,正在尝试使用crypto包。

我的代码如下:

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))
}

我得到了以下错误:

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

我做错了什么?

你可以在Go Playground上找到我的代码这里

英文:

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

答案1

得分: 6

我已经为你翻译了代码部分,如下所示:

package main

import "fmt"
import "crypto/aes"

func main() {
    bc, err := aes.NewCipher([]byte("key3456789012345"))
    if err != nil {
        fmt.Println(err)
    }
    fmt.Printf("区块大小为 %d\n", bc.BlockSize())

    var dst = make([]byte, 16)
    var src = []byte("sensitive1234567")

    bc.Encrypt(dst, src)
    fmt.Println(dst)
}

一般来说,你应该检查错误代码并仔细阅读你调用的每个函数的文档。此外,这是一个分块密码,因此它需要特定大小的字节块。

英文:

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\n", 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.

huangapple
  • 本文由 发表于 2013年12月31日 12:58:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/20851943.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定