package com.casic.missiles.util; import org.apache.commons.codec.binary.Base64; import javax.crypto.Cipher; import java.security.KeyFactory; import java.security.interfaces.RSAPublicKey; import java.security.spec.X509EncodedKeySpec; /** * */ /** * <p> * RSA公钥/私钥/签名工具包 * </p> * <p> * 罗纳德·李维斯特(Ron [R]ivest)、阿迪·萨莫尔(Adi [S]hamir)和伦纳德·阿德曼(Leonard [A]dleman) * </p> * <p> * 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式<br/> * 由于非对称加密速度极其缓慢,一般文件不使用它来加密而是使用对称加密,<br/> * 非对称加密算法可以用来对对称加密的密钥加密,这样保证密钥的安全也就保证了数据的安全 * </p> * * @author LWH * @date 2018-10-29 */ public class RSATestUtils { public static String RSAPrivateKey = "RSAPrivateKey"; public static String RSAPublicKey = "RSAPublicKey"; public static void main(String[] args) throws Exception { //加密字符串 long salt = System.currentTimeMillis(); String timestamp = String.valueOf(salt); String message = "test-" + timestamp; String public_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCe6fr64/YNoKNEsA85WCsIuEL7RQIUxsveyYyGHF3f+JatpAiV2Xp5e/DK/73dWJ9xnEFzmeHFfOrs1czOolnYdLpboORZRsEI6zX+xq37EmFG631CmgQcOxw+rb1ipFPBPxC9jdBm46q2tp3hm9IChebttfKCIAoq9j0HFh1/CwIDAQAB"; String messageEn = encrypt(message, public_key); System.out.println(message + "\t加密后的字符串为:" + messageEn); } /** * RSA公钥加密 * * @param str 加密字符串 * @param publicKey 公钥 * @return 密文 * @throws Exception 加密过程中的异常信息 */ public static String encrypt(String str, String publicKey) throws Exception { //base64编码的公钥 byte[] decoded = Base64.decodeBase64(publicKey); RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded)); //RSA加密 Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, pubKey); String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8"))); return outStr; } }