特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过。如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/mao2080/
1、生成公钥私钥对
1 package com.mao.common.util; 2 3 import java.security.KeyPair; 4 import java.security.KeyPairGenerator; 5 import java.security.interfaces.RSAPrivateKey; 6 import java.security.interfaces.RSAPublicKey; 7 8 import org.apache.tomcat.util.codec.binary.Base64; 9 10 /** 11 * 12 * 描述:密钥生成器 13 * @author mao2080@sina.com 14 * @created 2017年4月20日 下午8:32:20 15 * @since 16 */ 17 public class Generator { 18 19 public static final String ALGORITHM_RSA = "RSA"; 20 21 public static void main(String[] args) throws Exception { 22 KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(ALGORITHM_RSA); 23 keyPairGen.initialize(1024); 24 KeyPair keyPair = keyPairGen.generateKeyPair(); 25 RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic(); 26 byte[] keyBs = rsaPublicKey.getEncoded(); 27 String publicKey = encodeBase64(keyBs); 28 System.out.println("生成的公钥: " + publicKey); 29 RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate(); 30 keyBs = rsaPrivateKey.getEncoded(); 31 String privateKey = encodeBase64(keyBs); 32 System.out.println("生成的私钥: " + privateKey); 33 } 34 35 /** 36 * 37 * 描述:byte数组转String 38 * @author mao2080@sina.com 39 * @created 2017年4月9日 下午8:43:05 40 * @since 41 * @param source 42 * @return 43 * @throws Exception 44 */ 45 public static String encodeBase64(byte[] source) throws Exception { 46 return new String(Base64.encodeBase64(source), "UTF-8"); 47 } 48 49 /** 50 * 51 * 描述:String转byte数组 52 * @author mao2080@sina.com 53 * @created 2017年4月9日 下午8:42:59 54 * @since 55 * @param target 56 * @return 57 * @throws Exception 58 */ 59 public static byte[] decodeBase64(String target) throws Exception { 60 return Base64.decodeBase64(target.getBytes("UTF-8")); 61 } 62 63 }
运行结果:
生成的公钥: MIGfMA0GCSqGS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; 2 3 import java.security.KeyFactory; 4 import java.security.PrivateKey; 5 import java.security.PublicKey; 6 import java.security.spec.PKCS8EncodedKeySpec; 7 import java.security.spec.X509EncodedKeySpec; 8 9 import javax.crypto.Cipher; 10 11 import org.apache.tomcat.util.codec.binary.Base64; 12 13 /** 14 * 15 * 描述:安全工具类 16 * @author mao2080@sina.com 17 * @created 2017年4月20日 下午8:32:42 18 * @since 19 */ 20 public final class SecurityUtil { 21 22 private static final String ALGORITHM_RSA = "RSA"; 23 24 /**RSA-charset*/ 25 private static final String RSA_CHARSET = "UTF-8"; 26 27 /** 28 * 29 * 描述:将字符串通过RSA算法公钥加密 30 * @author mao2080@sina.com 31 * @created 2017年4月9日 上午09:18:51 32 * @since 33 * @param content 需要加密的内容 34 * @param pubKey 公钥 35 * @return 加密后字符串 36 * @throws Exception 37 */ 38 private static String EncryptByRSAPubKey(String content, String pubKey) throws Exception { 39 try { 40 PublicKey publicKey = SecurityUtil.getRSAPubKey(pubKey); 41 Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm()); 42 cipher.init(Cipher.ENCRYPT_MODE, publicKey); 43 cipher.update(content.getBytes(SecurityUtil.RSA_CHARSET)); 44 return SecurityUtil.encodeBase64(cipher.doFinal()); 45 } catch (Exception e) { 46 e.printStackTrace(); 47 throw new Exception(); 48 } 49 } 50 51 /** 52 * 53 * 描述:将字符串通过RSA算法公钥解密 54 * @author mao2080@sina.com 55 * @created 2017年4月9日 上午09:18:51 56 * @since 57 * @param content 需要解密的内容 58 * @param pubKey 公钥 59 * @return 解密后字符串 60 * @throws Exception 61 */ 62 private static String DecryptByRSAPubKey(String content, String pubKey) throws Exception { 63 try { 64 PublicKey publicKey = SecurityUtil.getRSAPubKey(pubKey); 65 Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm()); 66 cipher.init(Cipher.DECRYPT_MODE, publicKey); 67 cipher.update(SecurityUtil.decodeBase64(content)); 68 return new String(cipher.doFinal(), RSA_CHARSET); 69 } catch (Exception e) { 70 e.printStackTrace(); 71 throw new Exception(); 72 } 73 } 74 75 /** 76 * 77 * 描述:将字符串通过RSA算法私钥加密 78 * @author mao2080@sina.com 79 * @created 2017年4月9日 上午09:18:51 80 * @since 81 * @param content 需要加密的内容 82 * @param priKey 私钥 83 * @return 加密后字符串 84 * @throws Exception 85 */ 86 public static String EncryptByRSAPriKey(String content, String priKey) throws Exception { 87 try { 88 PrivateKey privateKey = SecurityUtil.getRSAPriKey(priKey); 89 Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm()); 90 cipher.init(Cipher.ENCRYPT_MODE, privateKey); 91 cipher.update(content.getBytes(SecurityUtil.RSA_CHARSET)); 92 return SecurityUtil.encodeBase64(cipher.doFinal()); 93 } catch (Exception e) { 94 e.printStackTrace(); 95 throw new Exception(); 96 } 97 } 98 99 /** 100 * 101 * 描述:将字符串通过RSA算法私钥解密 102 * @author mao2080@sina.com 103 * @created 2017年4月9日 上午09:18:51 104 * @since 105 * @param content 需要解密的内容 106 * @param priKey 私钥 107 * @return 解密后字符串 108 * @throws Exception 109 */ 110 public static String DecryptByRSAPriKey(String content, String priKey) throws Exception { 111 try { 112 PrivateKey privateKey = SecurityUtil.getRSAPriKey(priKey); 113 Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm()); 114 cipher.init(Cipher.DECRYPT_MODE, privateKey); 115 cipher.update(SecurityUtil.decodeBase64(content)); 116 return new String(cipher.doFinal(), SecurityUtil.RSA_CHARSET); 117 } catch (Exception e) { 118 e.printStackTrace(); 119 throw new Exception(); 120 } 121 } 122 123 /** 124 * 125 * 描述:获取RSA公钥 126 * @author mao2080@sina.com 127 * @created 2017年4月9日 上午09:18:51 128 * @since 129 * @param priKey 私钥 130 * @return PublicKey 131 * @throws Exception 132 */ 133 private static PublicKey getRSAPubKey(String pubKey) throws Exception { 134 try { 135 X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(SecurityUtil.decodeBase64(pubKey)); 136 KeyFactory keyFactory = KeyFactory.getInstance(SecurityUtil.ALGORITHM_RSA); 137 return keyFactory.generatePublic(publicKeySpec); 138 } catch (Exception e) { 139 e.printStackTrace(); 140 throw new Exception(); 141 } 142 } 143 144 /** 145 * 146 * 描述:获取RSA私钥 147 * @author mao2080@sina.com 148 * @created 2017年4月9日 上午09:18:51 149 * @since 150 * @param priKey 私钥 151 * @return PrivateKey 152 * @throws Exception 153 */ 154 private static PrivateKey getRSAPriKey(String priKey) throws Exception { 155 try { 156 PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(SecurityUtil.decodeBase64(priKey)); 157 KeyFactory keyFactory = KeyFactory.getInstance(SecurityUtil.ALGORITHM_RSA); 158 return keyFactory.generatePrivate(privateKeySpec); 159 } catch (Exception e) { 160 e.printStackTrace(); 161 throw new Exception(); 162 } 163 } 164 165 /** 166 * base64编码 167 * @param source 168 * @return 169 * @throws Exception 170 */ 171 public static String encodeBase64(byte[] source) throws Exception { 172 return new String(Base64.encodeBase64(source), "UTF-8"); 173 } 174 175 /** 176 * Base64解码 177 * @param target 178 * @return 179 * @throws Exception 180 */ 181 public static byte[] decodeBase64(String target) throws Exception { 182 return Base64.decodeBase64(target.getBytes("UTF-8")); 183 } 184 185 public static void main(String[] args) throws Exception { 186 String pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDHj1kf4EV0zCVdleIq/3pSm+tV0xuDGaXDzDyjVhDmrSptFv3MkBRY73qxbs/ZHGsVAwsY1kvh5qrFLdUesGMw92PgWwSXrNfBxYBLECweG0iIe8vTtvo824KdrJK3/1jPSXMJ0jYRaWXGr0qtEv5ak81kF/pDMiDG86wLKnq1jQIDAQAB"; 187 String priKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMePWR/gRXTMJV2V4ir/elKb61XTG4MZpcPMPKNWEOatKm0W/cyQFFjverFuz9kcaxUDCxjWS+HmqsUt1R6wYzD3Y+BbBJes18HFgEsQLB4bSIh7y9O2+jzbgp2skrf/WM9JcwnSNhFpZcavSq0S/lqTzWQX+kMyIMbzrAsqerWNAgMBAAECgYAo33xiof232WRB0cQcCG2WY+cEkhONe4BPJRK6ZZNam9cXtuDOuCfiu1IG62pYzpBEInZwZNvv7d3GOwfunDQEY1Zt6TC6D8E59aRGE+2HofVwA47X3ulXz8EsV9ZXYd/Eq/P0tpDci6DtWC/Gh0UZSgcUhwM6DXwa9ctMo3VxoQJBAPvHQ0SbapSOxqALc9WNrG/dq2wvQaecCnuVqhrl7ZuIeGronQMvsxFHMBp2OPcK/64jESZ9LoAoPnwlYuIs33kCQQDK5/E4YnBjzb6w//l1e1dhIbRwMZHkn8VNMorYjTQemX9m7gsJeAPSBF11lo1XGWR84M0nPMnrnyeG8zl68B21AkEA81Cf+19OYn6QCP7IVGpzaDAKh6QriLTNlJ0QJKprM1FxPa/KfNfN7zaikBAMAQIKENkmq9Fx7Lv3lrXyl6zR0QJAeSLb+kOawZrVm6pWbfMDCbQrm0ecyBcynZHtHre+Q/5z9ylqYW7LKRj+CvOk0jkQqxUypZg/HHJaENEooeK0eQJAVckJuNXO+XQsMo1J+dkthmAbJY1u8ylDW6V/ofpvCIkZwWagbDhqrb2lt0Mc/JaL/+5HtM3boMRXGcleTDFWZQ=="; 188 String content = "12345678"; 189 String s = EncryptByRSAPubKey(content, pubKey); 190 System.out.println("公钥加密后:"+s); 191 System.out.println("私钥解密后:"+DecryptByRSAPriKey(s, priKey)); 192 content = "12345678"; 193 s = EncryptByRSAPriKey(content, priKey); 194 System.out.println("私钥加密后:"+s); 195 System.out.println("公钥解密后:"+DecryptByRSAPubKey(s, pubKey)); 196 } 197 198 }
运行结果:
公钥加密后:hTsS0vrBpaQgp+T1dyoTQ8jJKt6qAmE5Np3URgYjRuA0vrib9fElFz8BFX5NHOlcmDMZKuudulfehQ3P43DNA0k9dAMStIuofQIA70fY5GQxNjLTu0S7/J510wYPAtopMDqO9eriVg39R3KzJUPwgMKQGELBCOWstK9nO1F6z0w= 私钥解密后:12345678 私钥加密后:xaKKEf6eC80Zh3MbrQA13hbpIv57IFvW2N1oMshojZYqGNTbGQvyZcHOkVzAsVlZJDyexDKdD82kP8lfZ/729BC/7EGwtXlND8w68pfOsSDYtknRLrXpflNU7C+EqzUQBUsruj+tUc7m050eZmJw7u6DF3lIIviIICWV/O1OiDw= 公钥解密后:12345678