其他都是废话,直接上代码,我们不生产代码,我们只是代码的搬运工。

java版本RSA算法:

  1 package cn.com.gome.utils;
  2 
  3 import java.io.FileReader;
  4 import java.io.FileWriter;
  5 import java.io.IOException;
  6 import java.io.Reader;
  7 import java.io.Writer;
  8 import java.math.BigInteger;
  9 import java.security.NoSuchAlgorithmException;
 10 import java.security.SecureRandom;
 11 import java.util.HashMap;
 12 import java.util.Map;
 13 
 14 import org.bouncycastle.asn1.ASN1Object;
 15 import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
 16 import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
 17 import org.bouncycastle.crypto.AsymmetricBlockCipher;
 18 import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
 19 import org.bouncycastle.crypto.InvalidCipherTextException;
 20 import org.bouncycastle.crypto.encodings.PKCS1Encoding;
 21 import org.bouncycastle.crypto.engines.RSAEngine;
 22 import org.bouncycastle.crypto.generators.RSAKeyPairGenerator;
 23 import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
 24 import org.bouncycastle.crypto.params.RSAKeyGenerationParameters;
 25 import org.bouncycastle.crypto.params.RSAKeyParameters;
 26 import org.bouncycastle.crypto.util.PrivateKeyFactory;
 27 import org.bouncycastle.crypto.util.PrivateKeyInfoFactory;
 28 import org.bouncycastle.crypto.util.PublicKeyFactory;
 29 import org.bouncycastle.crypto.util.SubjectPublicKeyInfoFactory;
 30 import org.bouncycastle.util.encoders.Base64;
 31 import org.bouncycastle.util.io.pem.PemObject;
 32 import org.bouncycastle.util.io.pem.PemReader;
 33 import org.bouncycastle.util.io.pem.PemWriter;
 34 
 35 import sun.misc.BASE64Encoder;
 36 
 37 /**
 38  * sra加密
 39  * @author
 40  *
 41  */
 42 public class RSAUtils {
 43 
 44     /**
 45      * 生成公钥和私钥
 46      * @throws NoSuchAlgorithmException 
 47      *
 48      */
 49     public static Map<String,String> getKeys(Boolean isGenerateFile) throws NoSuchAlgorithmException{
 50         Map<String,String> map = new HashMap<String,String>();
 51         //生成参数配置
 52         RSAKeyPairGenerator rsaKeyPairGenerator = new RSAKeyPairGenerator();
 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((new BASE64Encoder()).encode(publicInfoByte)));
 80             map.put("private", new String((new BASE64Encoder()).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 = new PemWriter(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 = new PemWriter(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         return map;
106     }
107     
108     /**
109      * 获取pem格式
110      * @return
111      * @throws NoSuchAlgorithmException
112      */
113     public static Map<String,String> getKeysPem(Map<String,String> map) throws NoSuchAlgorithmException{
114         
115         if (map==null){
116             map = getKeys(false);
117         }
118         
119         StringBuffer str_Public_Key = new StringBuffer();
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 = new StringBuffer();
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         return map;
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(new RSAEngine());
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         return bytes;
181     }
182     
183     /**
184      * 加密
185      * @param publicKey
186      * @param data
187      * @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(new RSAEngine());
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         return bytes;
226     }
227     
228 }
View Code

相关文章:

  • 2022-12-23
  • 2021-05-29
  • 2021-09-25
  • 2021-06-20
  • 2021-12-07
  • 2021-07-27
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-03
  • 2022-12-23
  • 2021-06-18
相关资源
相似解决方案