如何使用JWK(ColdFusion)验证JWT

时间:2019-03-25 16:57:57

标签: java coldfusion jwt cfml coldbox

我目前正在尝试使用从JWKS URL构建的RSA公钥来验证JWT的签名。我为此使用了一些Java对象,但是我的问题是Java Signature验证程序不仅仅将解码为二进制的纯文本字符串作为参数,还接受了它自己专有的二进制解码的“签名”。

因此,我只是想知道如何将纯文本签名转换为Java签名verify()函数期望的数据类型。

这是我当前的代码:

private function validate_jwt_signature(rc) {
    var id_token = listToArray(rc.id_token, ".");

    if (listToArray(id_token[2], "")[len(id_token[2])] != "=") {
            id_token[2] = id_token[2] & "=";
        }

    var header = deserializeJSON(base64urldecode(id_token[1]));
    var payload = deserializeJSON(base64urldecode(id_token[2]));
    var body = id_token[1] & "." & id_token[2];
    var signature = id_token[3];

    cfhttp(url="https://lti-ri.imsglobal.org/platforms/53/platform_keys/48.json", method="GET", result="key");

    var platformPubKey = deserializeJSON(key.filecontent).keys[1].n;

    createObject( "java", "java.security.Security" )
        .addProvider( createObject( "java", "org.bouncycastle.jce.provider.BouncyCastleProvider" ).init());

    var platformPubKey = reReplace( platformPubKey, "-", "+", "all" );
    var platformPubKey = reReplace( platformPubKey, "_", "/", "all" );
    var pemKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA" & platformPubKey & "IDAQAB";
    var publicKeySpec = createObject( "java", "java.security.spec.X509EncodedKeySpec" )
        .init(binaryDecode( pemKey, "base64" ));

    var publicKey = createObject( "java", "java.security.KeyFactory" )
        .getInstance( javaCast( "string", "RSA" ) )
        .generatePublic( publicKeySpec );

    var verifier = createObject( "java", "java.security.Signature" )
        .getInstance( javaCast( "string", 'SHA256withRSA' ));

    var verifier.initVerify( publicKey );
    var verifier.update( charsetDecode( body, "utf-8" ) );
    var signature = reReplace( signature, "-", "+", "all" );
    var signature = reReplace( signature, "_", "/", "all" );
    var verified = verifier.verify( charsetDecode(signature, "utf-8"));

    return verified;
}

此代码可以运行并且不会出错,但是即使我知道签名有效,它也始终返回false。

0 个答案:

没有答案