How to decrypt JWE(Json Web Encryption) data using private key in java

21.6k views Asked by At

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

3

There are 3 answers

0
vuhoanghiep1993 On

This is what I use

    public String verifyAndDecrypt(String senderJws) throws ParseException, KeyStoreException, JOSEException, NoSuchAlgorithmException, UnrecoverableKeyException, JsonProcessingException {
    String paJson = null;
    JWSObject jwsObject = JWSObject.parse(senderJws);
    RSASSAVerifier verifier = new RSASSAVerifier(getPublicKeyFromString());

    if (jwsObject.verify(verifier)) {
        JWEObject jweObject = JWEObject.parse(jwsObject.getPayload().toString());
        JWEHeader jweHeader = (JWEHeader) jweObject.getHeader();
        RSADecrypter decrypter = getDecrypter();
        jweObject.decrypt(decrypter);
        if (jweObject.getState() == JWEObject.State.DECRYPTED) {
            paJson = jweObject.getPayload().toString();
        }

    }
    return paJson;
}



public RSAPublicKey getPublicKeyFromString() throws IOException, GeneralSecurityException {
    try {
        byte[] encoded = Base64.getDecoder().decode(certString); //certString is string not include ---BEGIN--- and ---END---
        InputStream certstream = new ByteArrayInputStream(encoded);
        Certificate certder = CertificateFactory.getInstance("X.509").generateCertificate(certstream);
        return (RSAPublicKey) certder.getPublicKey();
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
        throw e; 
    }
}

public RSAPrivateKey getMyPrivateKey() throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
    byte[] encoded = Base64.getDecoder().decode(privateKeyString);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
    RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(keySpec);
    return privKey;
}
1
FluffyDestroyerOfCode On

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();
0
aviad On

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);
}