将字节[]转换为Java中的PrivateKey以进行数字签名 [英] Converting a byte [] to PrivateKey in java for digital signature

查看:192
本文介绍了将字节[]转换为Java中的PrivateKey以进行数字签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

摘要是我应用SHA-1摘要算法的字节数组:

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.

推荐答案

我不知道您如何将私钥持久保存到数据库中.但是此页面提供了有关如何从文件系统加载KeyStore,以及如何检索PrivatePublic键.

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

然后

   KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(PRIVATE_KEY_ALIAS, password);  
   PrivateKey privateKey = pkEntry.getPrivateKey();

这篇关于将字节[]转换为Java中的PrivateKey以进行数字签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆