我需要将RSA PublicKey转换为有效的JWK。尤其是JWK的值“n”和“e”是我正在努力解决的值。在https://tools.ietf.org/html/rfc7517#page-25上查看示例JWK时,编码似乎不正确

目前,我的代码基本上如下所示:

private Map<String, Object> generateJWK(PublicKey publicKey){

    RSAPublicKey rsa = (RSAPublicKey) publicKey;

    Map<String, Object> values = new HashMap<>();

    values.put("kty", rsa.getAlgorithm()); // getAlgorithm() returns kty not algorithm
    values.put("kid", "someuniqueid");
    values.put("n", Base64.encode(rsa.getModulus().toString()));
    values.put("e", Base64.encode(rsa.getPublicExponent().toString()));
    values.put("alg", "RS256");
    values.put("use", "sig");

    return values;
}

但是,输出似乎未正确编码或类似,例如e看起来像这样:NjU1Mzc=n不包含特殊字符,例如-_+。 :
jMzk1MNT0xTk2NED1xzzgNyQ00IykADzMAM0c0wz0M0MONj2z5TgNzI3yAM0OONYzzMjzwNzDxgAzxDxzMMAjTwNNDYMINMgNQDOEAkIM2jMQzkjUTDUYONNg1A00Tw1Nx4YEzAzjUT1MTNMjDjMM1MNNAjyTMIzxNADDINQANwT5yTDEMjEzNz2z2gOgjDDDNyNDjTzz43ETOYMI35gDjE00MYYM2DzDjDgww53Mwz0ME1NMgOM3MIzYTzMwzOMIQU5MjOzUjMNQNNg50U5NIDNzw2DMMOggNcQQM21TI5NMzDTN5Mj123O33MNNMkyNTNONxMM5wMMc04jTgAUE3MM1zMg4NNMT4MNDMM5yTO2j4jNDEMy1yNANNAzOIEUDzNwzExwTIkNjUjkN54Uz0DT5x0zM51k2MxYkx0zMNzxMkDUDTTQN3gAYODATQDDwMDMjMMcONjxMNTYMT5kgxNkMjNMQU0jzMEwIIMzTzUD4MgYDkDNzcAzN0TN4yNTz11DMxDUjDM2MyDMy4DEINMwT22QxjNNEzNDATy1OM1NNDxYgz5TxDkj3gQ32kIwNNkDO3xczDAENcTMNO0MOjTDwE3g11wNUcgNTwQk30kjjNNzTz4jTj4OOjQNYzMzcMjTQMkyzNNNUQOTOMMkMMMNzwNxDOEkg4xADIT4DNxMz2TENT4yN4z2I2zjyMU3DTOEQN4MIQjNDMU5Y11QkccwMNI0kNzyNjMMN4NMTTNMzMwxMjjDzgAANO1zwjYIEUjM1ADgDNjxTITMNNkIYxzyzzEEDMzDzNjzM4NjNNjc3ITTD0T5jzN=

我是否正确假设两个值n和e均未正确编码?
我应该如何将PublicKey转换为JWK? (不能使用第三方库)

最佳答案

JWK使用的base64url编码与base64略有不同。此外,请勿对toString()值使用BigInteger方法。直接以字节数组形式获取数据

改变

Base64.encode(rsa.getModulus().toString())
Base64.encode(rsa.getPublicExponent().toString())


Base64.getUrlEncoder().encodeToString(rsa.getModulus().toByteArray())
Base64.getUrlEncoder().encodeToString(rsa.getPublicExponent().toByteArray())

10-05 22:07