当前位置 博文首页 > 程序员石磊:rsa 生成密匙 ,密匙导出,加密解密封装
利用hutool实现,原谅我只是个调参侠!
import cn.hutool.core.io.file.FileReader;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import org.springframework.util.ResourceUtils;
public class RSAUtil {
private static RSA rsa = null;
static {
try {
FileReader fileReader = new FileReader(ResourceUtils.getFile("classpath:publickey.pem"));
String publicKeyStr = fileReader.readString();
FileReader fileReaderPrivate = new FileReader(ResourceUtils.getFile("classpath:privatekey.pem"));
String privateKeyStr = fileReaderPrivate.readString();
rsa = new RSA(privateKeyStr, publicKeyStr);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 解密
*
* @param data
* @return
*/
public static String decrypt(String data) {
return rsa.decryptStr(data, KeyType.PrivateKey);
}
/**
* 加密
*
* @param data
* @return
*/
public static String encrypt(String data) {
return rsa.encryptHex(data, KeyType.PublicKey);
}
}
@Test
public void exportKeys() throws IOException {
RSA rsa = new RSA();
//获得私钥
rsa.getPrivateKey();
rsa.getPrivateKeyBase64();
//获得公钥
rsa.getPublicKey();
rsa.getPublicKeyBase64();
FileWriter writer = new FileWriter("d:/publickey.pem");
writer.write(rsa.getPublicKeyBase64());
FileWriter writer1 = new FileWriter("d:/privatekey.pem");
writer1.write( rsa.getPrivateKeyBase64());
}
@Test
public void testDecryptEncrypt() throws IOException {
String en = RSAUtil.encrypt("程序员123");
LOGGER.info(en);
String de = RSAUtil.decrypt(en);
LOGGER.info(de);
Assert.assertEquals("程序员123", de);
}
cs