直接上代码,如下:
import org.apache.commons.codec.binary.Base64; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; /** * 加密工具 * @author huangxin 2020/1/2 */ public class EncryptTool { class KeyBean { /** 私钥 */ private String privateKey; /** 公钥 */ private String publicKey; public String getPrivateKey() { return privateKey; } public void setPrivateKey(String privateKey) { this.privateKey = privateKey; } public String getPublicKey() { return publicKey; } public void setPublicKey(String publicKey) { this.publicKey = publicKey; } } /** * 生成RSA公、私钥对 * @return * @throws NoSuchAlgorithmException */ public KeyBean generateRSAKeyPairs() throws NoSuchAlgorithmException { KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(1024); KeyPair keyPair = generator.genKeyPair(); KeyBean keyBean = new KeyBean(); keyBean.setPrivateKey(Base64.encodeBase64String(keyPair.getPrivate().getEncoded())); keyBean.setPublicKey(Base64.encodeBase64String(keyPair.getPublic().getEncoded())); return keyBean; } public static void main(String[] args) throws Exception { EncryptTool demo = new EncryptTool(); KeyBean keyBean = demo.generateRSAKeyPairs(); System.out.println("公钥:" + keyBean.getPublicKey()); System.out.println("私钥:" + keyBean.getPrivateKey()); } }
运行示例,输出如下:
公钥:MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCuOFMwnouXWEueTm2Qmua5oo8J7frN96DoSDtw11ObrfvfVKu91GcjPlF/ynUeyjwPuzmi+bkCIDs2wUn0wz3CU52o4e1drzLiDOhGGqAb+cj5//o9mUVRJGrfzZyEePW8/gaRK3Q1iqu8hkBXbWGIkGFsbc3DJdkWlkd+Y6fHGwIDAQAB 私钥:MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAK44UzCei5dYS55ObZCa5rmijwnt+s33oOhIO3DXU5ut+99Uq73UZyM+UX/KdR7KPA+7OaL5uQIgOzbBSfTDPcJTnajh7V2vMuIM6EYaoBv5yPn/+j2ZRVEkat/NnIR49bz+BpErdDWKq7yGQFdtYYiQYWxtzcMl2RaWR35jp8cbAgMBAAECgYA4ETJcjDl6PFUhnjXOertT9Ie591dmn5GuD0jp2LI0gLp1NgeLMOb8RZru2FX20bigi21SELHEiGDmDzBgz9B4x9lY8IIoB52FZdd+YgSVvXV/hA9Ikf1HClixC1DrixJ6/O/4e4r8uwdeTyVZvhVmf8Q37hfCRSKGCF5+plds0QJBAOltOgzTjF3iSjCjjXKprsaZZvgFaq+2/vmjzJvfDepBWU76MV+B5BB63n7C9S9jden+70qyCdATbLcezuEZCjkCQQC/EVzPNnsUre7u46bngTnkgVXcjcDler4BLBgDUCnJE06PDar48rcrEzK+0w3kCXN74ZzNFCt4A/1SKK9zh6vzAkBHfr39+bmPc+T3WtDTIue2SnwAUWBo62rTOXlM8JfJfTSGfRksQJOC/K8zMjF4z0TpY70VKszYn2p3+AazaUD5AkBNUSFVWJ6Fx7ygPs8Tb1+V8CBml5YvRnQM1WMCNDY0f/OSP92nz8//Rk2Kmq1MUebBgpKJClhswHCKBpy5C3WxAkB/prC/JNPP37P/G1+nALQpJ1kascODroWcS1x8BeLLHfCnSdYcI5uTLVzpBt/IfajEHCIDgW+yWJigqjf6DvjX