4

I have a private key similar to below

e.g.

-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDGBRdsiDqKPGyH
gOpzxmSU2EQkm+zYZLvlPlwkwyfFWLndFLZ3saxJS+LIixsFhunrrUT9ZZ0x+bB6
MV55o70z4ABOJRFNWx1wbMGqdiC0Fyfpwad3iYpRVjZO+5etHA9JEoaTPoFxv+kt
QwBjBRAJ3Y5jtrESprGdUFRb0oavDHuBtWUt2XmXspWgtRn1xC8sXZExDdxmJRPA
ADTO3rrGo9hicG/WKGzSHD5l1f+IO1SfmUN/6i2JjcnE07eYArNrCfbMgkFavj50
2ne2fSaYM4p0o147O9Ty8jCyY9vuh/ZGid6qUe3TBI6/okWfmYw6FVbRpNfVEeG7
kPfkDW/JdH7qkWTFbh3eH1k=
-----END PRIVATE KEY-----

I have a JWE data as below which was encrypted using the public key generated from above private key/certificate

aaaaa.bbbbb.ccccc.ddddd.eeeee

Can someone give me java code I can use to decrypt this JWE using my private key? I cannot find a clear answer from internet. I am kind if new to this JWE concept

Roshanck
  • 2,220
  • 8
  • 41
  • 56

2 Answers2

3

Due to your other question and tags to this question, I assume you chose the library Nimbus JOSE + JWT. Regardless of your Framework for JWT, I advise you to use the provided way to encrypt/decrypt your tokens, because they validate the structure of the token.

RSAPrivateKey privateKey; //initialize with your key
String jwtTokenAsString = "aaaaa.bbbbb.ccccc.ddddd.eeeee"; //your token
EncryptedJWT encryptedJWT = EncryptedJWT.parse(jwtTokenAsString);
RSADecrypter decrypter = new RSADecrypter(privateKey);
encryptedJWT.decrypt(decrypter);

//Access content with diffrent methods
JWTClaimsSet claims = encryptedJWT.getJWTClaimsSet();
Payload payload = encryptedJWT.getPayload();
  • 1
    Can you explain more with your first line `RSAPrivateKey privateKey; //initialize with your key`? – tnkh May 19 '21 at 08:06
1

Something to get you started with:

public static void main(String[] args) throws Exception
{
    Key privateKey = KeyFactory
            .getInstance("RSA")
            .generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode("your base64 private key")));

    Cipher decrypt = Cipher.getInstance("RSA/ECB/PKCS1Padding");

    decrypt.init(Cipher.DECRYPT_MODE, privateKey, new IvParameterSpec(Base64.getDecoder().decode("ccccc")));

    String decryptedMessage = new String(decrypt.doFinal(Base64.getDecoder().decode("ddddd")), StandardCharsets.UTF_8);
}
aviad
  • 1,553
  • 12
  • 15