I want to encrypt a string with RSA public and private keys. However, when I try to decrypt the characters back to there initial ascii-value, they return something different. Here are my methods for encrypting and decrypting:

```
/**
* Method to encrypt a string using associated public-key
* @param plainText string to cipher
* @returns string of encrypted plainText
*/
public encryptData(plainText: string): string {
let cipher = "";
for (let i = 0; i < plainText.length; i++) {
console.log(plainText.charCodeAt(i));
let temp: number = Math.pow(plainText.charCodeAt(i), this.e) % this.n;
console.log(String.fromCharCode(temp).charCodeAt(i));
cipher += String.fromCharCode(temp);
}
return cipher;
}
/**
* Method to decrypt a string using associated private-key
* @param cipherText string to decrypt
* @returns string of encrypted plainText
*/
public decryptData(cipherText: string): string {
let text = "";
for (let i = 0; i < cipherText.length; i++) {
console.log(cipherText.charCodeAt(i));
let temp: number = Math.pow(cipherText.charCodeAt(i), this.d) % this.n;
text += String.fromCharCode(temp);
}
return text;
}
```

`n`

, `e`

and `d`

are 15, 7 and 13 respectively. Any advice on this would be greatly appreciated!

EDIT

Found a solution to the problem, use the following in method when creating variable `temp`

.

```
private modular_pow(base: number, expo: number, modulo: number) {
base = base % modulo;
var result = 1;
var x = base;
while(expo > 0){
var leastSignificantBit = expo % 2;
expo = Math.floor(expo / 2);
if (leastSignificantBit == 1) {
result = result * x;
result = result % modulo;
}
x = x * x;
x = x % modulo;
}
return result;
}
```

·
Juan Pablo Isaza

The size of the modulus N decides the maximum payload for textbook RSA. As it is the value 15 the message value must be 14 or lower.

Characters are commonly at least in the range 0..25 and that's not the character value but the index in the alphabet. So either you split up the characters even further or you need to use a larger modulus (such as p = 7, q = 19 and the all important n=133 which would be able to handle any ASCII character (of course wandering outside of printable ASCII for some values).

Beware that if you have larger components of your RSA that it becomes imperative to perform modular exponentiation using a specialized algorithm, instead of first performing exponentiation followed by a modulus calculation, which is very inefficient and will likely cause an integer overflow (or something similar) during the exponentiation step.

Note too that the output of your textbook RSA must be put into a (printable) character in your scheme. For practice you could also use just the numbers separated by space, ignoring the growth of the ciphertext.

·
Juan Pablo Isaza
Report