Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions cipher/rsa/rsa2.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ package rsa

import (
"encoding/binary"
"fmt"
"math/big"
"math/rand"
"strings"

"github.com/TheAlgorithms/Go/math/gcd"
"github.com/TheAlgorithms/Go/math/lcm"
Expand Down Expand Up @@ -61,37 +61,37 @@ func New() *rsa {
// EncryptString encrypts the data using RSA algorithm
// returns the encrypted string
func (rsa *rsa) EncryptString(data string) string {
var nums []byte
var result strings.Builder

for _, char := range data {
for i := 0; i < len(data); i++ {
slice := make([]byte, 8)
binary.BigEndian.PutUint64( // convert uint64 to byte slice
slice,
encryptDecryptInt(rsa.publicKey, rsa.modulus, uint64(char)), // encrypt each character
encryptDecryptInt(rsa.publicKey, rsa.modulus, uint64(data[i])), // encrypt each byte
)
nums = append(nums, slice...)
result.Write(slice)
}

return string(nums)
return result.String()
}

// DecryptString decrypts the data using RSA algorithm
// returns the decrypted string
func (rsa *rsa) DecryptString(data string) string {
result := ""
var result strings.Builder
middle := []byte(data)

for i := 0; i < len(middle); i += 8 {
if i+8 > len(middle) {
break
}

slice := middle[i : i+8]
slice := middle[i : i+8] // temp slice
num := binary.BigEndian.Uint64(slice) // convert byte slice to uint64
result += fmt.Sprintf("%c", encryptDecryptInt(rsa.privateKey, rsa.modulus, num))
result.WriteByte(byte(encryptDecryptInt(rsa.privateKey, rsa.modulus, num)))
}

return result
return result.String()
}

// GetPublicKey returns the public key and modulus
Expand Down
31 changes: 31 additions & 0 deletions cipher/rsa/rsa2_fuzz_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package rsa

import (
"testing"
)

func FuzzRSA2RoundTrip(f *testing.F) {
// Add seed corpus
f.Add("Hello")
f.Add("World")
f.Add("A")
f.Add("Test123")
f.Add("")
f.Add("Special chars: !@#")
f.Add("Unicode: αβγ")

f.Fuzz(func(t *testing.T, message string) {
rsaInstance := New()

if rsaInstance == nil {
t.Fatal("Failed to create RSA instance")
}

encrypted := rsaInstance.EncryptString(message)
decrypted := rsaInstance.DecryptString(encrypted)

if decrypted != message {
t.Errorf("RSA2 roundtrip failed:\n Original: %q\n Decrypted: %q", message, decrypted)
}
})
}
4 changes: 4 additions & 0 deletions cipher/rsa/rsa2_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ func TestRSA(t *testing.T) {
name: "Encrypt 'Hello, World!' and decrypt it back",
message: "Hello, World!",
},
{
name: "Encrypt an unicode string and decrypt it back",
message: "こんにちは世界",
},
}

for _, tt := range tests {
Expand Down