My problem is that after inputting a string, I encrypted the ASCII code of the string. The encrypted text will exceed the range of 0~127, and after writing into the txt file that most of them will become '?'. If I read the file, the ASCII code will be 63, so I can't decrypt the string correctly.
Sorry for my bad English, I am confused about this problem.
package test;
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
import java.io.IOException;
public class rsa2 {
public static void main(String[] args) throws IOException{
int p=23;
int q=11;
int N = p*q; //N=253
int n = (p-1)*(q-1); //n=220
int e = 7; //public key=(e,N)
int d; //private key=(d,N)
int i = 1;
while((e*i) % n != 1) {
i++;
}
d=i;
File ifs = new File("HW_Text.txt");
Scanner input = new Scanner(ifs);
File ofs = new File("RsaEncryptData2.txt");
if(!ofs.exists()) {
System.out.println("file not exists");
}
//encryption
try(PrintWriter output = new PrintWriter(ofs)){
while(input.hasNext()) {
String content = input.nextLine();
for(i=0; i<content.length(); i++) {
int M = content.charAt(i);
//System.out.print(M+" ");
int C = caculate(M,e,N);
char c = (char)(C);
output.print(c);
System.out.print(C+":"+c+" ");
}
}
output.close();
input.close();
}
ifs = new File("RsaEncryptData2.txt");
input = new Scanner(ifs);
ofs = new File("RsaDecryptData2.txt");
if(!ofs.exists()) {
System.out.println("file not exists");
}
//decryption
try(PrintWriter output = new PrintWriter(ofs)){
while(input.hasNext()) {
String content = input.nextLine();
for(i=0; i<content.length(); i++) {
int C = content.charAt(i);
System.out.print(C+" ");
int M = caculate(C,d,N);
char ans = (char)(M);
output.print(ans);
//System.out.print(ans);
}
}
output.close();
input.close();
}
}
static int caculate(int C, int d, int N) {
int M = 1;
while(d!=0) {
while(d%2==0) {
d=d/2;
C=(C*C)%N;
}
d--;
M=(M*C)%N;
}
return M;
}
}
