11package rsa
22
33import (
4+ "bytes"
45 "crypto/rand"
56 "crypto/rsa"
67 "crypto/x509"
@@ -34,15 +35,36 @@ func rsaEncrypt(plainText, publicKey []byte) (cipherText []byte, err error) {
3435 if err != nil {
3536 return nil , err
3637 }
37-
38- cipherText , err = rsa .EncryptPKCS1v15 (rand .Reader , pub , plainText )
39- if err != nil {
40- return nil , err
38+ pubSize , plainTextSize := pub .Size (), len (plainText )
39+ // EncryptPKCS1v15 encrypts the given message with RSA and the padding
40+ // scheme from PKCS #1 v1.5. The message must be no longer than the
41+ // length of the public modulus minus 11 bytes.
42+ //
43+ // The rand parameter is used as a source of entropy to ensure that
44+ // encrypting the same message twice doesn't result in the same
45+ // ciphertext.
46+ //
47+ // WARNING: use of this function to encrypt plaintexts other than
48+ // session keys is dangerous. Use RSA OAEP in new protocols.
49+ offSet , once := 0 , pubSize - 11
50+ buffer := bytes.Buffer {}
51+ for offSet < plainTextSize {
52+ endIndex := offSet + once
53+ if endIndex > plainTextSize {
54+ endIndex = plainTextSize
55+ }
56+ bytesOnce , err := rsa .EncryptPKCS1v15 (rand .Reader , pub , plainText [offSet :endIndex ])
57+ if err != nil {
58+ return nil , err
59+ }
60+ buffer .Write (bytesOnce )
61+ offSet = endIndex
4162 }
63+ cipherText = buffer .Bytes ()
4264 return cipherText , nil
4365}
4466
45- func rsaDecrypt (cryptText , privateKey []byte ) (plainText []byte , err error ) {
67+ func rsaDecrypt (cipherText , privateKey []byte ) (plainText []byte , err error ) {
4668 defer func () {
4769 if err := recover (); err != nil {
4870 switch err .(type ) {
@@ -57,10 +79,22 @@ func rsaDecrypt(cryptText, privateKey []byte) (plainText []byte, err error) {
5779 if err != nil {
5880 return []byte {}, err
5981 }
60- plainText , err = rsa .DecryptPKCS1v15 (rand .Reader , pri , cryptText )
61- if err != nil {
62- return []byte {}, err
82+ priSize , cipherTextSize := pri .Size (), len (cipherText )
83+ var offSet = 0
84+ var buffer = bytes.Buffer {}
85+ for offSet < cipherTextSize {
86+ endIndex := offSet + priSize
87+ if endIndex > cipherTextSize {
88+ endIndex = cipherTextSize
89+ }
90+ bytesOnce , err := rsa .DecryptPKCS1v15 (rand .Reader , pri , cipherText [offSet :endIndex ])
91+ if err != nil {
92+ return nil , err
93+ }
94+ buffer .Write (bytesOnce )
95+ offSet = endIndex
6396 }
97+ plainText = buffer .Bytes ()
6498 return plainText , nil
6599}
66100
0 commit comments