接收加密/rsa:解密文件时出现解密错误

IT小君   2022-11-11T00:11:47

这是我的解密函数,但它不断返回:“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
}
评论(1)
IT小君

的步骤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 消息对于 RSA 公钥大小来说太长 - 错误签名 JWT

2022-11-11T00:11:47   回复