📄 testrsa.java
字号:
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import javax.crypto.Cipher;
public class testRSA {
public static void main(String[] agrs ) {
try {
testRSA ept = new testRSA();
String encryptText = "my information";
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("rsa");
keyPairGen.initialize(1024);
KeyPair KeyPair = keyPairGen.generateKeyPair();
RSAPrivateKey PrivateKey = (RSAPrivateKey) KeyPair.getPrivate();
RSAPublicKey PublicKey = (RSAPublicKey) KeyPair.getPublic();
byte[] e = ept.encrypt(PublicKey,encryptText.getBytes());//使用公钥加密过程
byte[] de = ept.decrypt(PrivateKey,e);//解密过程用自己的私钥
String str = "";
str = ept.bytesToString(e);
System.out.println(str);
System.out.println(ept.bytesToString(de));
}
catch (Exception e) {
e.printStackTrace();
}
}
protected String bytesToString(byte[] encryptByte) {
String result = "";
for( Byte bytes : encryptByte) {
result += (char) bytes.intValue();
}
return result;
}
protected byte[] encrypt(RSAPublicKey PublicKey,byte[] obj) {
if(PublicKey != null) {
try{
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE,PublicKey);
return cipher.doFinal(obj);
}
catch(Exception e) {
e.printStackTrace();
}
}
return null;
}
protected byte[] decrypt(RSAPrivateKey PrivateKey, byte[] obj) {
if(PrivateKey != null) {
try {
Cipher cipher = Cipher.getInstance("rsa");
cipher.init(Cipher.DECRYPT_MODE,PrivateKey);
return cipher.doFinal(obj);
}
catch(Exception e) {
e.printStackTrace();
}
}
return null;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -