在java中将byte 转换为PrivateKey以进行数字签名

我需要先使用SHA-1摘要算法对String进行数字签名,然后应用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); 

这是我想到的解决方案,但如果有人有更好的解决方案我会很感激。

我不知道你是如何将私钥保存到数据库中的。 但是此页面提供了有关如何从文件系统加载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();