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

bouncycastle(8)Learn from others ECC/KeyTool

    博客分类:
  • JAVA
 
阅读更多
bouncycastle(8)Learn from others ECC/KeyTool

ECC (Elliptic Curves Cryptography)
It is not supported by JDK from the content of other's blog. So I do not take time to verify the codes.

Work with KeyTool in JDK
prepare the key pair first
>keytool -genkey -validity 36000 -alias www.sillycat.com -keyalg RSA -keystore /Users/karl/work/easy/easycastle/src/main/resources/sillycat.keystore
-genkey means generate the key
-validity means the valid date, 36000 means 36000 days.
-alias    means the name
-keyalg  algorithm
-keystore  where do we store the key pair

>keytool -export -keystore /Users/karl/work/easy/easycastle/src/main/resources/sillycat.keystore -alias www.sillycat.com -file /Users/karl/work/easy/easycastle/src/main/resources/sillycat.cer -rfc

-export
-keystore  identify the key store file
-alias
-file          where do we store the car file.
-rfc           means output to txt based on base64

sillycat.keystore holds the private key, sillycat.cer holds the public key.

The implementation will be as follow.
package com.sillycat.easycastle.encryption;

import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Date;

import javax.crypto.Cipher;

publicabstractclass CertificateCoder extends Coder {

/**
* (Java Key Store,JKS)KEY_STORE
*/
publicstaticfinal String KEY_STORE = "JKS";

publicstaticfinal String X509 = "X.509";

/**
* get the private key from keystore
*
* @param keyStorePath
* @param alias
* @param password
* @return
* @throws Exception
*/
privatestatic PrivateKey getPrivateKey(String keyStorePath, String alias,
String password) throws Exception {
KeyStore ks = getKeyStore(keyStorePath, password);
PrivateKey key = (PrivateKey) ks.getKey(alias, password.toCharArray());
return key;
}

/**
* get the public key from certificate
*
* @param certificatePath
* @return
* @throws Exception
*/
privatestatic PublicKey getPublicKey(String certificatePath)
throws Exception {
Certificate certificate = getCertificate(certificatePath);
PublicKey key = certificate.getPublicKey();
return key;
}

privatestatic Certificate getCertificate(String certificatePath)
throws Exception {
FileInputStream in = null;
Certificate certificate = null;
CertificateFactory certificateFactory = CertificateFactory
.getInstance(X509);
in = new FileInputStream(certificatePath);
certificate = certificateFactory.generateCertificate(in);
in.close();
return certificate;
}

privatestatic Certificate getCertificate(String keyStorePath,
String alias, String password) throws Exception {
KeyStore ks = getKeyStore(keyStorePath, password);
Certificate certificate = ks.getCertificate(alias);
return certificate;
}

privatestatic KeyStore getKeyStore(String keyStorePath, String password)
throws Exception {
FileInputStream is = new FileInputStream(keyStorePath);
KeyStore ks = KeyStore.getInstance(KEY_STORE);
ks.load(is, password.toCharArray());
is.close();
return ks;
}

/**
* encrypt the data using private key
*
* @param data
* @param keyStorePath
* @param alias
* @param password
* @return
* @throws Exception
*/
publicstaticbyte[] encryptByPrivateKey(byte[] data, String keyStorePath,
String alias, String password) throws Exception {
// get private key
PrivateKey privateKey = getPrivateKey(keyStorePath, alias, password);
// encrypt the data
Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return cipher.doFinal(data);
}

/**
* decrypt the data using private key
*
* @param data
* @param keyStorePath
* @param alias
* @param password
* @return
* @throws Exception
*/
publicstaticbyte[] decryptByPrivateKey(byte[] data, String keyStorePath,
String alias, String password) throws Exception {
// get the private key
PrivateKey privateKey = getPrivateKey(keyStorePath, alias, password);
// decrypt the data
Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(data);
}

/**
* encrypt data based on public key
* @param data
* @param certificatePath
* @return
* @throws Exception
*/
publicstaticbyte[] encryptByPublicKey(byte[] data, String certificatePath)
throws Exception {
// get the public key
PublicKey publicKey = getPublicKey(certificatePath);
// encrypt the data
Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(data);
}

/**
* decrypt data based on public key
* @param data
* @param certificatePath
* @return
* @throws Exception
*/
publicstaticbyte[] decryptByPublicKey(byte[] data, String certificatePath)
throws Exception {
// get the public key
PublicKey publicKey = getPublicKey(certificatePath);
// decrypt data
Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return cipher.doFinal(data);
}

/**
* verify Certificate
* @param certificatePath
* @return
*/
publicstaticboolean verifyCertificate(String certificatePath) {
return verifyCertificate(new Date(), certificatePath);
}

/**
* verify Certificate valid
* @param date
* @param certificatePath
* @return
*/
publicstaticboolean verifyCertificate(Date date, String certificatePath) {
boolean status = true;
try {
// get the certificate
Certificate certificate = getCertificate(certificatePath);
status = verifyCertificate(date, certificate);
} catch (Exception e) {
status = false;
}
return status;
}

privatestaticboolean verifyCertificate(Date date, Certificate certificate) {
boolean status = true;
try {
X509Certificate x509Certificate = (X509Certificate) certificate;
x509Certificate.checkValidity(date);
} catch (Exception e) {
status = false;
}
return status;
}

/**
* signature
* @param keyStorePath
* @param alias
* @param password
* @return
* @throws Exception
*/
publicstatic String sign(byte[] sign, String keyStorePath, String alias,
String password) throws Exception {
X509Certificate x509Certificate = (X509Certificate) getCertificate(
keyStorePath, alias, password);
KeyStore ks = getKeyStore(keyStorePath, password);
//get private key
PrivateKey privateKey = (PrivateKey) ks.getKey(alias,
password.toCharArray());

//generate signature object
Signature signature = Signature.getInstance(x509Certificate
.getSigAlgName());
signature.initSign(privateKey);
signature.update(sign);
return encryptBASE64(signature.sign());
}

/**
* verify the signature
* @param data
* @param sign
* @param certificatePath
* @return
* @throws Exception
*/
publicstaticboolean verify(byte[] data, String sign,
String certificatePath) throws Exception {
X509Certificate x509Certificate = (X509Certificate) getCertificate(certificatePath);
        //get public key
PublicKey publicKey = x509Certificate.getPublicKey();
//generate signature
Signature signature = Signature.getInstance(x509Certificate
.getSigAlgName());
signature.initVerify(publicKey);
signature.update(data);
return signature.verify(decryptBASE64(sign));
}

/**
* verify keystore
* @param keyStorePath
* @param alias
* @param password
* @return
*/
publicstaticboolean verifyCertificate(Date date, String keyStorePath,
String alias, String password) {
boolean status = true;
try {
Certificate certificate = getCertificate(keyStorePath, alias,
password);
status = verifyCertificate(date, certificate);
} catch (Exception e) {
status = false;
}
return status;
}

/**
* verify key store
* @param keyStorePath
* @param alias
* @param password
* @return
*/
publicstaticboolean verifyCertificate(String keyStorePath, String alias,
String password) {
return verifyCertificate(new Date(), keyStorePath, alias, password);
}

}

The test case will be as follow:
package com.sillycat.easycastle.encryption;

importstatic org.junit.Assert.assertArrayEquals;
importstatic org.junit.Assert.assertEquals;
importstatic org.junit.Assert.assertTrue;

import org.junit.Test;

publicclass CertificateCoderTest {

private String password = "123456";
private String alias = "www.sillycat.com";
private String certificatePath = "/Users/karl/work/easy/easycastle/src/main/resources/sillycat.cer";
private String keyStorePath = "/Users/karl/work/easy/easycastle/src/main/resources/sillycat.keystore";

@Test
publicvoid testPublic2Private() throws Exception {
System.out.println("\npublic key encrypt——private key decrypt\n");
String inputStr = "A new world will come at the end.";
byte[] data = inputStr.getBytes();
byte[] encrypt = CertificateCoder.encryptByPublicKey(data,
certificatePath);
byte[] decrypt = CertificateCoder.decryptByPrivateKey(encrypt,
keyStorePath, alias, password);
String outputStr = new String(decrypt);
String encryptStr = new String(encrypt);
System.out.println("data: " + inputStr);
System.out.println("decryption: " + outputStr);
System.out.println("encryption: " + encryptStr);
assertArrayEquals(data, decrypt);
// verify the cer file
assertTrue(CertificateCoder.verifyCertificate(certificatePath));
}

@Test
publicvoid testPrivate2Public() throws Exception {
System.out.println("\nprivate encryption——public decryption\n");
String inputStr = "what is the status?";
byte[] data = inputStr.getBytes();
byte[] encodedData = CertificateCoder.encryptByPrivateKey(data,
keyStorePath, alias, password);
byte[] decodedData = CertificateCoder.decryptByPublicKey(encodedData,
certificatePath);
String outputStr = new String(decodedData);
String encryptStr = new String(encodedData);
System.out.println("data: " + inputStr);
System.out.println("decryption: " + outputStr);
System.out.println("encryption: " + encryptStr);
assertEquals(inputStr, outputStr);
}

@Test
publicvoid testSign() throws Exception {
System.out.println("\nprivate sign——public verify signature\n");
String data = "It is rainy out side.";
// generate the sign
String sign = CertificateCoder.sign(data.getBytes(), keyStorePath, alias,
password);
System.out.println("signature:\r" + sign);
// verification
boolean status = CertificateCoder.verify(data.getBytes(), sign,
certificatePath);
System.out.println("status:\r" + status);
assertTrue(status);
}

}

references:
http://snowolf.iteye.com/blog/383412
http://snowolf.iteye.com/blog/391931
http://snowolf.iteye.com/blog/397693
http://snowolf.iteye.com/blog/398198


分享到:
评论

相关推荐

    java使用bouncycastle实现椭圆曲线(ECC)双向加密解密

    Bouncy Castle是一个强大的Java加密库,提供了对ECC的支持,包括密钥生成、加密解密等功能。下面我们将详细探讨如何使用Bouncy Castle库来实现ECC的双向加密解密。 1. **椭圆曲线加密原理**: 椭圆曲线加密算法...

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

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

    org.bouncycastle.jar

    解决org/bouncycastle/jce/provider/bouncycastlepr错误专用。

    BouncyCastle依赖.zip

    BouncyCastle是一个强大的Java安全库,它为加密、数字签名、证书处理以及许多其他安全功能提供了全面的支持。在Android开发中,BouncyCastle扮演着重要角色,特别是在处理SSL/TLS连接、加密通信以及生成和验证X.509...

    在线等待解决java tomcat 报错问题:java.lang.NoClassDefFoundError: javax/tools/StandardJavaF

    标题中的“java.lang.NoClassDefFoundError: javax/tools/StandardJavaFile”是一个常见的Java运行时错误,它表示在类路径中找不到某个类的定义。这个错误通常发生在试图执行包含特定类的代码,但该类在运行时环境中...

    org.bouncycastle完整资源包

    《深入解析org.bouncycastle:Java安全加密与证书权威库》 在Java开发中,安全性是不可或缺的一部分,尤其是在处理敏感数据、网络通信以及数字签名时。`org.bouncycastle`库是一个强大的开源加密库,为Java开发者...

    BouncyCastle.Crypto.dll 版本1.8.1

    **BouncyCastle.Crypto.dll** 是一个开源的加密库,主要为.NET Framework和.NET Core提供加密功能。在版本1.8.1中,这个库继续为开发者提供了广泛的密码学算法和安全服务。BouncyCastle 不仅限于.NET平台,它也支持...

    bouncycastle jar包

    **Bouncy Castle简介** Bouncy Castle是一个开源的Java加密库,提供了广泛的加密算法、协议实现以及相关的工具。这个jar包是专门为Java开发者设计的,它弥补了Java标准加密API(如JCE)在某些功能上的不足,使得...

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

    BouncyCastle.Crypto.dll 是一个专门用于加密和解密操作的动态链接库,适用于C#编程语言。这个版本1.8.6是在2020年2月21日发布,是BouncyCastle库的最新迭代,为开发者提供了强大的安全功能。 BouncyCastle库本身是...

    BouncyCastle.Crypto

    非对称加密,如RSA和ECC(椭圆曲线加密),在BouncyCastle中也得到良好支持。这类加密方式使用一对公钥和私钥,公钥可以公开,私钥必须保密,用于数字签名和密钥交换,确保了通信的机密性和身份验证。 3. **哈希...

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

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

    BouncyCastle.Crypto.dll

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

    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)等。...

    Bouncy Castle 1.64 API及制作工具

    Bouncy Castle 包含了密钥生成、导入和导出的工具,支持 PKCS#8 和 PKCS#12 格式。此外,它还支持密钥对的加密和解密,以保护密钥的安全存储。 6. **CMS(Cryptographic Message Syntax)** CMS 是一个标准,用于...

    最详细的bouncycastle的jar包

    asn1 crypto i18n jce math mozilla ocsp openssl tsp util voms x509

    BouncyCastle.Crypto.dll 1.8.2

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

Global site tag (gtag.js) - Google Analytics