Reputation: 56
This is my decrypt function but it keeps returning: "crypto/rsa: decryption error". any advice would be helpful! I split the encryption into sections because the key kept raising the "key too short error". I am new to the encryption work in 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
}
Encryption function:
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
}
Upvotes: 1
Views: 2918
Reputation: 37
The step for rsa.EncryptOAEP()
should be no longer than :
publicKey.Size() - 2*hash.Size() - 2
You can use publicKey.Size() - 2*hash.Size() - 2
as step of rsa.EncryptOAEP()
No matter the length of step,
rsa.EncryptOAEP()
function always produce fixed length encrypted data, the fixed length is publicKey.Size()
.
so, the step for rsa.DecryptOAEP()
is :
publicKey.Size()
Please see : RS256 message too long for RSA public key size - error signing JWT
Upvotes: 1