1 /*
2  * Copyright (C) 2014 jsonwebtoken.io
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package io.jsonwebtoken.impl.crypto;
17
18 import io.jsonwebtoken.SignatureAlgorithm;
19 import io.jsonwebtoken.impl.TextCodec;
20 import io.jsonwebtoken.lang.Assert;
21
22 import java.nio.charset.Charset;
23 import java.security.Key;
24
25 public class DefaultJwtSignatureValidator implements JwtSignatureValidator {
26
27     private static final Charset US_ASCII = Charset.forName("US-ASCII");
28
29     private final SignatureValidator signatureValidator;
30
31     public DefaultJwtSignatureValidator(SignatureAlgorithm alg, Key key) {
32         this(DefaultSignatureValidatorFactory.INSTANCE, alg, key);
33     }
34
35     public DefaultJwtSignatureValidator(SignatureValidatorFactory factory, SignatureAlgorithm alg, Key key) {
36         Assert.notNull(factory, "SignerFactory argument cannot be null.");
37         this.signatureValidator = factory.createSignatureValidator(alg, key);
38     }
39
40     @Override
41     public boolean isValid(String jwtWithoutSignature, String base64UrlEncodedSignature) {
42
43         byte[] data = jwtWithoutSignature.getBytes(US_ASCII);
44
45         byte[] signature = TextCodec.BASE64URL.decode(base64UrlEncodedSignature);
46
47         return this.signatureValidator.isValid(data, signature);
48     }
49 }
50