I am trying to encode a message with SH1 RSA
but I have no experience with security subject except some base information about RSA
. I have been given a private key as String
. I have managed to write following code block to do the job but I am not sure if I am doing the job securely and correctly.
I am not an expert but putting my private key as String in code is not secure I guess. Can anyone guide me?
String privateKeyString = "mykeyhere...";
byte[] privateKeyBytes = privateKeyString.getBytes();
String encodedPrivateKey = Base64.encodeToString(privateKeyBytes, Base64.URL_SAFE);
KeyFactory factory = KeyFactory.getInstance(RSA);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedPrivateKey.getBytes());
RSAPrivateKey privateKey = (RSAPrivateKey) factory.generatePrivate(keySpec);
Signature instance = Signature.getInstance(ALGORITHM);
instance.initSign(privateKey);
instance.update(content.getBytes());
return new String(instance.sign());
My private key is in form as:
"-----BEGIN PRIVATE KEY-----\n"+
"MIIE...\n"+
"cH0iRj...\n"+
"O0Hhj...\n"+
.
.
.
"fG6...\n"+
"B6/hF...\n"+
"3Mq38...\n"+
"-----END PRIVATE KEY-----\n"
Your key format is an unencrypted base64-encoded PKCS8-encoded private key. Here is an example of how to decode it into a private key. (Don't worry about the security of the private key in this example, it is just a throwaway for the example).