Converting a byte [] to PrivateKey in java for digital signature

[亡魂溺海] 提交于 2019-12-05 10:06:59

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/8438857/converting-a-byte-to-privatekey-in-java-for-digital-signature

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!