Skip to content

Instantly share code, notes, and snippets.

@fungiboletus
Created October 23, 2018 12:23
Show Gist options
  • Save fungiboletus/3e61377ecfff87ab83dc6b609437c4f9 to your computer and use it in GitHub Desktop.
Save fungiboletus/3e61377ecfff87ab83dc6b609437c4f9 to your computer and use it in GitHub Desktop.
How to make a RSA JWE JWT JOSE whatever encrypted thing in Java
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.Date;
import java.util.UUID;
import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.RSAEncrypter;
import com.nimbusds.jwt.EncryptedJWT;
import com.nimbusds.jwt.JWTClaimsSet;
public class Main {
public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, JOSEException {
System.out.println("I don't like Java very much");
byte[] fuckit = Files.readAllBytes(Paths.get("public_key.der"));
X509EncodedKeySpec spec =
new X509EncodedKeySpec(fuckit);
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPublicKey toto = (RSAPublicKey) kf.generatePublic(spec);
JWEEncrypter encrypter = new RSAEncrypter(toto);
Date now = new Date();
JWTClaimsSet jwtClaims = new JWTClaimsSet.Builder()
// Optional string, can be used on the client to check stuff
.issuer("https://perdu.com")
// Optional string, subject like subject of an email, boring and useless
.subject("truc chiant")
// Optional list of recipients. Can be strings or urls. Interpretation is application specific.
// If it doesn't match, the jwt must be rejected but it's optional so who cares...
.audience(Arrays.asList("https://example.net/"))
// Optional expiration time
.expirationTime(new Date(now.getTime() + 1000*60*10)) // expires in 10 minutes
// Optional not before time
.notBeforeTime(now)
// Optional issued at
.issueTime(now)
// optional JWT id, must be unique if used
.jwtID(UUID.randomUUID().toString())
// Finally our crap
.claim("token", "prout")
.build();
JWEHeader header = new JWEHeader(JWEAlgorithm.RSA_OAEP_256, EncryptionMethod.A256GCM);
EncryptedJWT jwt = new EncryptedJWT(header, jwtClaims);
jwt.encrypt(encrypter);
String jwtString = jwt.serialize();
System.out.println(jwtString);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment