dongxin1999
dongxin1999
2017-01-19 00:22

Go加密与使用相同密钥和iv的Ruby加密不同

  • aes
  • ruby

I have the following Ruby code:

require 'base64'
require 'openssl'

data = '503666666'

key = '4768c01c4f598828ef80d9982d95f888fb952c5b12189c002123e87f751e3e82'

nonce = '4eFi6Q3PX1478767
'
nonce = Base64.decode64(nonce)

c = OpenSSL::Cipher.new('aes-256-gcm')
c.encrypt
c.key = key
c.iv = nonce

result = c.update(data) + c.final
tag = c.auth_tag

puts Base64.encode64(result + tag) # => J3AVfNG84bz2UuXcfre7LVjSbMpX9XBq6g==

that I'm trying to replicate in Golang. Here's what I have so far:

package main

import (
    "fmt"
    "crypto/aes"
    "crypto/cipher"
    "encoding/base64"
    "encoding/hex"
)

func main() {
    data := []byte("503666666")

    key, err := hex.DecodeString(`4768c01c4f598828ef80d9982d95f888fb952c5b12189c002123e87f751e3e82`)
    if err != nil {
        panic(err)
    }

    nonceB64 := "4eFi6Q3PX1478767
"
    nonce, err := base64.StdEncoding.DecodeString(nonceB64)
    if err != nil {
        panic(err)
    }

    block, err := aes.NewCipher(key)
    if err != nil {
        panic(err.Error())
    }

    aesgcm, err := cipher.NewGCM(block)
    if err != nil {
        panic(err.Error())
    }

    ciphertext := aesgcm.Seal(nil, nonce, data, nil)
    fmt.Printf("%s
", base64.StdEncoding.EncodeToString(ciphertext))
}

However the outcome from the Go version is:

+S52HGbLV1xp+GnF0v8VNOqc5J2GY2+SqA==

vs.

J3AVfNG84bz2UuXcfre7LVjSbMpX9XBq6g==

Why am I getting different results?

Thanks,

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答