Skip to content

Commit

Permalink
rsautil: Decrypt data with splited sizes
Browse files Browse the repository at this point in the history
  • Loading branch information
ish-hcc committed Sep 24, 2024
1 parent 69aa0a8 commit 08d6e90
Showing 1 changed file with 35 additions and 4 deletions.
39 changes: 35 additions & 4 deletions lib/rsautil/rsaUtil.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package rsautil

import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/sha512"
Expand All @@ -25,9 +26,39 @@ func BytesToPrivateKey(priv []byte) (*rsa.PrivateKey, error) {
// DecryptWithPrivateKey decrypts data with private key
func DecryptWithPrivateKey(ciphertext []byte, priv *rsa.PrivateKey) []byte {
hash := sha512.New()
plaintext, err := rsa.DecryptOAEP(hash, rand.Reader, priv, ciphertext, nil)
if err != nil {
log.Error(err)

chunkSize := priv.Size()

if len(ciphertext) == 0 {
log.Error("ciphertext is empty")
return nil
}

var plaintextData bytes.Buffer
offset := 0

for offset < len(ciphertext) {
end := offset + chunkSize
if end > len(ciphertext) {
log.Error("invalid ciphertext length")
return nil
}

chunk := ciphertext[offset:end]
plaintext, err := rsa.DecryptOAEP(hash, rand.Reader, priv, chunk, nil)
if err != nil {
log.Error(err)
return nil
}

_, err = plaintextData.Write(plaintext)
if err != nil {
log.Error(err)
return nil
}

offset = end
}
return plaintext

return plaintextData.Bytes()
}

0 comments on commit 08d6e90

Please sign in to comment.