У меня уже есть закрытый ключ, который хранится в базе данных как varchar2 и хранится в переменной с именем Key, как показано в коде.
Ниже приведен мой фрагмент кода для установки этого закрытого ключа на JsonWebSignature, но я получаю сообщение об ошибке типа
The method setKey(Key) in the type JsonWebStructure is not applicable for the arguments (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;
}




Ты сделаешь:
String key = "jxFd%asdjd";
....
jws.setKey(key);// Getting error here
Подпись метода setKey - public void setKey (ключ ключа)
Поэтому вам нужно передать ему Ключ. Вы передаете ему String, поэтому он не компилируется. Вам нужно сделать ключ из своей строки.
Хотя не знаю, как это сделать.
Обновлено:
Думаю, вы могли бы сделать что-то в этом роде:
String keyString = "jxFd%asdjd";
PublicJsonWebKey originalKey = PublicJsonWebKey.Factory.newPublicJwk(keyString);
JsonWebSignature jws = new JsonWebSignature();
jws.setKey(originalKey.getPrivateKey());
Но это не сработает, поскольку метод newPublicJwk ожидает строку JSON. Вы получили свой ключ из строки JSON?
Пробовал с тем же: - String key = "jxFd% asdjd"; byte [] decodedKey = Base64.getDecoder (). decode (ключ); SecretKey originalKey = новый SecretKeySpec (decodedKey, 0, decodedKey.length, «HS256»);
Получение исключения: исключение в потоке "main" java.lang.IllegalArgumentException: недопустимый символ base64 в byte [] decodedKey = Base64.getDecoder (). Decode (key);
ваша строка не является допустимой строкой Base64. Смотрите мою последнюю правку, вы взяли ключ из какого-то JSON?
У меня есть решение моей проблемы. Ниже мой фрагмент кода, где «ключ» - «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;
}
Строковый ключ = "jxFd% asdjd"; Это ключ, который я хочу установить