`
jguangyou
  • 浏览: 368995 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

keystore提取私钥和证书

 
阅读更多

keytool -genkey -alias test -keyalg RSA -keystore c:/key.store

生成keyStore

RSA是一个既能用于数据加密也能用于数字签名的算法。

DSA(Digital Signature Algorithm,数字签名算法,用作数字签名标准的一部分),它是另一种公开密钥算法,它不能用作加密,只用作数字签名。DSA使用公开密钥,为接受者验证数据的完整性和数据发送者的身份。

提取证书:

通过keytool命令我们可以很轻松的提取证书.

证书包括主体信息,公钥.

keytool -export -alias 别名 -keystore 文件名 -file 证书名称

 

但是我们无法通过KEYTOOL工具来提取私钥的..我们只能通过java的KeyStore类getEntry() 或者getKey()来提取私钥.

 

读取keyStore文件:

char[] password = "password".toCharArray();

java.io.FileInputStream fis = new java.io.FileInputStream("c:/server/server_keystore");

// 从指定的输入流中加载此 KeyStore
ks.load(fis, password);
//keystore 中的每一项都用“别名”字符串标识。

//使用指定保护参数获取指定别名的 keystore Entry

//KeyStore.PrivateKeyEntry 保存 PrivateKey 和相应证书链的 KeyStore 项。

方法1. KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(
"keystore别名",
new KeyStore.PasswordProtection(
password));

 

// 返回与给定别名相关联的密钥

方法2. PrivateKey key = (PrivateKey) ks.getKey("ser", password);

怎么来验证提取的私钥是否正确呢?(因为公钥私钥必须成对出现,我们可以通过证书提取去公钥,然后用公钥加密,使用刚刚获得的私钥解密)

 

提取证书的方法:

keytool -export -alias 别名 -keystore 文件名 -file 证书名称

//通过证书,获取公钥


CertificateFactory cf = CertificateFactory.getInstance("X.509");
FileInputStream in = new FileInputStream("C:\\server\\server.cer");

//生成一个证书对象并使用从输入流 inStream 中读取的数据对它进行初始化。
Certificate c = cf.generateCertificate(in);
PublicKey publicKey = c.getPublicKey();

 

 

//通过下面这段代码提取的私钥是否正确

String before = "asdf";
byte[] plainText = before.getBytes("UTF-8");
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
// 用公钥进行加密,返回一个字节流
byte[] cipherText = cipher.doFinal(plainText);
cipher.init(Cipher.DECRYPT_MODE, myPrivateKey);
// 用私钥进行解密,返回一个字节流
byte[] newPlainText = cipher.doFinal(cipherText);
System.out.println(new String(newPlainText, "UTF-8"));

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics