我有一对公钥和私钥以及我的证书。那些在 OpenSSL 中创建的(为什么?因为我被要求在 OpenSSL 中创建)。现在我想用这些东西来制作一个使用数字签名的 Java 应用程序。如何使用我的私钥和公钥来加密/解密信息(并使用证书来查看数据是否有效?Java 中有哪些类允许我这样做?
我的密钥是这样的纯文本:
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDuyg3h0VbP9iZ6RCxSU6x4WX4
anAwedMVUTqF0WHlvHl1Kiqa6N6TiUk23uXAVUX8RwLFjXWHlG0xwW7mGByA2mX9
5oPQpQFu8C70aMuUotGv87iiLi0UKCZV+9wS9rMdg5LHu1mMPilwgOO6MlyTxKem
-----END PUBLIC KEY-----
更新
我制作了这段代码,但仍然无法使用私钥对字符串进行签名。
public void encryptHash(String hashToEncrypt, String pathOfKey, String Algorithm) {
FileInputStream fis = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len;
File f = new File(pathOfKey);
fis = new FileInputStream(pathOfKey);
len = 0;
while((len = fis.read()) != -1){
baos.write(len);
}
KeyFactory kf = KeyFactory.getInstance(Algorithm); //Algorithm = "RSA"
KeySpec keySpec = new PKCS8EncodedKeySpec(baos.toByteArray());
baos.close();
PrivateKey privateKey = kf.generatePrivate(keySpec); //Here's the exception thrown
Signature rsaSigner = Signature.getInstance("SHA1withRSA");
rsaSigner.initSign(privateKey);
fis = new FileInputStream(hashToEncrypt);
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] buffer = new byte[1024];
len = 0;
while((len = bis.read(buffer)) >= 0){
try {
rsaSigner.update(buffer, 0, len);
} catch (SignatureException ex) {
Logger.getLogger(DataEncryptor.class.getName()).log(Level.SEVERE, null, ex);
}
}
bis.close();
byte[] signature = rsaSigner.sign();
System.out.println(new String(signature));
}
我得到的例外是
dic 09, 2011 12:49:02 PM firmaelectronica.DataEncryptor encryptHash
Grave: null
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : DER input, Integer tag error
at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:217)
at java.security.KeyFactory.generatePrivate(KeyFactory.java:372)
at firmaelectronica.DataEncryptor.encryptHash(DataEncryptor.java:40)
at firmaelectronica.FirmaElectronica.main(FirmaElectronica.java:39)
Caused by: java.security.InvalidKeyException: IOException : DER input, Integer tag error
at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:361)
at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:367)
at sun.security.rsa.RSAPrivateCrtKeyImpl.<init>(RSAPrivateCrtKeyImpl.java:91)
at sun.security.rsa.RSAPrivateCrtKeyImpl.newKey(RSAPrivateCrtKeyImpl.java:75)
at sun.security.rsa.RSAKeyFactory.generatePrivate(RSAKeyFactory.java:316)
at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:213)
... 3 more