最近在项目中需要用到RSA加密,特此记录一下。
首先需要生成一个用来加解密的秘钥对,包括一个秘钥和一个公钥,这里采用的是Java生成的,一般生产用的秘钥对都会采用专用的openSSL生成。
代码如下:
public static void main(String[] args) throws Exception { //1.初始化秘钥对 也可以使用openssl生成 秘钥对 KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA"); rsa.initialize(512); KeyPair keyPair = rsa.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate();//私钥 PublicKey publicKey = keyPair.getPublic();//公钥 System.out.println("私钥串:"+Hex.encodeHexString(privateKey.getEncoded())); System.out.println("公钥串:"+Hex.encodeHexString(publicKey.getEncoded())); //2.进行签名 String content = "加密内容"; PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKey.getEncoded()); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PrivateKey privateKey1 = keyFactory.generatePrivate(spec);//真正用来加密的私钥 Signature signature = Signature.getInstance("MD5withRSA"); signature.initSign(privateKey1); signature.update(content.getBytes()); byte[] res = signature.sign(); System.out.println("签名后的content:" + Hex.encodeHexString(res)); //3.验签 X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded()); keyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey1 = keyFactory.generatePublic((x509EncodedKeySpec)); signature = Signature.getInstance("MD5withRSA"); signature.initVerify(publicKey1); signature.update(content.getBytes()); boolean verify = signature.verify(res); System.out.println("验签结果:" + verify); }
其中Signature签名的算法,常用的有:
- MD5withRSA
- SHA1withRSA
- SHA256withRSA