RSA加密算法

AVAEE项目中很多时候都需要对核心数据进行加密传输,采用非对称加密算法在前段对数据进行加密,在服务端进行解密是一个不错的方式。而常用的实现是采用RSA非对称加密方法。具体步骤为:

1、在服务端用密码种子生成密钥对,保存密码种子(一个特定的密码种子,生成特定的密钥对,密码种子确定,密钥对确定)或者直接保存私钥

2、把公钥传到页面

3、页面用JS根据公钥把需要加密的数据进行加密,把加密后的数据传回服务端

4、服务端取出保存的密码种子或者直接保存的私钥,采用私钥对加密字符串进行解密,得到明文

 

package Security1;
 
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import javax.crypto.Cipher;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
 
/*
 * 公钥(N,e)
 * 私钥(N,d)
 */
public class RSAdemo {
    
            private static HashMap<String,String> map = new HashMap<String,String>();
            public static void main(String[] args) throws InvalidKeySpecException {
                
                 try {
                     //创建RSA加密
                    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
                    //密钥位数
                    keyPairGen.initialize(1024);
                    // 动态生成密钥对,这是当前最耗时的操作,一般要2s以上。
                    KeyPair key = keyPairGen.generateKeyPair();
                    //公钥
                    PublicKey publicKey =  key.getPublic();
                    
                    
                    //密钥
                    PrivateKey privateKey = key.getPrivate();
                    
                    printPrivateKey(privateKey);
                    printPublicKey(publicKey);
 
 
                    // 公钥比特编码
//                    byte[] privateData = privateKey.getEncoded();  //对应着getPrivateKey()方法
                    //密钥比特编码
//                    byte[] publicData = publicKey.getEncoded();   //对应着getPublicKey()方法
                    
                    String message ="吕双,我的女朋友";
                    String inputStr = encrypt(message, new String(new BASE64Encoder().encodeBuffer(publicKey.getEncoded())));
                    System.out.println(inputStr);
                    System.out.println(decrypt(inputStr, new String(new BASE64Encoder().encodeBuffer(privateKey.getEncoded()))));
                    
                                    
                    
                } catch (NoSuchAlgorithmException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
             // 通过公钥byte[]将公钥还原,适用于RSA算法
            public static PublicKey getPublicKey(byte[] keyBytes) throws NoSuchAlgorithmException,InvalidKeySpecException {
                X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                PublicKey publicKey = keyFactory.generatePublic(keySpec);
                return publicKey;
             }
            
            //通过私钥byte[]将密钥还原,适用于RSA算法
            public static PrivateKey getPrivateKey(byte[] keyBytes) throws NoSuchAlgorithmException,InvalidKeySpecException{
                PKCS8EncodedKeySpec keySpec = new  PKCS8EncodedKeySpec(keyBytes);
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
                return privateKey;
            }
            
            //打印公钥信息
            public static void printPublicKey(PublicKey publicKey) {
                RSAPublicKey key = (RSAPublicKey)publicKey;                
                map.put("N", key.getModulus().toString());                
                map.put("E", key.getPublicExponent().toString());
            }
            
            //获取私钥信息
            public static void printPrivateKey(PrivateKey privateKey) {
                RSAPrivateKey key = (RSAPrivateKey)privateKey;
                map.put("D", key.getPrivateExponent().toString());
            }
            
            // 使用N、E值还原公钥
            public static PublicKey getPublicKeyByN_E(String N,String E) throws NoSuchAlgorithmException, InvalidKeySpecException {
                BigInteger bigN = new BigInteger(N);
                BigInteger bigE = new BigInteger(E);
                RSAPublicKeySpec spec = new RSAPublicKeySpec(bigN, bigE);
                KeyFactory factory = KeyFactory.getInstance("RSA");
                return factory.generatePublic(spec);
            }
            // 使用N、D值还原公钥
            public static PrivateKey getPrivateKeyByN_D(String N,String D) throws NoSuchAlgorithmException, InvalidKeySpecException {
                BigInteger bigN = new BigInteger(N);
                BigInteger bigD = new BigInteger(D);
                RSAPrivateKeySpec spec = new RSAPrivateKeySpec(bigN, bigD);
                KeyFactory factory = KeyFactory.getInstance("RSA");
                return factory.generatePrivate(spec);
            }
            //加密
            /*
             * 公钥加密
             * @Param str : 加密字符串
             * @Param publicKey : 公钥
             * return : 密文
             */
            public static String encrypt(String str , String publicKey) throws Exception {
                //base64编码的公钥
                byte[] decoded = new BASE64Decoder().decodeBuffer(publicKey);
                X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decoded);
                RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(keySpec);
                
                //RSA加密
                Cipher cipher = Cipher.getInstance("RSA");
                cipher.init(Cipher.ENCRYPT_MODE, pubKey);
                String outStr = new BASE64Encoder().encode(cipher.doFinal(str.getBytes("UTF-8")));
                return outStr;
                
            }
            
            /*
             * RSA私钥解密
             * @param str :加密后的字符串
             * @param privateKey : 解密后的字符串
             */
            public static String decrypt(String str,String privateKey) throws Exception{
                
                //64位解码加密后的字符串
                byte[] inputStr = new BASE64Decoder().decodeBuffer(new String(str.getBytes("utf-8"),"utf-8"));
                //base64解码的私钥
                byte[] decode = new BASE64Decoder().decodeBuffer(privateKey);
                PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decode);
                RSAPrivateKey priKey = (RSAPrivateKey)KeyFactory.getInstance("RSA").generatePrivate(keySpec);
                Cipher cipher = Cipher.getInstance("RSA");
                cipher.init(Cipher.DECRYPT_MODE, priKey);
                String outStr = new String(cipher.doFinal(inputStr));
                return outStr;
            }
            
}    

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值