public static final String ALGORITHM = "RSA";
public static final int KEYSIZE = 1024*10;//16384;
public static String public_key_file = "public_key.dat";
public static String private_key_file = "private_key.dat";
public static void generateKeyPair() throws NoSuchAlgorithmException, FileNotFoundException, IOException {
SecureRandom sr = new SecureRandom();
KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGORITHM);
kpg.initialize(KEYSIZE, sr);
// 生成密钥对
KeyPair keyPair = kpg.generateKeyPair();
// 得到公钥
Key publicKey = keyPair.getPublic();
// 得到私钥
Key privateKey = keyPair.getPrivate();
ObjectOutputStream oosl1 = new ObjectOutputStream(new FileOutputStream(public_key_file));
ObjectOutputStream oosl2 = new ObjectOutputStream(new FileOutputStream(private_key_file));
oosl1.writeObject(publicKey);
oosl2.writeObject(privateKey);
oosl1.close();
oosl2.close();
}
public static String encrypt(String source) throws Exception {
generateKeyPair();
// 取出公钥
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(public_key_file));
Key key = (Key) ois.readObject();
ois.close();
// 开始对公钥加密
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] b = source.getBytes();
// 使用base64进行编码 字符和byte转换
byte[] doFinal = cipher.doFinal(b);
return new String(Base64.getEncoder().encode(doFinal));
}
public static String decrypt(String cryptText) throws Exception {
// 读文件
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(private_key_file));
Key key = (Key) ois.readObject();
ois.close();
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
// byte[] decode = Base64.getDecoder().decode(cryptText);
// byte[] decode = it.sauronsoftware.base64.Base64.encode(cryptText).getBytes();
BASE64Decoder d = new BASE64Decoder();
byte[] decodeBuffer = d.decodeBuffer(cryptText);
byte[] doFinal = cipher.doFinal(decodeBuffer);
return new String(doFinal);
}
public static void main(String[] args) throws Exception {
String name = "ocean";
String text = encrypt(name);
System.out.println(text);
String target = decrypt(text);
System.out.println(target);
}