一个使用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. 用NSOperation和NSOperationQueue实现多线程编程

    1.上一讲简单介绍了NSThread的使用,虽然也可以实现多线程编程,但是需要我们去管理线程的生命周期,还要考虑线程同步.加锁问题,造成一些性能上的开销.我们也可以配合使用NSOperation和NS ...

  2. C# 网络通信基础 总结

    1.WebClient类 如果只是想从特定的URI(统一资源标识符)请求文件,则可以使用最简单的.NET类,System.Net.WebClient.支持http:.https:和file:标识符开头 ...

  3. xampp改到phpmyadmin的root密碼無法登錄

    open /Applications/XAMPP/xamppfiles/phpmyadmin/config.inc.php $cfg['Servers'][$i]['auth_type'] = 'co ...

  4. ZOJ 1243 URLs

    /*In the early nineties, the World Wide Web (WWW) was invented. Nowadays, most people think that the ...

  5. codeforces magic five --快速幂模

    题目链接:http://codeforces.com/contest/327/problem/C 首先先算出一个周期里面的值,保存在ans里面,就是平常的快速幂模m做法. 然后要计算一个公式,比如有k ...

  6. T语言TC发布脚本方法

    代码模式的注册码发布脚本方法 注册码项目模式的发布脚本方法 1.注册码项目发布版 2.注册码项目代理版 这两种方法都是基于注册码项目来实现的,所以在使用之前,需要先创建注册码项目.

  7. Android 中解析 JSON

    有什么不懂的可以去官网去看看:www.json.org 在google android中也有关于解析JSON的类库:JsonReader,但是只能在3.0以后的版本中才可以用,在这里我们用google ...

  8. DELPHI相应鼠标滚轮

    在鼠标的MouseWheel事件里写入以下内容 if WheelDelta < 0 then    SendMessage(scrollBox1.Handle, WM_VSCROLL, SB_L ...

  9. Linux下PHP+MySQL+CoreSeek中文检索引擎配置

    说明: 操作系统:CentOS 5.X 服务器IP地址:192.168.21.127 Web环境:Nginx+PHP+MySQL 站点根目录:/usr/local/nginx/html 目的:安装co ...

  10. postgreSQL 时间线

    “时间线”(Timeline)是PG一个很有特色的概念,在备份恢复方面的文档里面时有出现.但针对这个概念的详细解释却很少,也让人不太好理解,我们在此仔细解析一下. 时间线的引入 为了理解引入时间线的背 ...