如何将String转换为私钥并将其设置为JsonWebSignature

时间:2018-09-26 08:42:03

标签: java jwt jose4j

我已经有一个私钥,以varchar2的形式存储在数据库中,并存储在名为Key的变量中,如代码所示。 下面是我的代码,用于将此私钥设置为JsonWebSignature,但出现类似错误

  

JsonWebStructure类型的setKey(Key)方法不适用于参数(String)

我不想生成一个新的RSA密钥,因为我已经有了它。

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 个答案:

答案 0 :(得分:0)

您这样做:

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

setKey方法的签名为public void setKey(Key key) 因此,您需要将其传递给Key。您正在为它传递一个字符串,因此它不会编译。您需要使用字符串制作一个键。

虽然不确定如何执行此操作。

编辑:

我想您可以按照以下方式做些事情:

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

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

但是,由于newPublicJwk方法需要JSON字符串,因此无法使用。您是否从JSON字符串中获取了密钥?

答案 1 :(得分:0)

我已经解决了我的问题。下面是我的代码段,其中“键”是“ RSAPrivateKey”。
公共静态字符串getJWTToken(String userName)抛出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;
}