javajwtsap-pijson-web-signature

JWS Signing with RSA 256 privatekey with Algorithm RSASSA-PKCS1-v1.5 SHA-256


I need some help with JWS Signing with RSA 256 privatekey -RSASSA-PKCS1-v1.5 SHA-256
I m working on SAP PI/PO.
I am unable to retrieve the RSA privatekey saved in server's OS folder, so I
am trying to pass the pem(base64 encoded) key as a string.
My requirement is to generate Header & payload & signed it.

Sample input Header:

{"alg": "RS256","kid": "asff1233dd"}

sample Json Payload:

{"CompInvoiceId": "0009699521","IssueDtm": "20220623"}<br />

Error: I am able to generate Header.payload in base64 url encode but the
signature part is getting corrupted when I convert the privatekey to
PKCS8encoding.
The generated JWS looks like:
eyJhbGciOiJSUzI1NiIsImtpZCI6Imh5d3kzaHIifQ.eyJDb21waW52b2ljZSI6IjAwOTk5MzMzI
iwic3VibWl0SWQiOiIxMjM0NSJ9.[B@42ace6ba
This is signature part which is getting corrupted - [B@42ace6ba
Kindly help with below code:
This is because of this declaration byte[] signed = null, when I remove
that it just throws
error as cannot find variable for signed.
Please help me with passing privatekey & signature.
The Java code I am working on:
I am passing :
Json data= data,
header = header
Privatekey in base64 = key

String jwsToken(String key, String data, String header, Container container) throws 
StreamTransformationException{
String tok = null;
byte[] signed = null;
try {
StringBuffer token = new StringBuffer();
//Encode the JWT Header and add it to our string to sign
token.append(Base64.getUrlEncoder().withoutPadding().encodeToString(header.getBytes("UTF- 
8")));
token.append(".");
//Encode the Json payload
token.append(Base64.getUrlEncoder().withoutPadding().encodeToString(data.getBytes("UTF-8")));
//Separate with a period
token.append(".");
//String signedPayload = 
Base64.getUrlEncoder().withoutPadding().encodeToString(signature.sign());
PrivateKey privatekey = null;
String privateKeyPEM = key;
//String key = new String(Files.readAllBytes(file.toPath()), Charset.defaultCharset());
byte[] decodePrivateKey = Base64.getDecoder().decode(key);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodePrivateKey);
privatekey = (PrivateKey) keyFactory.generatePrivate(keySpec);
Signature sig = Signature.getInstance( "SHA256withRSA" );
sig.initSign( ( PrivateKey ) privatekey );
sig.update(token.toString().getBytes("UTF-8"));
signed=sig.sign();
tok = (token.toString());
}
catch (Exception e) {
e.printStackTrace();
}
return tok;
}

Solution

  • Instead of appending byte array, encode it in base64 then append it

    signed = sig.sign(); token.append(Base64.getUrlEncoder().withoutPadding().encodeToString(signed));