package aisin.text;  
  
import com.google.common.collect.Maps;  
import sun.misc.BASE64Decoder;  
import sun.misc.BASE64Encoder;  
  
import javax.crypto.Cipher;

import java.io.UnsupportedEncodingException;
import java.security.*;  
import java.security.interfaces.RSAPrivateKey;  
import java.security.interfaces.RSAPublicKey;  
import java.security.spec.PKCS8EncodedKeySpec;  
import java.security.spec.X509EncodedKeySpec;  
import java.util.Map;  
  
/** 
 * Created by xiang.li on 2015/3/3. 
 * RSA 加解密工具类 
 */  
public class test {  
    /** 
     * 定义加密方式 
     */  
    private final static String KEY_RSA = "RSA";  
    /** 
     * 定义签名算法 
     */  
    private final static String KEY_RSA_SIGNATURE = "MD5withRSA";  
    /** 
     * 定义公钥算法 
     */  
    private final static String KEY_RSA_PUBLICKEY = "RSAPublicKey";  
    /** 
     * 定义私钥算法 
     */  
    private final static String KEY_RSA_PRIVATEKEY = "RSAPrivateKey";  
  
    /** 
     * 初始化密钥 
     * @return 
     */  
    public static Map<String, Object> init() {  
        Map<String, Object> map = null;  
        try {  
            KeyPairGenerator generator = KeyPairGenerator.getInstance(KEY_RSA);  
            generator.initialize(1024);  
            KeyPair keyPair = generator.generateKeyPair();  
            // 公钥  
            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  
            // 私钥  
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();  
            // 将密钥封装为map  
            map = Maps.newHashMap();  
            map.put(KEY_RSA_PUBLICKEY, publicKey);  
            map.put(KEY_RSA_PRIVATEKEY, privateKey);  
        } catch (NoSuchAlgorithmException e) {  
            e.printStackTrace();  
        }  
        return map;  
    }  
  
    /** 
     * 用私钥对信息生成数字签名 
     * @param data 加密数据 
     * @param privateKey 私钥 
     * @return 
     */  
    public static String sign(byte[] data, String privateKey) {  
        String str = "";  
        try {  
            // 解密由base64编码的私钥  
            byte[] bytes = decryptBase64(privateKey);  
            // 构造PKCS8EncodedKeySpec对象  
            PKCS8EncodedKeySpec pkcs = new PKCS8EncodedKeySpec(bytes);  
            // 指定的加密算法  
            KeyFactory factory = KeyFactory.getInstance(KEY_RSA);  
            // 取私钥对象  
            PrivateKey key = factory.generatePrivate(pkcs);  
            // 用私钥对信息生成数字签名  
            Signature signature = Signature.getInstance(KEY_RSA_SIGNATURE);  
            signature.initSign(key);  
            signature.update(data);  
            str = encryptBase64(signature.sign());  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return str;  
    }  
  
    /** 
     * 校验数字签名 
     * @param data 加密数据 
     * @param publicKey 公钥 
     * @param sign 数字签名 
     * @return 校验成功返回true,失败返回false 
     */  
    public static boolean verify(byte[] data, String publicKey, String sign) {  
        boolean flag = false;  
        try {  
            // 解密由base64编码的公钥  
            byte[] bytes = decryptBase64(publicKey);  
            // 构造X509EncodedKeySpec对象  
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);  
            // 指定的加密算法  
            KeyFactory factory = KeyFactory.getInstance(KEY_RSA);  
            // 取公钥对象  
            PublicKey key = factory.generatePublic(keySpec);  
            // 用公钥验证数字签名  
            Signature signature = Signature.getInstance(KEY_RSA_SIGNATURE);  
            signature.initVerify(key);  
            signature.update(data);  
            flag = signature.verify(decryptBase64(sign));  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return flag;  
    }  
  
    /** 
     * 私钥解密 
     * @param data 加密数据 
     * @param key 私钥 
     * @return 
     */  
    public static byte[] decryptByPrivateKey(byte[] data, String key) {  
        byte[] result = null;  
        try {  
            // 对私钥解密  
            byte[] bytes = decryptBase64(key);  
            // 取得私钥  
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);  
            KeyFactory factory = KeyFactory.getInstance(KEY_RSA);  
            PrivateKey privateKey = factory.generatePrivate(keySpec);  
            // 对数据解密  
            Cipher cipher = Cipher.getInstance(factory.getAlgorithm());  
            cipher.init(Cipher.DECRYPT_MODE, privateKey);  
            result = cipher.doFinal(data);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return result;  
    }  
  
    /** 
     * 私钥解密 
     * @param data 加密数据 
     * @param key 公钥 
     * @return 
     */  
    public static byte[] decryptByPublicKey(byte[] data, String key) {  
        byte[] result = null;  
        try {  
            // 对公钥解密  
            byte[] bytes = decryptBase64(key);  
            // 取得公钥  
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);  
            KeyFactory factory = KeyFactory.getInstance(KEY_RSA);  
            PublicKey publicKey = factory.generatePublic(keySpec);  
            // 对数据解密  
            Cipher cipher = Cipher.getInstance(factory.getAlgorithm());  
            cipher.init(Cipher.DECRYPT_MODE, publicKey);  
            result = cipher.doFinal(data);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return result;  
    }  
  
    /** 
     * 公钥加密 
     * @param data 待加密数据 
     * @param key 公钥 
     * @return 
     */  
    public static byte[] encryptByPublicKey(byte[] data, String key) {  
        byte[] result = null;  
        try {  
            byte[] bytes = decryptBase64(key);  
            // 取得公钥  
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);  
            KeyFactory factory = KeyFactory.getInstance(KEY_RSA);  
            PublicKey publicKey = factory.generatePublic(keySpec);  
            // 对数据加密  
            Cipher cipher = Cipher.getInstance(factory.getAlgorithm());  
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);  
            result = cipher.doFinal(data);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return result;  
    }  
  
    /** 
     * 私钥加密 
     * @param data 待加密数据 
     * @param key 私钥 
     * @return 
     */  
    public static byte[] encryptByPrivateKey(byte[] data, String key) {  
        byte[] result = null;  
        try {  
            byte[] bytes = decryptBase64(key);  
            // 取得私钥  
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);  
            KeyFactory factory = KeyFactory.getInstance(KEY_RSA);  
            PrivateKey privateKey = factory.generatePrivate(keySpec);  
            // 对数据加密  
            Cipher cipher = Cipher.getInstance(factory.getAlgorithm());  
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);  
            result = cipher.doFinal(data);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return result;  
    }  
  
    /** 
     * 获取公钥 
     * @param map 
     * @return 
     */  
    public static String getPublicKey(Map<String, Object> map) {  
        String str = "";  
        try {  
            Key key = (Key) map.get(KEY_RSA_PUBLICKEY);  
            str = encryptBase64(key.getEncoded());  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return str;  
    }  
  
    /** 
     * 获取私钥 
     * @param map 
     * @return 
     */  
    public static String getPrivateKey(Map<String, Object> map) {  
        String str = "";  
        try {  
            Key key = (Key) map.get(KEY_RSA_PRIVATEKEY);  
            str = encryptBase64(key.getEncoded());  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return str;  
    }  
  
    /** 
     * BASE64 解密 
     * @param key 需要解密的字符串 
     * @return 字节数组 
     * @throws Exception 
     */  
    public static byte[] decryptBase64(String key) throws Exception {  
        return (new BASE64Decoder()).decodeBuffer(key);  
    }  
  
    /** 
     * BASE64 加密 
     * @param key 需要加密的字节数组 
     * @return 字符串 
     * @throws Exception 
     */  
    public static String encryptBase64(byte[] key) throws Exception {  
        return (new BASE64Encoder()).encodeBuffer(key);  
    }  
  
    /** 
     * 测试方法 
     * @param args 
     * @throws UnsupportedEncodingException 
     */  
    public static void main(String[] args) throws UnsupportedEncodingException {  
        String privateKey = "";  
        String publicKey = "";  
        // 生成公钥私钥  
        Map<String, Object> map = init();  
        publicKey = getPublicKey(map);  
        privateKey = getPrivateKey(map);  
        System.out.println("公钥: \n\r" + publicKey);  
        System.out.println("私钥: \n\r" + privateKey);  
        System.out.println("公钥加密--------私钥解密");  
        String word = "你好!";  
        byte[] encWord = encryptByPublicKey(word.getBytes(), publicKey);  
       
        String decWord = new String(decryptByPrivateKey(encWord, privateKey));  
        System.out.println("加密前: " + word + "\n\r" + "解密后: " + decWord);  
        System.out.println("私钥加密--------公钥解密");  
        String english = "Hello, World!";  
        byte[] encEnglish = encryptByPrivateKey(english.getBytes(), privateKey);  
        String decEnglish = new String(decryptByPublicKey(encEnglish, publicKey));  
        System.out.println("加密前: " + english + "\n\r" + "解密后: " + decEnglish);  
        System.out.println("私钥签名——公钥验证签名");  
        // 产生签名  
        String sign = sign(encEnglish, privateKey);  
        System.out.println("签名:\r" + sign);  
        // 验证签名  
        boolean status = verify(encEnglish, publicKey, sign);  
        System.out.println("状态:\r" + status);  
    }  
}

CA数字加密解密Demo的更多相关文章

  1. <经验杂谈>C#对CA证书加密解密的简单介绍

    最近做项目接触了一些关于用CA证书加密解密的知识,现在分享一下,加密主要分为对称加密和非对称加密以及单项加密这三种,CA是一个权威的第三方认证机构,CA加密有公钥和私钥之分. 以下是C#读取证书文件进 ...

  2. java纯数字加密解密实例

    我们都知道,在用户加入信息时,一些比較敏感的信息,如身份证号,手机号,用户的登录password等信息,是不能直接明文存进数据库的.今天我们就以一个详细的样例来说明一下纯数字的java加密解密技术. ...

  3. Asp.net,C# 纯数字加密解密字符串

    也就是说加密后的数据不再是:N8lAaHMFtSAQgaf3+RUFng== 希望encryptedString是"1203877893704809384098328409234923840 ...

  4. RSA JS 加密解密DEMO

    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script&g ...

  5. 加密解密(2)*客户端,服务器,CA(Certificate Authority),公钥,私钥,证书,签名,验证

    加密解密(2)*客户端,服务器,CA(Certificate Authority),公钥,私钥,证书,签名,验证 各角色比喻 客户端:通常为请求方,要验证服务器的身份. 服务器:通常为响应方,有时也要 ...

  6. Java加密解密与数字证书的操作

    1 keytool命令总结 一.创建数字证书 交互模式 使用默认的密钥库.keystore(文件夹是c: Documents and Settingusername)和算法(DSA) keytool  ...

  7. 加密解密以及CA签证

    在当今互联网时代,数据越来越来重要.那么如何加密?解密?以及通过什么方式来认证了?? 接下来,我就会和大家谈谈加密,解密以及CA签证的实现. 首先大家的知道一些加密,解密的基本常识: 互联网上中间人一 ...

  8. PHP加密解密数字

    <?php /** * 加密解密类,PHP加密解密数字,适用于URL加密 * 该算法仅支持加密数字.比较适用于数据库中id字段的加密解密,以及根据数字显示url的加密. * @version a ...

  9. linux基础之加密解密、PKI及SSL、创建私有CA

    加密解密基础 1. 对称加密: 加密和解密使用同一个密钥 常见的加密算法有:DES.3DES.AES.Blowfish.Twofish.IDEA.RC6.CAST5 特性: 1. 加密.解密使用同一个 ...

随机推荐

  1. jQuery loop over JSON字符串 – $.each实例

    先来一段简单的javascript对象的遍历: var json = [ {"id":"1","tagName":"apple&q ...

  2. grafana二次开发

    grafana官方地址: https://github.com/grafana/grafana 开发文档:http://docs.grafana.org/project/building_from_s ...

  3. npm install 报错 ECONNREFUSED

    在window环境下,使用npm install 命令安装任何框架,都会报如下的错误 error code ECONNREFUSED error errno ECONNREFUSED error Fe ...

  4. Elasticsearch6.0之二:常用语句

    // 查看集群状态 GET /_cluster/health?pretty // 查看所有索引配置信息 Get _all/_settings // 查看所有索引状态 GET /_cat/indices ...

  5. ACM ICPC 2010–2011, Northeastern European Regional Contest St Petersburg – Barnaul – Tashkent – Tbilisi, November 24, 2010

    ACM ICPC 2010–2011, Northeastern European Regional Contest St Petersburg – Barnaul – Tashkent – Tbil ...

  6. spring mvc:练习 @RequestParam(参数绑定到控制器)和@PathVariable(参数绑定到url模板变量)

    spring mvc:练习 @RequestParam和@PathVariable @RequestParam: 注解将请求参数绑定到你的控制器方法参数 @PathVariable: 注释将一个方法参 ...

  7. HDU 4274 Spy's Work (树形DP)

    题意 给定一棵树,给出一些子树的权值关系,问是否矛盾(初始所有结点的下限为1) 思路 设lmin和lmax表示题目给定的限制范围,默认为[1..oo]:amin和amax表示实际符合要求的范围.从根节 ...

  8. 【Python】装饰器理解

    以下文章转载自:点这里 关于装饰器相关的帖子记录在这里: 廖雪峰, thy专栏, stackflow Python的函数是对象 简单的例子: def shout(word="yes" ...

  9. iptables(五)iptables匹配条件总结之二(常用扩展模块)

    iprange扩展模块 之前我们已经总结过,在不使用任何扩展模块的情况下,使用-s选项或者-d选项即可匹配报文的源地址与目标地址,而且在指定IP地址时,可以同时指定多个IP地址,每个IP用" ...

  10. centos 7安装jenkins

    1. 安装java yum install java 2. 安装jenkins wget -O /etc/yum.repos.d/jenkins.repo http://pkg.jenkins-ci. ...