无法使用已配置的PublicKey验证RSA签名。签名长度不正确:达到255,但预期为256

时间:2019-02-14 16:04:09

标签: java spring-boot jwt rsa

我正在尝试学习如何使用RSA公私钥对来签署JWT。

我使用openssl生成了密钥对。

openssl genpkey -algorithm RSA -out private_key.pem -pkeyopt rsa_keygen_bits:2048

openssl rsa -pubout -in private_key.pem -out public_key.pem

我正在如下设置环境变量

export PRIVATE_KEY_DEMO=`cat private_key.pem`

export PUBLIC_KEY_DEMO=`cat public_key.pem`

我具有以下创建PrivateKeyPublicKey

的功能
public PrivateKey getPrivateKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, URISyntaxException {
    String key = env.getProperty("PRIVATE_KEY_DEMO");
    key = key.replace("-----BEGIN PRIVATE KEY-----", "")
         .replace("-----END PRIVATE KEY-----", "")
         .replace("\n", "");

    byte[] keyBytes = Base64.getMimeDecoder().decode(key);

    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePrivate(spec);
}

private PublicKey getPublicKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, URISyntaxException {

    String key = env.getProperty("PUBLIC_KEY_DEMO");
    key = key.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLICKEY-----", "").replace("\n", "");
    byte[] keyBytes = Base64.getMimeDecoder().decode(key);

    X509EncodedKeySpec spec = new X509EncodedKeySpec((keyBytes));
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePublic(spec);
}

我能够获得JWT令牌,但是我无法生成PublicKey 以下是ExceptionStack:

java.security.SignatureException: Signature length not correct: got 255 but was expecting 256
    at sun.security.rsa.RSASignature.engineVerify(RSASignature.java:189) ~[na:1.8.0_191]
    at java.security.Signature$Delegate.engineVerify(Signature.java:1222) ~[na:1.8.0_191]
    at java.security.Signature.verify(Signature.java:655) ~[na:1.8.0_191]
    at io.jsonwebtoken.impl.crypto.RsaSignatureValidator.doVerify(RsaSignatureValidator.java:63) ~[jjwt-0.9.1.jar:0.9.1]
    at io.jsonwebtoken.impl.crypto.RsaSignatureValidator.isValid(RsaSignatureValidator.java:47) ~[jjwt-0.9.1.jar:0.9.1]
    at io.jsonwebtoken.impl.crypto.DefaultJwtSignatureValidator.isValid(DefaultJwtSignatureValidator.java:47) ~[jjwt-0.9.1.jar:0.9.1]
    at io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:351) ~[jjwt-0.9.1.jar:0.9.1]

请让我知道我在做错什么,以及是否可以更好地实施。


修改

下面是我用来生成/验证JWT的方法。

public String generateToken()
        throws NoSuchAlgorithmException, InvalidKeySpecException, IOException, URISyntaxException {

    PrivateKey privateKey = this.getPrivateKey();

    Date date = new Date();
    date.setTime(date.getTime() + 60 * 60 * 1000);
    String jws;

    jws = Jwts.builder()
                .setAudience("jws-consumers")
                .setIssuer("jws-issuer")
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "RS256")
                .setExpiration(date)
                .setIssuedAt(new Date())
                .setSubject("nish")
                .signWith(SignatureAlgorithm.RS256, privateKey)
                .compact();
    return jws;
}

public Object validateToken(String token) throws ExpiredJwtException, MalformedJwtException, SignatureException,
        IllegalArgumentException, NoSuchAlgorithmException, InvalidKeySpecException, IOException, URISyntaxException {
    return Jwts.parser()
            .setSigningKey(getPublicKey())
            .parse(token)
            .getBody();
}

这里是生成的JWT的示例

eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiJqd3MtY29uc3VtZXJzIiwiaXNzIjoiandzLWlzc3VlciIsImV4cCI6MTU1MDE2NDc0NCwiaWF0IjoxNTUwMTYxMTQ0LCJzdWIiOiJuaXNoIn0.EbNzMIUc4HE6CwIDyURdYF-tE4z7rzM9_GbHpB-TlRror9HRO5bmGgXR7x9HOazmL3cTUPMd46s7QJ9cU_HIJYQu9pYIQzu3V2WZf0zpFevtFxBbGDU_UCM1fbdsgSrd8APSKt_mXbJGdzIA8L7O6gBnpvNowgEuNHYgMiRwL89GrT17c31WwIWSRfRubn-bYU62pd5wm5pMArvGBYi6f6EAoIdYsK-nlhKjOIsxjGigjYAohoooV_xv36_q5_8Iaxppl2yroxCeYCy6Jp9po3bjoLVu3k9vkD_-yUGoXr9e-LCktSS4Ndxq4KCVRI_Cf5Ix_ImcZrqFZLdb4UWGmA

GitHub

1 个答案:

答案 0 :(得分:0)

万一有人遇到相同的问题,我可以通过遵循example来解决。

我使用显示在here上的命令生成了public / private键。

并更改了以下几行(对于PRIVATE键,使用PRIVATE而不是PUBLIC)

key = key.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLICKEY-----", "").replace("\n", "");

key = key.replaceAll("\\n", "").replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "");

它起到了神奇的作用,并且效果很好。