1 packagecn.com.gome.utils;2
3 importjava.io.FileReader;4 importjava.io.FileWriter;5 importjava.io.IOException;6 importjava.io.Reader;7 importjava.io.Writer;8 importjava.math.BigInteger;9 importjava.security.NoSuchAlgorithmException;10 importjava.security.SecureRandom;11 importjava.util.HashMap;12 importjava.util.Map;13
14 importorg.bouncycastle.asn1.ASN1Object;15 importorg.bouncycastle.asn1.pkcs.PrivateKeyInfo;16 importorg.bouncycastle.asn1.x509.SubjectPublicKeyInfo;17 importorg.bouncycastle.crypto.AsymmetricBlockCipher;18 importorg.bouncycastle.crypto.AsymmetricCipherKeyPair;19 importorg.bouncycastle.crypto.InvalidCipherTextException;20 importorg.bouncycastle.crypto.encodings.PKCS1Encoding;21 importorg.bouncycastle.crypto.engines.RSAEngine;22 importorg.bouncycastle.crypto.generators.RSAKeyPairGenerator;23 importorg.bouncycastle.crypto.params.AsymmetricKeyParameter;24 importorg.bouncycastle.crypto.params.RSAKeyGenerationParameters;25 importorg.bouncycastle.crypto.params.RSAKeyParameters;26 importorg.bouncycastle.crypto.util.PrivateKeyFactory;27 importorg.bouncycastle.crypto.util.PrivateKeyInfoFactory;28 importorg.bouncycastle.crypto.util.PublicKeyFactory;29 importorg.bouncycastle.crypto.util.SubjectPublicKeyInfoFactory;30 importorg.bouncycastle.util.encoders.Base64;31 importorg.bouncycastle.util.io.pem.PemObject;32 importorg.bouncycastle.util.io.pem.PemReader;33 importorg.bouncycastle.util.io.pem.PemWriter;34
35 importsun.misc.BASE64Encoder;36
37 /**
38 * sra加密39 *@author
40 *41 */
42 public classRSAUtils {43
44 /**
45 * 生成公钥和私钥46 *@throwsNoSuchAlgorithmException47 *48 */
49 public static Map getKeys(Boolean isGenerateFile) throwsNoSuchAlgorithmException{50 Map map = new HashMap();51 //生成参数配置
52 RSAKeyPairGenerator rsaKeyPairGenerator = newRSAKeyPairGenerator();53 //设置秘钥生成参数
54 SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");55 //secureRandom.setSeed(seed);
56 RSAKeyGenerationParameters rsaKeyGenerationParameters = new RSAKeyGenerationParameters(BigInteger.valueOf(65537), secureRandom, 1024, 16);57 rsaKeyPairGenerator.init(rsaKeyGenerationParameters);58
59 //生成秘钥
60 AsymmetricCipherKeyPair keyPair =rsaKeyPairGenerator.generateKeyPair();61 RSAKeyParameters publicKey = (RSAKeyParameters) keyPair.getPublic();//公钥
62 RSAKeyParameters privateKey = (RSAKeyParameters) keyPair.getPrivate();//私钥63
64 //使用x509证书进行处理
65 SubjectPublicKeyInfo subjectPublicKeyInfo;66 PrivateKeyInfo privateKeyInfo;67 try{68 subjectPublicKeyInfo =SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(publicKey);69 privateKeyInfo =PrivateKeyInfoFactory.createPrivateKeyInfo(privateKey);70
71 //pem格式处理
72 ASN1Object asn1ObjectPublic =subjectPublicKeyInfo.toASN1Primitive();73 byte[] publicInfoByte = asn1ObjectPublic.getEncoded("DER");74
75 ASN1Object asn1ObjectPrivate =privateKeyInfo.toASN1Primitive();76 byte[] privateInfoByte = asn1ObjectPrivate.getEncoded("DER");77
78 //写入map中
79 map.put("public", new String((newBASE64Encoder()).encode(publicInfoByte)));80 map.put("private", new String((newBASE64Encoder()).encode(privateInfoByte)));81 //map.put("public", new String(Base64.decode(publicInfoByte)));82 //map.put("private", new String(Base64.decode(privateInfoByte)));83
84 //生成文件
85 if(isGenerateFile){86 //写入文件private
87 Writer r = new FileWriter("private.pem");88 PemWriter pemWriter = newPemWriter(r);89 pemWriter.writeObject(new PemObject("PRIVATE KEY",Base64.encode(privateInfoByte)));90 //写入硬盘
91 pemWriter.flush();92 pemWriter.close();93 //public
94 Writer rp = new FileWriter("public.pem");95 PemWriter pemWriterp = newPemWriter(rp);96 pemWriterp.writeObject(new PemObject("PUBLIC KEY",Base64.encode(publicInfoByte)));97 //写入硬盘
98 pemWriterp.flush();99 pemWriterp.close();100 }101 } catch(IOException e) {102 //TODO Auto-generated catch block
103 e.printStackTrace();104 }105 returnmap;106 }107
108 /**
109 * 获取pem格式110 *@return
111 *@throwsNoSuchAlgorithmException112 */
113 public static Map getKeysPem(Map map) throwsNoSuchAlgorithmException{114
115 if (map==null){116 map = getKeys(false);117 }118
119 StringBuffer str_Public_Key = newStringBuffer();120 str_Public_Key.append("-----BEGIN PUBLIC KEY-----");121 str_Public_Key.append("\n");122 str_Public_Key.append(map.get("public"));123 str_Public_Key.append("\n");124 str_Public_Key.append("-----END PUBLIC KEY-----");125 map.put("public", str_Public_Key.toString());126
127 StringBuffer str_Private_Key = newStringBuffer();128 str_Private_Key.append("-----BEGIN PRIVATE KEY-----");129 str_Private_Key.append("\n");130 str_Private_Key.append(map.get("private"));131 str_Private_Key.append("\n");132 str_Private_Key.append("-----END PRIVATE KEY-----");133 map.put("private", str_Private_Key.toString());134
135 returnmap;136 }137
138
139 /**
140 * 解密141 *@return
142 */
143 public static byte[] decryptPrivateKey(String privateKey,byte[] data){144
145 //获取原始数据并进行64为解码
146 byte[] bytes = new byte[0];147
148 AsymmetricBlockCipher engine = new PKCS1Encoding(newRSAEngine());149 Reader r = null;150 try{151 if(privateKey==null ||privateKey==""){152 r = new FileReader("private.pem");153 //获取秘钥
154 PemReader pemReader = new PemReader(r); //载入私钥
155 PemObject readObject =pemReader.readPemObject();156 //生成key
157 AsymmetricKeyParameter priKey =PrivateKeyFactory.createKey(Base64.decode(readObject.getContent()));158 engine.init(false, priKey);159 //进行
160 pemReader.close();161 }else{162 //生成key
163 AsymmetricKeyParameter priKey =PrivateKeyFactory.createKey(Base64.decode(privateKey.getBytes()));164 engine.init(false, priKey);165 }166 //解密
167 bytes = engine.processBlock(data, 0, data.length);168
169 } catch (InvalidCipherTextException |IOException e) {170 e.printStackTrace();171 }finally{172 if(r!=null){173 try{174 r.close();175 } catch(IOException e) {176 e.printStackTrace();177 }178 }179 }180 returnbytes;181 }182
183 /**
184 * 加密185 *@parampublicKey186 *@paramdata187 *@return
188 */
189 public static byte[] encryptByPublicKey(String publicKey,byte[] data){190 //获取原始数据并进行64为解码
191 byte[] bytes = new byte[0];192
193 AsymmetricBlockCipher engine = new PKCS1Encoding(newRSAEngine());194 Reader r = null;195 try{196 if(publicKey==null || publicKey==""){197 r = new FileReader("public.pem");198 //获取秘钥
199 PemReader pemReader = new PemReader(r); //载入私钥
200 PemObject readObject =pemReader.readPemObject();201 AsymmetricKeyParameter pubKey =PublicKeyFactory.createKey(Base64.decode(readObject.getContent()));202 engine.init(true, pubKey);203
204 //关闭pem读取流
205 pemReader.close();206 }else{207 AsymmetricKeyParameter pubKey =PublicKeyFactory.createKey(Base64.decode(publicKey.getBytes()));208 engine.init(true, pubKey);209 }210 //解密
211 bytes = engine.processBlock(data, 0, data.length);212
213 } catch (InvalidCipherTextException |IOException e) {214 e.printStackTrace();215 }finally{216 if(r!=null){217 try{218 r.close();219 } catch(IOException e) {220 //TODO Auto-generated catch block
221 e.printStackTrace();222 }223 }224 }225 returnbytes;226 }227
228 }