How to generate JWT-Signature using RSA256 algorithm? - java

I have a PrivateKey and a PublicKey and use the privateKey to init Signature and publicKey to verify the Signature:
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
// decode public key
X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(pubKeyBytes);
RSAPublicKey pubKey = (RSAPublicKey)
keyFactory.generatePublic(publicSpec);
//decode private key
PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(prvKeyBytes);
RSAPrivateKey privKey = (RSAPrivateKey)
keyFactory.generatePrivate(privSpec);
//header and body Base64 decoded value
String headerString = mapper.writeValueAsString(header);
String headerEncoded =
Base64.getUrlEncoder().encodeToString(headerString.getBytes());
String payloadString = mapper.writeValueAsString(payload);
String payloadEncoded =
Base64.getUrlEncoder().encodeToString(payloadString.getBytes());
String tempAccessToken = hearderEncoded+"."+payloadString;
Signature sign = Signature.getInstance("SHA256withRSA");
sign.initSign(privKey);
sign.update(tempAccessToken.getBytes("UTF-8"));
byte[] signatureBytes = sign.sign();
sign.initVerify(pubKey);
sign.update(tempAccessToken.getBytes("UTF-8"));
String jsonToken = Base64.getUrlEncoder().encodeToString(signatureBytes);
String JWTtoken = tempAccessToken + "." + jsonToken;
finally I get the JWT token below (dummy value):
eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiI4MzliN2NhNC02MDE1LTQ0OWQtOGZiNi02jkyYzk1Ny1jYTNjLTQyMWQtOTk2zY2VkNTAzZGViNWYiLCJleHAiOjE1MzIwMDQwMTcsImF1ZCI6ImFjY291bnQtZC5kb2N1c2lnbi5jb20iLzY29wZSI6InNpZ25hdHVyZSBpbXBlcnNvbmF0aW9uIn0=.YNZzR0HgPWFm4dXMMHn3czEDRukYUB0Hyw7YP_BGY2dniIMqpH4Ctz5EEHcHrNT_mGImcp026w-isYgv56TTugYnkcAs8HH0YXa1Ey0skdjVYoZHdeyPC8Ci9xeOQF9wf4VjrBboaRxWkVXfngOHHewpV42NcaXxwmGlresWukHVmmjbFokd1Cm5BJKVhVlsZWuftcJlC3XoO9REjaZX78YTY9S5bpXmsZBYr20wHsWJrkP9EWGf7WSGHVXGBJfCpvOTZDC8_4B12ToD_RKjk6n5s8-F7X54KY4kx6Gg7xnk55vDw==
I'm not able to get the accessToken using this JWT Token. I will get the response instead:
"error" :"invalid_request";
NOTE: I am using this JWT token to get the access token for DocuSign Application.

Related

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.eyJDb21waW52b2ljZSI6IjAwOTk5MzMzIiwic3VibWl0SWQiOiIxMjM0NSJ9.[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 throwserror 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;
}
Instead of appending byte array, encode it in base64 then append it
signed = sig.sign();
token.append(Base64.getUrlEncoder().withoutPadding().encodeToString(signed));

Java: Converting between Key type and String

Is it possible to take a public key that I have generated, convert it into a string, reverse the process and use it as a key again?
generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048);
KeyPair keyPair = generator.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
Then convert this to a string:
String public = someMethod(publicKey)
and then Reverse it at a later time:
RSAPublicKey newPublicKey = someMethod(public)
You can convert the Public Key to a String as follows.
String publicKeyString = Base64.getEncoder().encodeToString(publicKey.getEncoded());
Then that String can be converted back to a public key as follows.
byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyString);
X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey2 = keyFactory.generatePublic(spec);

how to convert a String to an ECDH PublicKey and check its connectness

I'm using Java with Bouncy Castle to convert a server-side string_1 to ECDH PublicKey, then convert the PublicKey to string_2 to check the code's correctness, but string_1 and string_2 are different and I don't know where's wrong.
String key ="BJNiB1+k2n2hiYZccfwGE87mbo5+29l+PFfKzO72tvDmXCAT4QtxqqgX2vUi5go1+MpjJCFyBmIfv5jcsOo9fo3cd/v2jwZAyh2IHh7NHWkA6PFip6el2rNfvyNCd5eN6Q==";
System.out.println("server key:" + key);
byte[] keyBytes = Base64.decodeBase64(key.getBytes("utf-8"));
ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("secp384r1");
KeyFactory kf = KeyFactory.getInstance("ECDH", new BouncyCastleProvider());
ECNamedCurveSpec params = new ECNamedCurveSpec("secp384r1", spec.getCurve(), spec.getG(), spec.getN());
ECPoint point = ECPointUtil.decodePoint(params.getCurve(), keyBytes);
ECPublicKeySpec pubKeySpec1 = new ECPublicKeySpec(point, params);
PublicKey pk = kf.generatePublic(pubKeySpec1);
System.out.println("convert Key*: " + Base64.encodeBase64String(pk.getEncoded()));
The server key and convert key are different, can't find the reason, need help!
server key:BJNiB1+k2n2hiYZccfwGE87mbo5+29l+PFfKzO72tvDmXCAT4QtxqqgX2vUi5go1+MpjJCFyBmIfv5jcsOo9fo3cd/v2jwZAyh2IHh7NHWkA6PFip6el2rNfvyNCd5eN6Q==
convert Key*: MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEk2IHX6TafaGJhlxx/AYTzuZujn7b2X48V8rM7va28OZcIBPhC3GqqBfa9SLmCjX4ymMkIXIGYh+/mNyw6j1+jdx3+/aPBkDKHYgeHs0daQDo8WKnp6Xas1+/I0J3l43p

How to generate Private key from string using BouncyCastle

I have a String stored in a variable:
-----BEGIN RSA PUBLIC KEY-----
MIGHAoGBANAahj75ZIz9nXqW2H83nGcUao4wNyYZ9Z1kiNTUYQl7ob/RBmDzs5rY
mUahXAg0qyS7+a55eU/csShf5ATGzAXv+DDPcz8HrSTcHMEFpuyYooX6PrIZ07Ma
XtsJ2J4mhlySI5uOZVRDoaFY53MPQx5gud2quDz759IN/0gnDEEVAgED
-----END RSA PUBLIC KEY-----
I generate public key as:
public static PublicKey getFromString(String keystr) throws Exception
{
//String S1= asciiToHex(keystr);
byte[] keyBytes = new sun.misc.BASE64Decoder().decodeBuffer(keystr);
ASN1InputStream in = new ASN1InputStream(keyBytes);
DERObject obj = in.readObject();
RSAPublicKeyStructure pStruct = RSAPublicKeyStructure.getInstance(obj);
RSAPublicKeySpec spec = new RSAPublicKeySpec(pStrcut.getModulus(), pStruct.getPublicExponent());
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
How to generate the PrivateKey using bouncy castle in android
{Edit}
Without using bouncy castle i am generating private key like this:
public static PrivateKey getKey(String mKey){
try{
// Read in the key into a String
StringBuilder pkcs8Lines = new StringBuilder();
BufferedReader rdr = new BufferedReader(new StringReader(mKey));
String line;
while ((line = rdr.readLine()) != null) {
pkcs8Lines.append(line);
}
// Remove the "BEGIN" and "END" lines, as well as any whitespace
String pkcs8Pem = pkcs8Lines.toString();
pkcs8Pem = pkcs8Pem.replace("-----BEGIN RSA PRIVATE KEY-----", "");
pkcs8Pem = pkcs8Pem.replace("-----END RSA PRIVATE KEY-----", "");
pkcs8Pem = pkcs8Pem.replaceAll("\\s+","");
// Base64 decode the result
byte [] pkcs8EncodedBytes = Base64.decode(pkcs8Pem, Base64.DEFAULT);
// extract the private key
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey privKey = kf.generatePrivate(keySpec);
System.out.println(privKey);
return privKey;
}catch (Exception ex){
ex.printStackTrace();
}
return null;
}
I want to achieve the same using Bouncy Castle
I'm a little confused on why you insist on using bouncycastle, but if you really want to use bouncycastle then the CMS/PKIX library has a nice helper class called PEMParser that will shorten the code needed, e.g:
public static PrivateKey getPemPrivateKey(String mKey) throws Exception {
PEMParser pemParser = new PEMParser(new StringReader(mKey));
final PEMKeyPair pemKeyPair = (PEMKeyPair) pemParser.readObject();
final byte[] encoded = pemKeyPair.getPrivateKeyInfo().getEncoded();
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(new PKCS8EncodedKeySpec(encoded));
}

String to Public key using Base64.getEncoder() [duplicate]

I've used the following code to convert the public and private key to a string
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(2048);
KeyPair keyPair = keyPairGen.genKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
String publicK = Base64.encodeBase64String(publicKey.getEncoded());
String privateK = Base64.encodeBase64String(privateKey.getEncoded());
Now I'm trying to convert it back to public ad private key
PublicKey publicDecoded = Base64.decodeBase64(publicK);
I'm getting error of cannot convert from byte[] to public key. So I tried like this
PublicKey publicDecoded = new SecretKeySpec(Base64.decodeBase64(publicK),"RSA");
This leads to error like below
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: Neither a public nor a private key
Looks like I'm doing wrong key conversion here. Any help would be appreciated.
I don't think you can use the SecretKeySpec with RSA.
This should do:
byte[] publicBytes = Base64.decodeBase64(publicK);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(keySpec);
And to decode the private use PKCS8EncodedKeySpec

Categories