`
sillycat
  • 浏览: 2487470 次
  • 性别: 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


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics