【问题标题】:receiving crypto/rsa: decryption error when decrypting a file接收加密/rsa:解密文件时出现解密错误
【发布时间】:2020-11-16 02:34:26
【问题描述】:

这是我的解密函数,但它不断返回:“crypto/rsa:解密错误”。任何意见将是有益的!我将加密分成几部分,因为密钥不断引发“密钥太短错误”。我是 golang 加密工作的新手。

func DecryptFile(file string, privateKey *rsa.PrivateKey)([]byte, error){
  var decryptedBytes []byte
  // read the file into bytes
  data, err := ioutil.ReadFile(file)
  if err != nil {
    return decryptedBytes,err
  }
  fmt.Println(len(data))
  var decryptedByte []byte
  ByteSlice := split(data,200)
  rng := rand.Reader
  for _,bytes := range ByteSlice{
    decryptedBytes,err = rsa.DecryptOAEP(
      sha256.New(),
      rng,
      privateKey,
      bytes,
      nil)
    if err != nil {
     return decryptedBytes,err
    }
    decryptedBytes = append(decryptedBytes,decryptedByte...)
  }

  return decryptedBytes,nil
}

加密功能:

func EncryptFile(file string, PublicKey *rsa.PublicKey)([]byte, error){
  var encryptedBytes []byte

  // read the file into bytes
  data, err := ioutil.ReadFile(file)
  if err != nil {
    return encryptedBytes,err
  }
  fmt.Println(len(data))
  // Encrypts the file
  //fmt.Println(PublicKey.N.BitLen())
  //_,_ = strconv.Atoi((PublicKey.N).String())
  ByteSlice := split(data,200)
  var encryptedByte []byte
  rng := rand.Reader
  for _,bytes := range ByteSlice{
    encryptedByte, err = rsa.EncryptOAEP(
         sha256.New(),
         rng,
         PublicKey,
         bytes,
         nil)
    if err != nil {
      return encryptedBytes,err
    }
    encryptedBytes = append(encryptedBytes, encryptedByte...)
  }

  // Returns file encrypted
  return encryptedBytes,nil
}

【问题讨论】:

  • 不要拆分输入。
  • 我尝试这样做,但它返回相同的错误。我也会添加加密功能。
  • 你的分割函数是什么,你是如何生成私钥/公钥的?
  • ECB模式下最好使用hybrid encryption而不是RSA。这更快,更不容易出错
  • 查看加密数据与明文数据的大小。请注意,它已经变大了。您在解密时没有考虑到这一点,而只是假设这些块是 200 字节...... RSA 不适合批量加密

标签: go encryption


【解决方案1】:

rsa.EncryptOAEP() 的步长不应超过:

publicKey.Size() - 2*hash.Size() - 2

您可以使用publicKey.Size() - 2*hash.Size() - 2 作为rsa.EncryptOAEP() 的步骤

无论步长多长, rsa.EncryptOAEP()函数总是产生固定长度的加密数据,固定长度为publicKey.Size()

所以,rsa.DecryptOAEP() 的步骤是:

publicKey.Size()

请看: RS256 message too long for RSA public key size - error signing JWT

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 2019-10-12
    • 1970-01-01
    • 2018-05-06
    • 1970-01-01
    • 2020-09-22
    相关资源
    最近更新 更多