我试图实现的是使用已经提供的私钥和证书对消息进行签名,该消息要发送到某个需要确保消息来自我的地方(私钥签名而公钥加密)。
如果你已经有了。key文件和。crt文件?
试试这个:
步骤1:将密钥和证书转换为.p12文件
openssl pkcs12 -export -in certificate.crt -inkey privateKey.key -name alias -out yourconvertedfile.p12
步骤2:导入密钥并使用单个命令创建.jsk文件
keytool -importkeystore -deststorepass changeit -destkeystore keystore.jks -srckeystore umeme.p12 -srcstoretype PKCS12
步骤3:在java中:
char[] keyPassword = "changeit".toCharArray();
KeyStore keyStore = KeyStore.getInstance("JKS");
InputStream keyStoreData = new FileInputStream("keystore.jks");
keyStore.load(keyStoreData, keyPassword);
KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(keyPassword);
KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)keyStore.getEntry("alias", entryPassword);
System.out.println(privateKeyEntry.toString());
如果你需要用这个键给某个字符串签名,请执行以下操作:
步骤1:转换要加密的文本
byte[] data = "test".getBytes("UTF8");
步骤2:获取base64编码的私钥
keyStore.load(keyStoreData, keyPassword);
//get cert, pubkey and private key from the store by alias
Certificate cert = keyStore.getCertificate("localhost");
PublicKey publicKey = cert.getPublicKey();
KeyPair keyPair = new KeyPair(publicKey, (PrivateKey) key);
//sign with this alg
Signature sig = Signature.getInstance("SHA1WithRSA");
sig.initSign(keyPair.getPrivate());
sig.update(data);
byte[] signatureBytes = sig.sign();
System.out.println("Signature:" + Base64.getEncoder().encodeToString(signatureBytes));
sig.initVerify(keyPair.getPublic());
sig.update(data);
System.out.println(sig.verify(signatureBytes));
引用:
如何在Java密钥存储库中导入现有的x509证书和私钥以用于SSL?
http://tutorials.jenkov.com/java-cryptography/keystore.html
http://www.java2s.com/Code/Java/Security/RetrievingaKeyPairfromaKeyStore.htm
如何签署字符串与私钥
最后的程序
public static void main(String[] args) throws Exception {
byte[] data = "test".getBytes("UTF8");
// load keystore
char[] keyPassword = "changeit".toCharArray();
KeyStore keyStore = KeyStore.getInstance("JKS");
//System.getProperty("user.dir") + "" < for a file in particular path
InputStream keyStoreData = new FileInputStream("keystore.jks");
keyStore.load(keyStoreData, keyPassword);
Key key = keyStore.getKey("localhost", keyPassword);
Certificate cert = keyStore.getCertificate("localhost");
PublicKey publicKey = cert.getPublicKey();
KeyPair keyPair = new KeyPair(publicKey, (PrivateKey) key);
Signature sig = Signature.getInstance("SHA1WithRSA");
sig.initSign(keyPair.getPrivate());
sig.update(data);
byte[] signatureBytes = sig.sign();
System.out.println("Signature:" + Base64.getEncoder().encodeToString(signatureBytes));
sig.initVerify(keyPair.getPublic());
sig.update(data);
System.out.println(sig.verify(signatureBytes));
}