Converting a byte [] to PrivateKey in java for dig

2019-04-02 16:56发布

问题:

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