java中将byte[]转换为PrivateKey进行数字签名

发布于 2024-12-20 10:37:02 字数 548 浏览 4 评论 0原文

我需要首先使用 SHA-1 摘要算法对字符串进行数字签名,然后应用 RSA 算法,使用 PrivateKey 对其进行签名。我已经将 PrivateKey 作为 base64 数据类型 char(250) 存储在我的数据库中。我的问题是,我不知道如何将其转换为 PrivateKey 以便使用它进行登录:

Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] cipherText = cipher.doFinal(digest);

Digest 是一个字节数组,我对其应用了 SHA-1 摘要算法:

MessageDigest md = MessageDigest.getInstance("SHA-1");
byte [] ba = cadena.getBytes();
byte [] digest  = md.digest(ba);

这是我想到的解决方案,但如果任何人有更好的解决方案我将不胜感激。

I need to digitally sign a String using the SHA-1 digest algorithm first and then apply the RSA algorithm, using a PrivateKey to sign it. I already have the PrivateKey stored in my database as data type char(250) in base64. My problem is that I don't know how to convert it into a PrivateKey for using it for signing in:

Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] cipherText = cipher.doFinal(digest);

Digest was an array of bytes to which I applied the SHA-1 digest algorithm:

MessageDigest md = MessageDigest.getInstance("SHA-1");
byte [] ba = cadena.getBytes();
byte [] digest  = md.digest(ba);

That is the solution I thought about, but if anyone has a better solution I would appreciate.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

琴流音 2024-12-27 10:37:02

我不知道你是如何将私钥保存到数据库中的。但是此页面提供了一些关于如何从文件系统加载KeyStore,并检索PrivatePublic密钥。

相关代码片段(根据您的要求进行修改)是,

   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();

I don't know how you persisted the private key into the DB. But this page provides some information on how to load a KeyStore from a file system, and retrieve the Private and Public keys.

Relevant code snippet (modified to suit your requirement) is,

   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);

and then,

   KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(PRIVATE_KEY_ALIAS, password);  
   PrivateKey privateKey = pkEntry.getPrivateKey();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文