📄 privatecrypto.java
字号:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.security.Key;
import java.security.SecureRandom;
import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;
public class PrivateCrypto {
private Cipher cipher;
private Key pkey;
public PrivateCrypto() {
try {
pkey = readKey();
//cipher=Cipher.getInstance("DES");
cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
//cipher = Cipher.getInstance("DES/ECB/NoPadding");
} catch (Exception e) {
e.printStackTrace();
}
}
public byte[] getKey() {
return pkey.getEncoded();
}
public Key readKey() {
try {
java.io.ObjectInputStream in = new java.io.ObjectInputStream(new java.io.FileInputStream("key.dat"));
pkey = (Key)in.readObject();
in.close();
return pkey;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public byte[] encrypt(byte[] plainText) {
try {
//byte[] keyInfo = pkey.getEncoded();
//System.out.println(new String(keyInfo));
//System.out.println(keyInfo.length);
//byte[] plainText=str.getBytes("UTF8");
cipher.init(Cipher.ENCRYPT_MODE, pkey);
byte[] cipherText = cipher.doFinal(plainText);
//return (new String(cipherText, "UTF8"));
//return (new BASE64Encoder().encode(cipherText));
return cipherText;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//public byte[] decrypt(byte[] cipherText, byte[] keyInfo) {
public byte[] decrypt(byte[] cipherText) {
try {
//javax.crypto.spec.SecretKeySpec skey = new javax.crypto.spec.SecretKeySpec(keyInfo, "AES");
///cipher.init(Cipher.DECRYPT_MODE,skey);
cipher.init(Cipher.DECRYPT_MODE, pkey);
byte[] newPlainText = cipher.doFinal(cipherText);
//System.out.println(newPlainText.length);
//return (new String(newPlainText,"UTF8"));
return newPlainText;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) throws Exception {
byte[] plainText = "何利军,会议时间s^&*&*%%%".getBytes();
PrivateCrypto pe = new PrivateCrypto();
//String newStr;
byte[] cipherText;
//byte[] keyInfo = pe.getKey();
cipherText = pe.encrypt(plainText);
System.out.println(new String(cipherText));
System.out.println(new String(pe.decrypt(cipherText)));
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -