Golang AES ECB加密

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

Golang AES ECB Encryption

问题

尝试在Go中模拟一种基本上是AES ECB模式加密的算法。

以下是我目前的代码:

func Decrypt(data []byte) []byte {
    cipher, err := aes.NewCipher([]byte(KEY))
    if err == nil {
        cipher.Decrypt(data, PKCS5Pad(data))
        return data
    }
    return nil
}

我还有一个经过测试和工作正常的PKCS5Padding算法,它首先对数据进行填充。我找不到关于如何在Go的AES包中切换加密模式的任何信息(在文档中肯定没有)。

我在另一种语言中有这段代码,这就是我知道这个算法不完全正确的原因。

编辑:以下是我从问题页面解释的方法:

func AESECB(ciphertext []byte) []byte {
    cipher, _ := aes.NewCipher([]byte(KEY))
    fmt.Println("AESing the data")
    bs := 16
    if len(ciphertext)%bs != 0 {
        panic("Need a multiple of the blocksize")
    }

    plaintext := make([]byte, len(ciphertext))
    for len(plaintext) > 0 {
        cipher.Decrypt(plaintext, ciphertext)
        plaintext = plaintext[bs:]
        ciphertext = ciphertext[bs:]
    }
    return plaintext
}

实际上,这并没有返回任何数据,也许在从加密改为解密时我搞错了什么。

英文:

Trying to emulate an algorithm in Go that is basically AES ECB Mode encryption.

Here's what I have so far

func Decrypt(data []byte) []byte {
	cipher, err := aes.NewCipher([]byte(KEY))
	if err == nil {
		cipher.Decrypt(data, PKCS5Pad(data))
		return data
	}
	return nil
}

I also have a PKCS5Padding algorithm, which is tested and working, which pads the data first. I cant find any information on how to switch the encryption mode in the Go AES package (it's definitely not in the docs).

I have this code in another language, which is how I know this algorithm isn't working quite correctly.

EDIT: Here is the method as I have interpreted from on the issue page

func AESECB(ciphertext []byte) []byte {
    cipher, _ := aes.NewCipher([]byte(KEY))
    fmt.Println("AESing the data")
    bs := 16
    if len(ciphertext)%bs != 0     {
	    panic("Need a multiple of the blocksize")
    }

    plaintext := make([]byte, len(ciphertext))
    for len(plaintext) > 0 {
	    cipher.Decrypt(plaintext, ciphertext)
	    plaintext = plaintext[bs:]
	    ciphertext = ciphertext[bs:]
    }
    return plaintext
}

This is actually not returning any data, maybe I screwed something up when changing it from encripting to decripting

答案1

得分: 10

电子密码本(ECB)是一种非常直接的操作模式。要加密的数据被分成具有相同大小的字节块。对于每个块,应用一个密码算法,例如AES,生成加密的块。

下面的代码片段解密了ECB中的AES-128数据(请注意,块大小为16字节):

package main

import (
	"crypto/aes"
)

func DecryptAes128Ecb(data, key []byte) []byte {
	cipher, _ := aes.NewCipher([]byte(key))
	decrypted := make([]byte, len(data))
	size := 16

	for bs, be := 0, size; bs < len(data); bs, be = bs+size, be+size {
		cipher.Decrypt(decrypted[bs:be], data[bs:be])
	}

	return decrypted
}

正如@OneOfOne所提到的,ECB是不安全的,并且非常容易检测,因为重复的块将始终加密为相同的加密块。这个Crypto SE答案给出了一个非常好的解释。

英文:

Electronic codebook ("ECB") is a very straightforward mode of operation. The data to be encrypted is divided into byte blocks, all having the same size. For each block, a cipher is applied, in this case AES, generating the encrypted block.

The code snippet below decrypts AES-128 data in ECB (note that the block size is 16 bytes):

package main

import (
	&quot;crypto/aes&quot;
)

func DecryptAes128Ecb(data, key []byte) []byte {
	cipher, _ := aes.NewCipher([]byte(key))
	decrypted := make([]byte, len(data))
	size := 16

	for bs, be := 0, size; bs &lt; len(data); bs, be = bs+size, be+size {
		cipher.Decrypt(decrypted[bs:be], data[bs:be])
	}

	return decrypted
}

As mentioned by @OneOfOne, ECB is insecure and very easy to detect, as repeated blocks will always encrypt to the same encrypted blocks. This Crypto SE answer gives a very good explanation why.

答案2

得分: 7

为什么?我们有意将ECB排除在外:它是不安全的,而且如果需要的话,实现起来非常简单。

https://github.com/golang/go/issues/5597

英文:

> Why? We left ECB out intentionally: it's insecure, and if needed it's
trivial to implement.

https://github.com/golang/go/issues/5597

答案3

得分: 4

我使用了你的代码,所以我觉得有必要向你展示我是如何修复它的。

我正在使用Go语言完成这个问题的密码朋克挑战

我将为你解释错误,因为代码大部分是正确的。

for len(plaintext) > 0 {
    cipher.Decrypt(plaintext, ciphertext)
    plaintext = plaintext[bs:]
    ciphertext = ciphertext[bs:]
}

这个循环确实解密了数据,但没有将其放在任何地方。它只是简单地将这两个数组向前移动,没有产生任何输出。

i := 0
plaintext := make([]byte, len(ciphertext))
finalplaintext := make([]byte, len(ciphertext))
for len(ciphertext) > 0 {
    cipher.Decrypt(plaintext, ciphertext)
    ciphertext = ciphertext[bs:]
    decryptedBlock := plaintext[:bs]
    for index, element := range decryptedBlock {
        finalplaintext[(i*bs)+index] = element
    }
    i++
    plaintext = plaintext[bs:]
}
return finalplaintext[:len(finalplaintext)-5]

这个改进的部分将解密后的数据存储在一个名为finalplaintext的新的[]byte切片中。如果你返回它,你就可以得到数据。

以这种方式进行操作很重要,因为Decrypt函数一次只能处理一个块大小的数据。

我返回一个切片,因为我怀疑它可能是填充的。我对密码学和Go语言都不太熟悉,所以欢迎任何人纠正/修改这个代码。

英文:

I used your code so I feel the need to show you how I fixed it.

I am doing the cryptopals challenges for this problem in Go.

I'll walk you through the mistake since the code is mostly correct.

for len(plaintext) &gt; 0 {
    cipher.Decrypt(plaintext, ciphertext)
    plaintext = plaintext[bs:]
    ciphertext = ciphertext[bs:]
}

The loop does decrypt the data but does not put it anywhere. It simply shifts the two arrays along producing no output.

i := 0
plaintext := make([]byte, len(ciphertext))
finalplaintext := make([]byte, len(ciphertext))
for len(ciphertext) &gt; 0 {
	cipher.Decrypt(plaintext, ciphertext)
	ciphertext = ciphertext[bs:]
	decryptedBlock := plaintext[:bs]
	for index, element := range decryptedBlock {
		finalplaintext[(i*bs)+index] = element
	}
	i++
	plaintext = plaintext[bs:]
} 
return finalplaintext[:len(finalplaintext)-5]

What this new improvement does is store the decrypted data into a new []byte called finalplaintext. If you return that you get the data.

It's important to do it this way since the Decrypt function only works one block size at a time.

I return a slice because I suspect it's padded. I am new to cryptography and Go so anyone feel free to correct/revise this.

答案4

得分: 1

理想情况下,你希望实现crypto/cipher#BlockMode接口。由于官方没有提供这样的接口,我使用crypto/cipher#NewCBCEncrypter作为起点:

package ecb
import "crypto/cipher"

type ecbEncrypter struct { cipher.Block }

func newECBEncrypter(b cipher.Block) cipher.BlockMode {
   return ecbEncrypter{b}
}

func (x ecbEncrypter) BlockSize() int {
   return x.Block.BlockSize()
}

func (x ecbEncrypter) CryptBlocks(dst, src []byte) {
   size := x.BlockSize()
   if len(src) % size != 0 {
      panic("crypto/cipher: input not full blocks")
   }
   if len(dst) < len(src) {
      panic("crypto/cipher: output smaller than input")
   }
   for len(src) > 0 {
      x.Encrypt(dst, src)
      src, dst = src[size:], dst[size:]
   }
}
英文:

Ideally you want to implement the crypto/cipher#BlockMode interface. Since an official one doesn't exist, I used crypto/cipher#NewCBCEncrypter as a starting point:

package ecb
import &quot;crypto/cipher&quot;

type ecbEncrypter struct { cipher.Block }

func newECBEncrypter(b cipher.Block) cipher.BlockMode {
   return ecbEncrypter{b}
}

func (x ecbEncrypter) BlockSize() int {
   return x.Block.BlockSize()
}

func (x ecbEncrypter) CryptBlocks(dst, src []byte) {
   size := x.BlockSize()
   if len(src) % size != 0 {
      panic(&quot;crypto/cipher: input not full blocks&quot;)
   }
   if len(dst) &lt; len(src) {
      panic(&quot;crypto/cipher: output smaller than input&quot;)
   }
   for len(src) &gt; 0 {
      x.Encrypt(dst, src)
      src, dst = src[size:], dst[size:]
   }
}

答案5

得分: -2

我被一些事情搞糊涂了。

首先,我需要一个上述算法的AES-256版本,但显然当给定的密钥长度为32时,aes.Blocksize(即16)不会改变。因此,只需提供长度为32的密钥即可使算法成为AES-256。

其次,解密后的值仍然包含填充,填充值取决于加密字符串的长度。例如,当有5个填充字符时,填充字符本身将是5。

这是我的一个返回字符串的函数:

func DecryptAes256Ecb(hexString string, key string) string {
    data, _ := hex.DecodeString(hexString)

    cipher, _ := aes.NewCipher([]byte(key))

    decrypted := make([]byte, len(data))
    size := 16

    for bs, be := 0, size; bs < len(data); bs, be = bs+size, be+size {
        cipher.Decrypt(decrypted[bs:be], data[bs:be])
    }

    // 移除填充。字节数组中的最后一个字符是填充字符的数量
    paddingSize := int(decrypted[len(decrypted)-1])
    return string(decrypted[0 : len(decrypted)-paddingSize])
}

希望对你有帮助!

英文:

I was confused by a couple of things.

First i needed a aes-256 version of the above algorithm, but apparently the aes.Blocksize (which is 16) won't change when the given key has length 32. So it is enough to give a key of length 32 to make the algorithm aes-256

Second, the decrypted value still contains padding and the padding value changes depending on the length of the encrypted string. E.g. when there are 5 padding characters the padding character itself will be 5.

Here is my function which returns a string:

func DecryptAes256Ecb(hexString string, key string) string {
  data, _ := hex.DecodeString(hexString)

  cipher, _ := aes.NewCipher([]byte(key))

  decrypted := make([]byte, len(data))
  size := 16

  for bs, be := 0, size; bs &lt; len(data); bs, be = bs+size, be+size {
	cipher.Decrypt(decrypted[bs:be], data[bs:be])
  }

  // remove the padding. The last character in the byte array is the number of padding chars
  paddingSize := int(decrypted[len(decrypted)-1])
  return string(decrypted[0 : len(decrypted)-paddingSize])
}

huangapple
  • 本文由 发表于 2014年6月6日 07:48:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/24072026.html
匿名

发表评论

匿名网友

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

确定