已改编此代码 - http://www.roseindia.net/answers/viewqa/Java-Beginners/7551-encryption-and-decryption.html
但我有一些错误。在 (str) 上,它一直说要启动变量。当我把它改正为
字符串 st,str = null;
并运行,它给了我“错误:无法找到或加载主类 tryoutEncryption.encryptingfile”
包试用加密;
import java.io.*;
import java.security.*;
import javax.crypto.*;
class EncryptAndDecrypt {
public static void main (String[] args) throws Exception{
KeyPairGenerator keygenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
keygenerator.initialize(1024, random);
KeyPair keypair = keygenerator.generateKeyPair();
PrivateKey privateKey = keypair.getPrivate();
PublicKey publicKey = keypair.getPublic();
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
BufferedReader br=new BufferedReader(new FileReader(new File("C:\\Users\\Desktop\\testing.txt")));
String st,str;
while((st=br.readLine()) != null) {
str+=st+" ";
}
byte[] cleartext = null;
cleartext = str.getBytes();
byte[] ciphertext = null;
ciphertext = cipher.doFinal(cleartext);
System.out.println("the encrypted text is: " + ciphertext.toString());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] cleartext1 = cipher.doFinal(ciphertext);
System.out.println("the decrypted cleartext is: " + new String(cleartext1));
}
}