简体   繁体   中英

BouncyCastle weird characters in signed String

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á!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM