一个使用bouncycastle进行安全操作的实用类

2007-04-13 12:54

import java.io.*;
import java.security.*;
import java.security.interfaces.*;
import java.math.*;
import java.util.Enumeration;
import java.util.Vector;

import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.encodings.PKCS1Encoding;
import org.bouncycastle.crypto.engines.RSAEngine;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters;
import org.bouncycastle.util.encoders.Hex;

public class RSAUtil {

final public static int RAW = 1;
    final public static int PKCS1 = 2;

/*
    * 产生RSA公私钥对
    */
    public static KeyPair genRSAKeyPair() {
        KeyPairGenerator rsaKeyGen = null;
        KeyPair rsaKeyPair = null;
        try {
            System.out.println("Generating a pair of RSA key ... ");
            rsaKeyGen = KeyPairGenerator.getInstance("RSA");
            SecureRandom random = new SecureRandom();
            random.nextBytes(new byte[1]);
            rsaKeyGen.initialize(1024, new SecureRandom());
            rsaKeyPair = rsaKeyGen.genKeyPair();
            PublicKey rsaPublic = rsaKeyPair.getPublic();
            PrivateKey rsaPrivate = rsaKeyPair.getPrivate();
            System.out.println("1024-bit RSA key GENERATED.");
        } catch (Exception e) {
            System.out.println("Exception in keypair generation. Reason: " + e);
        }

return rsaKeyPair;
    }

/*
    * 列出密钥库中指定的条目
    */
    public static void showAllEntry(String filename, String pass) {
        try {
            FileInputStream inKeyStoreFile = new FileInputStream(filename);
            char[] password = pass.toCharArray();
            KeyStore from = KeyStore.getInstance("JKS", "SUN");
            from.load(null, null);
            from.load(inKeyStoreFile, password);
            Enumeration e = from.aliases();
            System.out.println("Entry List:");
            while (e.hasMoreElements()) {
                System.out.println((String) e.nextElement());
            }
            inKeyStoreFile.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

/*
    * 列出密钥库中所有的条目
    */
    public static Vector getAllEntry(String filename, String pass) {
        Vector v = new Vector();
        try {
            FileInputStream inKeyStoreFile = new FileInputStream(filename);
            char[] password = pass.toCharArray();
            KeyStore from = KeyStore.getInstance("JKS", "SUN");
            from.load(null, null);
            from.load(inKeyStoreFile, password);
            Enumeration e = from.aliases();
            System.out.println("Entry List:");
            while (e.hasMoreElements()) {
                v.addElement((String) e.nextElement());

}
            inKeyStoreFile.close();
            return v;
        } catch (Exception e) {
            System.out.println(e);
            return null;
        }
    }

/*
    * 获得私钥
    */
    public static RSAPrivateKey loadPrivateKey(String filename, String keyName,
            String pass) throws Exception {
        FileInputStream inKeyStoreFile = new FileInputStream(filename);
        char[] password = pass.toCharArray();
        KeyStore from = KeyStore.getInstance("JKS", "SUN");
        from.load(null, null);
        from.load(inKeyStoreFile, password);
        Key testkey = from.getKey(keyName, password);
        RSAPrivateKey pvtKey = (RSAPrivateKey) testkey;
        System.out.println("Private key exponent =\r\n"
                + pvtKey.getPrivateExponent().toString(16) + "\r\n");
        inKeyStoreFile.close();
        return pvtKey;
    }

/*
    * 获得公钥
    */
    public static RSAPublicKey loadPublicKey(String filename, String keyName,
            String pass) throws Exception {
        FileInputStream inKeyStoreFile = new FileInputStream(filename);
        char[] password = pass.toCharArray();
        KeyStore from = KeyStore.getInstance("JKS", "SUN");
        from.load(null, null);
        from.load(inKeyStoreFile, password);
        java.security.cert.Certificate c = from.getCertificate(keyName);
        RSAPublicKey pubKey = (RSAPublicKey) c.getPublicKey();
        System.out.println("Public key exponent =\r\n"
                + pubKey.getPublicExponent().toString(16) + "\r\n");
        inKeyStoreFile.close();
        return pubKey;
    }

/*
    * 使用公钥加密
    */
    public static byte[] rsaPubEncrypt(RSAPublicKey PubKey, byte[] clearBytes,
            int type) {

BigInteger mod = PubKey.getModulus();
        BigInteger pubExp = PubKey.getPublicExponent();

RSAKeyParameters pubParameters = new RSAKeyParameters(false, mod,
                pubExp);

System.out.println("mod:\r\n" + mod.toString(16));
        System.out.println("pubExp:\r\n" + pubExp.toString(16));
        AsymmetricBlockCipher eng = new RSAEngine();
        if (type == PKCS1)
            eng = new PKCS1Encoding(eng);
        eng.init(true, pubParameters);
        byte[] data = null;
        try {
            System.out.println("clearBytes:\r\n"
                    + new String(Hex.encode(clearBytes)));
            data = eng.processBlock(clearBytes, 0, clearBytes.length);
            System.out.println("EncBytes:\r\n" + new String(Hex.encode(data)));
            return data;
        } catch (Exception e) {
            System.out.println(e);
            return null;
        }
    }

/*
    * 公钥解密
    */
    public static byte[] rsaPubDecrypt(RSAPublicKey PubKey, byte[] clearBytes,
            int type) {

BigInteger mod = PubKey.getModulus();
        BigInteger pubExp = PubKey.getPublicExponent();

RSAKeyParameters pubParameters = new RSAKeyParameters(false, mod,
                pubExp);

System.out.println("mod:\r\n" + mod.toString(16));
        System.out.println("pubExp:\r\n" + pubExp.toString(16));
        AsymmetricBlockCipher eng = new RSAEngine();
        if (type == PKCS1)
            eng = new PKCS1Encoding(eng);
        eng.init(false, pubParameters);
        byte[] data = null;
        try {
            System.out.println("clearBytes:\r\n"
                    + new String(Hex.encode(clearBytes)));
            data = eng.processBlock(clearBytes, 0, clearBytes.length);
            System.out.println("EncBytes:\r\n" + new String(Hex.encode(data)));
            return data;
        } catch (Exception e) {
            System.out.println(e);
            return null;
        }
    }

/*
    * 私钥解密
    */
    public static byte[] rsaPriDecrypt(RSAPrivateKey prvKeyIn,
            byte[] encodedBytes, int type) {

RSAPrivateCrtKey prvKey = (RSAPrivateCrtKey) prvKeyIn;

BigInteger mod = prvKey.getModulus();
        BigInteger pubExp = prvKey.getPublicExponent();
        BigInteger privExp = prvKey.getPrivateExponent();
        BigInteger pExp = prvKey.getPrimeExponentP();
        BigInteger qExp = prvKey.getPrimeExponentQ();
        BigInteger p = prvKey.getPrimeP();
        BigInteger q = prvKey.getPrimeQ();
        BigInteger crtCoef = prvKey.getCrtCoefficient();

RSAKeyParameters privParameters = new RSAPrivateCrtKeyParameters(mod,
                pubExp, privExp, p, q, pExp, qExp, crtCoef);

AsymmetricBlockCipher eng = new RSAEngine();
        if (type == PKCS1)
            eng = new PKCS1Encoding(eng);

eng.init(false, privParameters);
        byte[] data = null;
        try {
            data = eng.processBlock(encodedBytes, 0, encodedBytes.length);
            return data;
        } catch (Exception e) {
            System.out.println(e);
            return null;
        }

}

/*
    * 使用私钥加密
    */
    public static byte[] rsaPriEncrypt(RSAPrivateKey prvKeyIn,
            byte[] encodedBytes, int type) {
        RSAPrivateCrtKey prvKey = (RSAPrivateCrtKey) prvKeyIn;
        BigInteger mod = prvKey.getModulus();
        BigInteger pubExp = prvKey.getPublicExponent();
        BigInteger privExp = prvKey.getPrivateExponent();
        BigInteger pExp = prvKey.getPrimeExponentP();
        BigInteger qExp = prvKey.getPrimeExponentQ();
        BigInteger p = prvKey.getPrimeP();
        BigInteger q = prvKey.getPrimeQ();
        BigInteger crtCoef = prvKey.getCrtCoefficient();
        RSAKeyParameters privParameters = new RSAPrivateCrtKeyParameters(mod,
                pubExp, privExp, p, q, pExp, qExp, crtCoef);
        AsymmetricBlockCipher eng = new RSAEngine();
        if (type == PKCS1)
            eng = new PKCS1Encoding(eng);
        eng.init(true, privParameters);
        byte[] data = null;
        try {
            data = eng.processBlock(encodedBytes, 0, encodedBytes.length);
            return data;
        } catch (Exception e) {
            System.out.println(e);
            return null;
        }

}

问题所在:

本系统采用的是RSA签名验证方案。采用PKCS1填充方案。

RSAPublicKey 和RSAPrivateKey 在BC中无该类,故研究发现:

RSAPublicKey可采用BC中的RSAKeyParameters,RSAPrivateKey可采用修改BC中的RSAPrivateCrtKeyParameter;主要修改其中的mod和privateExp;

并增加其getter和setter方法。以便于采用私钥参数加密。

Bouncycastle中的RSA技术以及解决之道的更多相关文章

  1. iOS 学习笔记二【cocopods安装使用和安装过程中遇到的问题及解决办法】【20160725更新】

    在osx 10.11之前cocopods问题不多,但是升级到11之后的版本,之前的cocopods大多用不了,需要重新安装,对于我这种使用测试版系统的技术狂来说,每次都需要重新安装很多东西, 当然,c ...

  2. Unity教程之再谈Unity中的优化技术

    这是从 Unity教程之再谈Unity中的优化技术 这篇文章里提取出来的一部分,这篇文章让我学到了挺多可能我应该知道却还没知道的知识,写的挺好的 优化几何体   这一步主要是为了针对性能瓶颈中的”顶点 ...

  3. GPRS GPRS(General Packet Radio Service)是通用分组无线服务技术的简称,它是GSM移动电话用户可用的一种移动数据业务,属于第二代移动通信中的数据传输技术

    GPRS 锁定 本词条由“科普中国”百科科学词条编写与应用工作项目 审核 . GPRS(General Packet Radio Service)是通用分组无线服务技术的简称,它是GSM移动电话用户可 ...

  4. Android中直播视频技术探究之---基础知识大纲介绍

    一.前言 最近各种视频直播app到处都是,各种霸屏,当然我们也是需要体验的,关于视频直播的软件这里就不介绍了,在不是技术的人来看,直播是一种潮流,是一种娱乐方式,但是作为一个高技术的,我们除了看看,更 ...

  5. VC中利用多线程技术实现线程之间的通信

    当前流行的Windows操作系统能同时运行几个程序(独立运行的程序又称之为进程),对于同一个程序,它又可以分成若干个独立的执行流,我们称之为线程,线程提供了多任务处理的能力.用进程和线程的观点来研究软 ...

  6. OS X 和iOS 中的多线程技术(上)

    OS X 和iOS 中的多线程技术(上) 本文梳理了OS X 和iOS 系统中提供的多线程技术.并且对这些技术的使用给出了一些实用的建议. 多线程的目的:通过并发执行提高 CPU 的使用效率,进而提供 ...

  7. C++中的Thunk技术 / 非静态类成员函数作为回调函数 的实现方法

    原文:https://blog.twofei.com/616/ 用我的理解通俗地解释一下什么是C++中的Thunk技术吧! Thunk技术就是申请一段可执行的内存, 并通过手动构造CPU指令的形式来生 ...

  8. iOS cocopods安装使用和安装过程中遇到的问题及解决办法

    在osx 10.11之前cocopods问题不多,但是升级到11之后的版本,之前的cocopods大多用不了,需要重新安装,对于我这种使用测试版系统的技术狂来说,每次都需要重新安装很多东西, 当然,c ...

  9. 在vue中使用 layui框架中的form.render()无效解决办法

    下面简单介绍在vue中使用 layui框架中的form.render()无效解决办法. 原文地址:小时刻个人技术博客 > http://small.aiweimeng.top/index.php ...

随机推荐

  1. 【题解】【区间】【二分查找】【Leetcode】Insert Interval & Merge Intervals

    Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessa ...

  2. MySQL单表多字段模糊查询解决方法

    例如现有table表,其中有title,tag,description三个字段,分别记录一条资料的标题,标签和介绍.然后根据用户输入的查询请求,将输入的字串通过空格分割为多个关键字,再在这三个字段中查 ...

  3. asp.net网站 提示Ambiguous match found

    在ASP.net中,每个aspx页面都会有一个.cs文件,(好像不可以多个aspx共用一个cs的,我前面就碰到这个问题), 在aspx页面中,我们会用到服务器控件,或html控件,这些控件的id命名时 ...

  4. Letter Combinations of a Phone Number

    Given a digit string, return all possible letter combinations that the number could represent. A map ...

  5. hdu4642 Fliping game ——博弈

    link:http://acm.hdu.edu.cn/showproblem.php?pid=4642 refer to: http://www.cnblogs.com/jackge/archive/ ...

  6. VK Cup 2012 Round 3 (Unofficial Div. 2 Edition)

    VK Cup 2012 Round 3 (Unofficial Div. 2 Edition) 代码 VK Cup 2012 Round 3 (Unofficial Div. 2 Edition) A ...

  7. 3-4 rpm包查询

    概述:yum不能查询已经安装好的rpm包, 就算采用了yum来进行安装,查询方法还是依赖rpm包的查询, 因此rpm包的查询十分常用和重要 1.查询是否安装 <1>rpm -q 包名(不是 ...

  8. OOP作业

    1,定义一个水果类(fruit),水果类中的有[属性]:颜色(color).价格(price).重量(weigth),再定义一个<测试类>,创建一个苹果(apple)的对象, 颜色是&qu ...

  9. Swiper说明及API手册说明

    最近使用Swipe.js,发现中文的资料很少,试着翻译了一下.能力有限,翻译难免错漏,欢迎指出,多谢! 翻译自:http://www.idangero.us/sliders/swiper/api.ph ...

  10. php get set方法深入理解

    在类当中,设计通用的set和get方法,可以简化对属性的读写,这种方法不同于针对于独立的属性的普通的get和set方法,后者针对每个属性,都必须提供一对方法,前者针对所有属性,因此,可以看作是批量定义 ...