How to convert String to Private Key and set it to JsonWebSignature

2.7k views Asked by At

I already have a private key stored in a database as varchar2 and stored in a variable named Key as shown in code. Below is my piece of code to set this private key to JsonWebSignature but I am getting an error like

The method setKey(Key) in the type JsonWebStructure is not applicable for the arguments (String)

I don't want to generate a new RSA key as I already have it.

public static String getJWTToken(String userName) throws JoseException {

    JwtClaims claims = new JwtClaims();
    claims.setAudience(Constants.AUDIENCE);
    claims.setIssuer(InitialLoader.JWT_KEY);//Getting from config property file
    claims.setIssuedAtToNow();      
    NumericDate tokenExpDate = NumericDate.now();
    tokenExpDate.addSeconds(Constants.SECONDS);
    claims.setExpirationTime(tokenExpDate);

    if(userName!=null && !userName.isEmpty())
        claims.setClaim("userName", userName);

    System.out.println("Senders end :: " + claims.toJson());

    // SIGNING the token
    String key = "jxFd%asdjd";
    RsaJsonWebKey jsonSignKey = RsaJwkGenerator.generateJwk(2048);
    JsonWebSignature jws = new JsonWebSignature();
    //jws.setKey(jsonSignKey.getPrivateKey());
    jws.setKey(key);// Getting error here
    jws.setPayload(claims.toJson());
    jws.setHeader("typ", Constants.TYP);
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);// Setting the algorithm to be used
    String signedJwt = jws.getCompactSerialization();// payload is signed using this compactSerialization
    System.out.println("Signed key for sender is::" + signedJwt);

    return signedJwt;
}
2

There are 2 answers

3
Bentaye On

You do:

String key = "jxFd%asdjd";
....
jws.setKey(key);// Getting error here

The signature of the setKey method is public void setKey(Key key) So you need to pass it a Key. You are passing it a String so it won't compile. You need to make a Key out of your String.

Not sure how to do that though.

EDIT:

I guess you could do something along these lines:

String keyString = "jxFd%asdjd";
PublicJsonWebKey originalKey = PublicJsonWebKey.Factory.newPublicJwk(keyString);

JsonWebSignature jws = new JsonWebSignature();
jws.setKey(originalKey.getPrivateKey());

But that won't work as the newPublicJwk method is expecting a JSON string. Did you get your key out of a JSON String?

0
rahul kumar On

I have got the solution to my problem. Below is my piece of code where "key" is "RSAPrivateKey".
public static String getJWTToken(String userName) throws JoseException {

    JwtClaims claims = new JwtClaims();
    claims.setAudience(Constants.AUDIENCE);
    claims.setIssuer(InitialLoader.JWT_KEY);
    claims.setIssuedAtToNow();      
    NumericDate tokenExpDate = NumericDate.now();
    tokenExpDate.addSeconds(Constants.SECONDS);
    claims.setExpirationTime(tokenExpDate);

    if(userName!=null && !userName.isEmpty())
        claims.setClaim("userName", userName);

    System.out.println("Senders end :: " + claims.toJson());

    // SIGNING the token
    PrivateKey privateKey = null;
    try {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        System.out.println("InitialLoader.RSAPrivateKey is::"+InitialLoader.RSAPrivateKey);
        byte[] content = Files.readAllBytes(Paths.get(InitialLoader.RSAPrivateKey));//from config file

        String pkcs8Pem = new String(content, StandardCharsets.UTF_8);
        byte[] pkcs8EncodedBytes = org.apache.commons.codec.binary.Base64.decodeBase64(pkcs8Pem);
        KeyFactory factory = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
        privateKey = factory.generatePrivate(privKeySpec);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvalidKeySpecException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    JsonWebSignature jws = new JsonWebSignature();
    jws.setKey(privateKey);
    jws.setPayload(claims.toJson());
    jws.setHeader("typ", Constants.TYP);
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);// Setting the algorithm to be used
    String signedJwt = jws.getCompactSerialization();// payload is signed using this compactSerialization
    System.out.println("Signed key for sender is::" + signedJwt);

    return signedJwt;
}