Reputation: 364
I'm trying to sign a string using BouncyCastle library. My code works, but the resulting string is full of weird characters and my instinct says something is wrong about it. My code looks like this
Security.addProvider(new BouncyCastleProvider());
FileReader fileReader = new FileReader(new File("certs/private.pem"));
PEMReader r = new PEMReader(fileReader);
PrivateKey privateKey = (PrivateKey) r.readObject();
r.close()
String toSign = "hello world";
Signature signature = Signature.getInstance("SHA1withRSA","BC");
signature.initSign(privateKey);
signature.update(toSign.getBytes("UTF-8"));
byte[] signedArray = signature.sign();
String signedString = new String(signedArray, "UTF-8");
And the resulting string (signedString) looks (awfully) like this:
�����jc.������c�1�#�ٶ����E8����a��f8���t�~W�{%��\Z#��it��ҽ;�n��k�n{U>&�d�_���&�?�N��g� z\�k�g���e~�S4��ƎG�g��U�:��s>i�%YL�n3�����Y��9����T���}�Usb���&�����eշѾUr�Y�ڝ[j�h~mu\3U��j���c�U�ac����t��No-��1J�B]�
The private.pem was generated with this command
openssl req -new -x509 -days 3652 -nodes -out private.crt -keyout private.pem.
Any help or hint will be very appreciated.
SOLVED
What I did was to encode de byte array to Base64 using this line
byte[] encodedArray = org.bouncycastle.util.encoders.Base64.encode(signedArray);
and voalá!
Upvotes: 0
Views: 422
Reputation: 15693
Your signature is a byte[]
, it is not a string. Attempting to treat a byte array as a string gives you what you have found. Either retain and store the signature as a byte array, or else convert the byte array to a string-compatible format, such as Base64. Java 8 contains the Base64
class which will do the conversion for you. If you do use Base64, then remember to convert back to bytes before checking the signature.
Upvotes: 2