`
sillycat
  • 浏览: 2552523 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

bouncycastle(5)Learn from others RSA

    博客分类:
  • JAVA
 
阅读更多
bouncycastle(5)Learn from others RSA

RSA
There are 2 keys in RSA, one is private, one is public. They can be used to encrypt/decrypt and signing.

A will generate private/public key pair. A shares the public key to B.
A will sign and encrypt the data, send the data to B.
B will use public key to validate the signing and decrypt the data.

B will use public key to encrypt the data.
A will use private key to decrypt the data.

The implementation class is as follow:
package com.sillycat.easycastle.encryption;
import javax.crypto.Cipher;
public class RSACoder extends Coder {
     public static final String KEY_ALGORITHM = "RSA";
     public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
     private static final String PUBLIC_KEY = "RSAPublicKey";
     private static final String PRIVATE_KEY = "RSAPrivateKey";
     /**
     * use private key to generate the signing data
     * @param data
     * @param privateKey
     * @return
     * @throws Exception
     */
     public static String sign(byte[] data, String privateKey) throws Exception {
          // decrypt the private key via base64
          byte[] keyBytes = decryptBASE64(privateKey);
          // construct PKCS8EncodedKeySpec object
          PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
          // KEY_ALGORITHM RSA
          KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
          // convert to key object from private key string
          PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);

          // signature
          Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
          signature.initSign(priKey);
          signature.update(data);

          return encryptBASE64(signature.sign());
     }

     /**
     * validate the signature
     * @param data
     * @param publicKey
     * @param sign
     *
     * @return true false
     * @throws Exception
     */
     public static boolean verify(byte[] data, String publicKey, String sign)
               throws Exception {
          // decrypt the public key via base64
          byte[] keyBytes = decryptBASE64(publicKey);
          // construct X509EncodedKeySpec object
          X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
          // KEY_ALGORITHM
          KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
          // convert to public key from public key string
          PublicKey pubKey = keyFactory.generatePublic(keySpec);

          Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
          signature.initVerify(pubKey);
          signature.update(data);

          // validate the signature
          return signature.verify(decryptBASE64(sign));
     }

     /**
     * decryption via private key
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
     public static byte[] decryptByPrivateKey(byte[] data, String privateKeyString)
               throws Exception {
          // decrypt key from string
          byte[] keyBytes = decryptBASE64(privateKeyString);

          // get the private key
          PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
          KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
          Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

          // decrypt the data via private key
          Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
          cipher.init(Cipher.DECRYPT_MODE, privateKey);

          return cipher.doFinal(data);
     }

     /**
     * decrypt via public key
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
     public static byte[] decryptByPublicKey(byte[] data, String publicKeyString)
               throws Exception {
          // decrypt the key string
          byte[] keyBytes = decryptBASE64(publicKeyString);

          // convert the key object to get the public key
          X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
          KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
          Key publicKey = keyFactory.generatePublic(x509KeySpec);

          // decrypt the data with public key
          Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
          cipher.init(Cipher.DECRYPT_MODE, publicKey);

          return cipher.doFinal(data);
     }

     /**
     * encrypt via public key
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
     public static byte[] encryptByPublicKey(byte[] data, String publicKeyString)
               throws Exception {
          // decrypt the public key
          byte[] keyBytes = decryptBASE64(publicKeyString);

          // convert to public key object
          X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
          KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
          Key publicKey = keyFactory.generatePublic(x509KeySpec);

          // encrypt the data via public key
          Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
          cipher.init(Cipher.ENCRYPT_MODE, publicKey);

          return cipher.doFinal(data);
     }

     /**
     * encrypt the data via private key
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
     public static byte[] encryptByPrivateKey(byte[] data, String privateKeyString)
               throws Exception {
          // decrypt the key from string
          byte[] keyBytes = decryptBASE64(privateKeyString);

          // convert to private key object
          PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
          KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
          Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

          // encrypt the data
          Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
          cipher.init(Cipher.ENCRYPT_MODE, privateKey);

          return cipher.doFinal(data);
     }

     /**
     * get the private key
     *
     * @param keyMap
     * @return
     * @throws Exception
     */
     public static String getPrivateKey(Map<String, Object> keyMap)
               throws Exception {
          Key key = (Key) keyMap.get(PRIVATE_KEY);
          return encryptBASE64(key.getEncoded());
     }

     /**
     * get public key
     *
     * @param keyMap
     * @return
     * @throws Exception
     */
     public static String getPublicKey(Map<String, Object> keyMap)
               throws Exception {
          Key key = (Key) keyMap.get(PUBLIC_KEY);
          return encryptBASE64(key.getEncoded());
     }

     /**
     * initiate the key pair
     * @return
     * @throws Exception
     */
     public static Map<String, Object> initKey() throws Exception {
          KeyPairGenerator keyPairGen = KeyPairGenerator
                    .getInstance(KEY_ALGORITHM);
          keyPairGen.initialize(1024);
          KeyPair keyPair = keyPairGen.generateKeyPair();
          // public key
          RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
          // private key
          RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
          Map<String, Object> keyMap = new HashMap<String, Object>(2);
          keyMap.put(PUBLIC_KEY, publicKey);
          keyMap.put(PRIVATE_KEY, privateKey);
          return keyMap;
     }
}

And the test class is as follow:
package com.sillycat.easycastle.encryption;
import static org.junit.Assert.*;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;

public class RSACoderTest {

     private String publicKey;
     private String privateKey;

     @Before
     public void setUp() throws Exception {
          Map<String, Object> keyMap = RSACoder.initKey();
          publicKey = RSACoder.getPublicKey(keyMap);
          privateKey = RSACoder.getPrivateKey(keyMap);
          System.out.println("public key : \n\r" + publicKey);
          System.out.println("private key: \n\r" + privateKey);
     }

     @Test
     public void test() throws Exception {
          System.out.println("public key encryption——private key decryption");
          String inputStr = "hello, sillycat.";
          byte[] data = inputStr.getBytes();
          byte[] encodedData = RSACoder.encryptByPublicKey(data, publicKey);

          byte[] decodedData = RSACoder.decryptByPrivateKey(encodedData,
                    privateKey);

          String outputStr = new String(decodedData);
          System.out.println("original: " + inputStr + "\n\r" + "decryption: " + outputStr);
          assertEquals(inputStr, outputStr);
     }

     @Test
     public void testSign() throws Exception {
          System.out.println("private encryption——public decryption");
          String inputStr = "hello, kiko.";
          byte[] data = inputStr.getBytes();

          byte[] encodedData = RSACoder.encryptByPrivateKey(data, privateKey);

          byte[] decodedData = RSACoder
                    .decryptByPublicKey(encodedData, publicKey);

          String outputStr = new String(decodedData);
          System.out.println("original: " + inputStr + "\n\r" + "decryption: " + outputStr);
          assertEquals(inputStr, outputStr);

          System.out.println("private signature——public validate the signature");
          // generate signature
          String sign = RSACoder.sign(encodedData, privateKey);
          System.out.println("singature string :\r" + sign);

          // validate signature string
          boolean status = RSACoder.verify(encodedData, publicKey, sign);
          System.out.println("status:\r" + status);
          assertTrue(status);
     }
}


references:
http://snowolf.iteye.com/blog/381767

分享到:
评论

相关推荐

    开源加密库Bouncy Castle Crypto APIs (RSA加密)

    在Java中,Bouncy Castle的`org.bouncycastle.jce.provider.BouncyCastleProvider`提供了一个强大的安全提供者,可以用来生成和管理RSA密钥对。在生成密钥对后,可以将其导出为PEM格式的字符串,如以下代码所示: `...

    BouncyCastle依赖.zip

    1. **bcprov-jdk15on-1.62.jar**:这是BouncyCastle的主要加密提供者包,提供了广泛的加密算法实现,如RSA、AES、DES、SHA等。它支持Java 1.5及更高版本,因此名称中的"jdk15on"表示这个版本适用于Java 1.5及以上。...

    bouncycastle jar包

    Bouncy Castle实现了PKCS#7(用于数据封装和签名)、PKCS#12(用于存储私钥和证书)、PKCS#5(用于密码化)和PKCS#11(用于硬件加密设备接口)等标准。 **OpenSSL兼容** Bouncy Castle还提供了一个名为BCrypt的...

    C# BouncyCastle实现带原文数据PKCS#7 签名、验签

    你可以使用BouncyCastle库生成一个新的RSA密钥对,或者从已有的PEM或DER格式的文件中加载。 3. **创建签名**: - 首先,你需要将原始数据转换为字节数组。 - 然后,创建一个DigestInfo对象,它包含了数据的哈希值...

    BouncyCastle.Crypto

    BouncyCastle提供了实现RSA和DSA(数字签名算法)等数字签名功能,使得信息不能被篡改且能验证发送者的身份。 5. **PKCS标准**: 支持PKCS#7(用于封装和签名数据)和PKCS#12(个人证书存储格式),方便导入和...

    BouncyCastle.Crypto.dll

    BouncyCastle.Crypto.dll是一个开源的加密库,由The Legion of the Bouncy Castle组织开发,提供了大量加密算法和协议的实现,包括但不限于RSA、AES、DES、DH(Diffie-Hellman)、ECC(椭圆曲线密码学)等。...

    org.bouncycastle 加密算法包 最新1.69版

    Bouncy Castle 实现了 PKCS#1、PKCS#5、PKCS#7、PKCS#8 和 PKCS#12 等标准,这些标准涉及密钥管理、密码存储和数据封装等。 9. **JCE 兼容性**: 作为 JCE 的扩展,Bouncy Castle 可以作为替代提供更丰富的加密...

    BouncyCastle.Crypto.dll 版本1.8.6 C#语言

    1. **加密算法支持**:BouncyCastle.Crypto.dll 提供了多种加密算法的实现,包括对称加密(如AES、Blowfish、DES)、非对称加密(如RSA、DSA、ECDSA)、哈希函数(如SHA-1、SHA-256、MD5)和消息认证码(MAC)。...

    BouncyCastle.dll C#依赖工具,用作数据的加解密辅助类

    RSA是最常见的非对称加密算法,Bouncy Castle也支持DSA和椭圆曲线加密(ECC),这些算法在密钥交换和数字签名中起着关键作用。 3. **数字签名**:Bouncy Castle可以创建和验证数字签名,这在确保数据完整性和来源...

    BouncyCastle.Crypto.rar

    BouncyCastle.Crypto.dll是.NET版本的核心组件,包含了大量加密算法的实现,如对称加密(如AES、DES、3DES)、非对称加密(RSA、DSA、ECC)、哈希算法(MD5、SHA-1、SHA-256等)以及消息认证码(MAC)等。...

    BouncyCastle.Crypto.dll 版本1.8.1

    2. **广泛的密码学算法**:BouncyCastle 支持众多加密算法,如AES、DES、3DES、Blowfish、RSA、DSA、ECDSA等,还包括哈希函数如SHA-1、SHA-256、MD5等,以及消息认证码(MAC)和伪随机数生成器(PRNG)。 3. **PKCS...

    BouncyCastle.Crypto.dll 1.8.2

    《BouncyCastle.Crypto.dll 1.8.2:深入解析加密库的奥秘》 在信息技术领域,安全是至关重要的。特别是在网络通信、数据存储和传输等方面,强大的加密技术是保障信息安全的基础。BouncyCastle.Crypto.dll是这样一个...

    bouncycastle1.59 帮助文档(包含html源文件制作工具)

    《BouncyCastle1.59帮助文档:深入理解与CHM制作详解》 BouncyCastle,作为Java和.NET平台上广泛使用的开源加密库,为开发者提供了丰富的加密算法、密码学标准接口以及证书处理功能。这份“BouncyCastle1.59帮助...

    Bouncy Castle 1.64 API及制作工具

    Bouncy Castle 支持多种加密算法,包括对称加密(如 AES、DES、3DES)、非对称加密(RSA、DSA、ECDSA)、哈希函数(MD5、SHA-1、SHA-256 及以上)、消息认证码(MAC)等。这些算法的实现使得开发人员能够灵活选择...

    C# BouncyCastle实现带原文数据PKCS#7 签名

    本文将详细讲解如何使用C#语言和BouncyCastle库来实现带原文数据的PKCS#7签名。 PKCS#7(Public-Key Cryptography Standards #7)是由RSA Security提出的一种标准,它定义了证书、证书撤销列表(CRL)的格式以及...

    bouncycastle集合包

    在这个集合包中,我们找到了四个不同版本的BouncyCastle相关jar文件,分别如下: 1. **bcprov-jdk16-1.46.jar**:这是BouncyCastle的主要提供者包,主要用于Java平台。"bcprov"代表BouncyCastle Provider,"jdk16...

Global site tag (gtag.js) - Google Analytics