美文网首页
RSA加密方式

RSA加密方式

作者: MR崔先生 | 来源:发表于2020-03-03 17:50 被阅读0次

RSA加密方式

import java.security.Key;
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.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class RSAUtils {
    private static Log log = LogFactory.getLog(RSAUtils.class);
    private static final String KEYALGORITHM = "RSA";
    private static final String SIGNATUREALGORITHM = "MD5withRSA";
 
    private static final String PUBLICKEY = "RSAPublicKey";
    private static final String PRIVATEKEY = "RSAPrivateKey";
 
    //rsa私钥  或者可从配置文件读取。
    public static final String DECRYPTPRIVATEKEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAIMzJa4oZpQcPhRDTIaWnF4olSaeGt5oV0XFwoeeSK+FZ3lc4N34523tdfasgba";
 
    private RSAUtils(){super();}
    
    public static byte[] decryptBASE64(String key) {
        Base64 base64 = new Base64();
        return base64.decode(key);
    }
 
    public static String encryptBASE64(byte[] bytes) {
        Base64 base64 = new Base64();
        return base64.encodeToString(bytes);
    }
 
    /**
     *
     *
     * @param data
     *
     * @param privateKey
     *
     * @return
     * @throws Exception
     */
    public static String sign(byte[] data, String privateKey){
        try {
 
            byte[] keyBytes = decryptBASE64(privateKey);
 
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
 
            KeyFactory keyFactory = KeyFactory.getInstance(KEYALGORITHM);
 
            PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
 
            Signature signature = Signature.getInstance(SIGNATUREALGORITHM);
            signature.initSign(priKey);
            signature.update(data);
            return encryptBASE64(signature.sign());
        }catch (Exception e){
            log.error("RSAUtilsSignError");
            return "";
        }
    }
 
    /**
     *
     *
     * @param data
     *
     * @param publicKey
     *
     * @param sign
     *
     * @return
     * @throws Exception
     */
    public static boolean verify(byte[] data, String publicKey, String sign){
        try {
 
            byte[] keyBytes = decryptBASE64(publicKey);
 
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
 
            KeyFactory keyFactory = KeyFactory.getInstance(KEYALGORITHM);
 
            PublicKey pubKey = keyFactory.generatePublic(keySpec);
            Signature signature = Signature.getInstance(SIGNATUREALGORITHM);
            signature.initVerify(pubKey);
            signature.update(data);
 
            return signature.verify(decryptBASE64(sign));
        }catch (Exception e){
            log.error("RSAUtilsVerifySignError");
            return false;
        }
    }
 
    public static byte[] decryptByPrivateKey(byte[] data, String key){
        try {
 
            byte[] keyBytes = decryptBASE64(key);
 
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEYALGORITHM);
            Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
 
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return cipher.doFinal(data);
        }catch (Exception e){
            log.error("RSAUtilsPrivateKeyDecryptError");
            return new byte[0];
        }
    }
 
    /**
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPrivateKey(String data, String key){
        return decryptByPrivateKey(decryptBASE64(data), key);
    }
 
    /**
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPublicKey(byte[] data, String key){
        try {
 
            byte[] keyBytes = decryptBASE64(key);
 
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEYALGORITHM);
            Key publicKey = keyFactory.generatePublic(x509KeySpec);
 
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            return cipher.doFinal(data);
        }catch (Exception e){
            log.error("RSAUtilsPublicKeyDecryptError");
            return new byte[0];
        }
 
    }
 
    /**
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPublicKey(String data, String key) {
        try {
 
            byte[] keyBytes = decryptBASE64(key);
 
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEYALGORITHM);
            Key publicKey = keyFactory.generatePublic(x509KeySpec);
 
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return cipher.doFinal(data.getBytes());
        }catch (Exception e){
            log.error("RSAUtilsPublicKeyEncryptError");
            return new byte[0];
        }
    }
 
    /**
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPrivateKey(byte[] data, String key){
        try {
 
            byte[] keyBytes = decryptBASE64(key);
 
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEYALGORITHM);
            Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
 
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            return cipher.doFinal(data);
        }catch (Exception e){
            log.error("RSAUtilsPrivateKeyEncryptError");
            return new byte[0];
        }
    }
 
    /**
     *
     * @param keyMap
     * @return
     * @throws Exception
     */
    public static String getPrivateKey(Map<String, Key> keyMap){
        if(keyMap != null){
            Key key = keyMap.get(PRIVATEKEY);
            return encryptBASE64(key.getEncoded());
        }else{
            return "";
        }
    }
 
    /**
     *
     * @param keyMap
     * @return
     * @throws Exception
     */
    public static String getPublicKey(Map<String, Key> keyMap){
        if(keyMap != null){
            Key key = keyMap.get(PUBLICKEY);
            return encryptBASE64(key.getEncoded());
        }else {
            return "";
        }
    }
 
    /**
     *
     * @return
     * @throws Exception
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Map<String, Key> initKey(){
        try {
            KeyPairGenerator keyPairGen = KeyPairGenerator
                    .getInstance(KEYALGORITHM);
            keyPairGen.initialize(2048);
            KeyPair keyPair = keyPairGen.generateKeyPair();
            Map<String, Key> keyMap = new HashMap(2);
            keyMap.put(PUBLICKEY, keyPair.getPublic());
            keyMap.put(PRIVATEKEY, keyPair.getPrivate());
            return keyMap;
        } catch (NoSuchAlgorithmException e) {
            log.error("RSAUtilsInitKeyError");
            return null;
        }
    }
}

获取RSA密钥

import java.security.Key;
import java.util.Map;

public class RSA {
    private static Map<String,Key> map;
    static{
        loadProps();
    }
    synchronized static private void loadProps(){
        map = RSAUtils.initKey();
    }
    public static String getPrivateKey(){
        return RSAUtils.getPrivateKey(map);
    }
    public static String getPublicKey(){
        return RSAUtils.getPublicKey(map);
    }
}

加密

var encrypt = new JSEncrypt();
encrypt.setPublicKey(公钥);
//password为加密密码
var password = encrypt.encrypt(密码明文);
公钥获取方式  后台
公钥 = RSA.getPublicKey();

解密

byte[] decryptData = RSAUtils.decryptByPrivateKey(passWord,RSA.getPrivateKey());
passWord = new String(decryptData);

js库

[jsencrypt](https://github.com/travist/jsencrypt).min.js下载地址:

[github主页]([https://github.com/travist/jsencrypt])    

[官方网站]([http://travistidwell.com/jsencrypt/])
jq库:
<script src="http://code.jquery.com/jquery-1.8.3.min.js "></script>

### (注!jquery-2.0以上版本不再支持IE 6/7/8) 并不是最新的版本就最好的,而是根据您项目需求所适合的版本!


相关文章

  • RSA加密方式

    RSA加密方式 获取RSA密钥 加密 解密 js库

  • 项目加密 RSA+DES3加密方式

    rsa加密参考网址 rsa加密参考网址 des3加密支持中文加密 des加密参考网址 加密的方式为 先将数据进行D...

  • iOS-15 加密

    1iOS 常用加密方式讲解 - 简书 2iOS加密方式(RSA签名、加密、AES) - 简书

  • Android-rsa解密服务端给的加密过的内容,利用rsa公钥

    内容后台加密方式:Base64 encode加密 -> Rsa私钥加密, 给我公钥用来解密, 实现方式参考:PHP...

  • python3中Crypto的AES和RSA

    RSA加密一般使用RSA/ECB/PKCS1Padding(算法/工作模式/填充方式),AES加密一般使用AES/...

  • iOS-对称加密和(rsa)非对称加密

    说起rsa,大家自然就会说,非对称加密嘛。是的,rsa非对称加密算是安全级别非常高的加密方式,至少对于现在而言。这...

  • RSA加解密学习笔记

    RSA加解密简单说明: RSA是非对称加密方式,就是说加密解密不是同一个Key。私钥加密公钥解密,待加密的明文字节...

  • iOS 关于加密

    常见的iOS代码加密常用加密方式包括Base64加密、MD5加密、AES加密、RSA加密等。 Base64加密 B...

  • RSA加密填充方式

    RSA加密常用的填充方式有下面3种: 1.RSA_PKCS1_PADDING 填充模式,最常用的模式 要求: 输入...

  • 前后端参数加密

    一,常用类型加密方式 1,base64无秘钥加密2,base64秘钥加密3,AES 加密4,RSA加密 二,加密方...

网友评论

      本文标题:RSA加密方式

      本文链接:https://www.haomeiwen.com/subject/umzhlhtx.html