我需要先使用 SHA-1 摘要算法对字符串进行数字签名,然后应用 RSA 算法,使用私钥对其进行签名。我已经将 PrivateKey 作为 base64 中的数据类型 char(250) 存储在我的数据库中。我的问题是我不知道如何将它转换成用于登录的私钥:
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] cipherText = cipher.doFinal(digest);
摘要是一个字节数组,我对其应用了 SHA-1 摘要算法:
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte [] ba = cadena.getBytes();
byte [] digest = md.digest(ba);
这是我想到的解决方案,但如果有人有更好的解决方案,我将不胜感激。
最佳答案
我不知道您是如何将私钥保存到数据库中的。但是this page提供了一些有关如何从文件系统加载 KeyStore
以及如何检索 Private
和 Public
key 的信息。
相关代码片段(根据您的要求进行了修改)是,
String password = ...;
KeyStore ks = KeyStore.getInstance(KEY_STORE_TYPE);
byte[] keyAsByteArray = ...; // The key persisted in the DB
InputStream keyStream = new ByteArrayInputStream(keyAsByteArray);
ks.load(keyStream, password);
然后,
KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(PRIVATE_KEY_ALIAS, password);
PrivateKey privateKey = pkEntry.getPrivateKey();
关于java - 将byte []转换为java中的PrivateKey以进行数字签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8438857/