Java Code Examples for io.jsonwebtoken.SignatureAlgorithm#getJcaName()

The following examples show how to use io.jsonwebtoken.SignatureAlgorithm#getJcaName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SecurityServiceImpl.java    From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License 8 votes vote down vote up
@Override
public String createToken(String subject, long ttlMillis) {
	
	if (ttlMillis <= 0) {
		throw new RuntimeException("Expiry time must be greater than Zero :["+ttlMillis+"] ");
	}
	
	SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

	// The JWT signature algorithm we will be using to sign the token
	long nowMillis = System.currentTimeMillis();

	byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secretKey);
	Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

	JwtBuilder builder = Jwts.builder()
			.setSubject(subject)				
			.signWith(signatureAlgorithm, signingKey);
	
	builder.setExpiration(new Date(nowMillis + ttlMillis));		

	return builder.compact();
}
 
Example 2
Source File: SecurityServiceImpl.java    From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License 8 votes vote down vote up
@Override
public String createToken(String subject, long ttlMillis) {
	
	if (ttlMillis <= 0) {
		throw new RuntimeException("Expiry time must be greater than Zero :["+ttlMillis+"] ");
	}
	
	SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

	// The JWT signature algorithm we will be using to sign the token
	long nowMillis = System.currentTimeMillis();

	byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secretKey);
	Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

	JwtBuilder builder = Jwts.builder()
			.setSubject(subject)				
			.signWith(signatureAlgorithm, signingKey);
	
	builder.setExpiration(new Date(nowMillis + ttlMillis));		

	return builder.compact();
}
 
Example 3
Source File: SecurityServiceImpl.java    From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License 7 votes vote down vote up
@Override
public String createToken(String subject, long ttlMillis) {
	
	if (ttlMillis <= 0) {
		throw new RuntimeException("Expiry time must be greater than Zero :["+ttlMillis+"] ");
	}
	
	SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

	// The JWT signature algorithm we will be using to sign the token
	long nowMillis = System.currentTimeMillis();

	byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secretKey);
	Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

	JwtBuilder builder = Jwts.builder()
			.setSubject(subject)				
			.signWith(signatureAlgorithm, signingKey);
	
	builder.setExpiration(new Date(nowMillis + ttlMillis));		

	return builder.compact();
}
 
Example 4
Source File: Keys.java    From jjwt with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new SecretKey instance for use with HMAC-SHA algorithms based on the specified key byte array.
 *
 * @param bytes the key byte array
 * @return a new SecretKey instance for use with HMAC-SHA algorithms based on the specified key byte array.
 * @throws WeakKeyException if the key byte array length is less than 256 bits (32 bytes) as mandated by the
 *                          <a href="https://tools.ietf.org/html/rfc7518#section-3.2">JWT JWA Specification
 *                          (RFC 7518, Section 3.2)</a>
 */
public static SecretKey hmacShaKeyFor(byte[] bytes) throws WeakKeyException {

    if (bytes == null) {
        throw new InvalidKeyException("SecretKey byte array cannot be null.");
    }

    int bitLength = bytes.length * 8;

    for (SignatureAlgorithm alg : PREFERRED_HMAC_ALGS) {
        if (bitLength >= alg.getMinKeyLength()) {
            return new SecretKeySpec(bytes, alg.getJcaName());
        }
    }

    String msg = "The specified key byte array is " + bitLength + " bits which " +
        "is not secure enough for any JWT HMAC-SHA algorithm.  The JWT " +
        "JWA Specification (RFC 7518, Section 3.2) states that keys used with HMAC-SHA algorithms MUST have a " +
        "size >= 256 bits (the key size must be greater than or equal to the hash " +
        "output size).  Consider using the " + Keys.class.getName() + "#secretKeyFor(SignatureAlgorithm) method " +
        "to create a key guaranteed to be secure enough for your preferred HMAC-SHA algorithm.  See " +
        "https://tools.ietf.org/html/rfc7518#section-3.2 for more information.";
    throw new WeakKeyException(msg);
}
 
Example 5
Source File: MacProvider.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generates a new secure-random secret key of a length suitable for creating and verifying HMAC signatures
 * according to the specified {@code SignatureAlgorithm} using the specified SecureRandom number generator.  This
 * implementation returns secure-random key sizes as follows:
 *
 * <table> <caption>Key Sizes</caption> <thead> <tr> <th>Signature Algorithm</th> <th>Generated Key Size</th> </tr> </thead> <tbody> <tr>
 * <td>HS256</td> <td>256 bits (32 bytes)</td> </tr> <tr> <td>HS384</td> <td>384 bits (48 bytes)</td> </tr> <tr>
 * <td>HS512</td> <td>512 bits (64 bytes)</td> </tr> </tbody> </table>
 *
 * @param alg    the signature algorithm that will be used with the generated key
 * @param random the secure random number generator used during key generation
 * @return a new secure-random secret key of a length suitable for creating and verifying HMAC signatures according
 * to the specified {@code SignatureAlgorithm} using the specified SecureRandom number generator.
 * @see #generateKey()
 * @see #generateKey(SignatureAlgorithm)
 * @since 0.5
 */
public static SecretKey generateKey(SignatureAlgorithm alg, SecureRandom random) {

    Assert.isTrue(alg.isHmac(), "SignatureAlgorithm argument must represent an HMAC algorithm.");

    byte[] bytes;

    switch (alg) {
        case HS256:
            bytes = new byte[32];
            break;
        case HS384:
            bytes = new byte[48];
            break;
        default:
            bytes = new byte[64];
    }

    random.nextBytes(bytes);

    return new SecretKeySpec(bytes, alg.getJcaName());
}
 
Example 6
Source File: SecurityServiceImpl.java    From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License 6 votes vote down vote up
@Override
public String createToken(String subject, long ttlMillis) {
	
	if (ttlMillis <= 0) {
		throw new RuntimeException("Expiry time must be greater than Zero :["+ttlMillis+"] ");
	}
	
	SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

	// The JWT signature algorithm we will be using to sign the token
	long nowMillis = System.currentTimeMillis();

	byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secretKey);
	Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

	JwtBuilder builder = Jwts.builder()
			.setSubject(subject)				
			.signWith(signatureAlgorithm, signingKey);
	
	builder.setExpiration(new Date(nowMillis + ttlMillis));		

	return builder.compact();
}
 
Example 7
Source File: SecurityServiceImpl.java    From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License 6 votes vote down vote up
@Override
public String createToken(String subject, long ttlMillis) {
	
	if (ttlMillis <= 0) {
		throw new RuntimeException("Expiry time must be greater than Zero :["+ttlMillis+"] ");
	}
	
	SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

	// The JWT signature algorithm we will be using to sign the token
	long nowMillis = System.currentTimeMillis();

	byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secretKey);
	Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

	JwtBuilder builder = Jwts.builder()
			.setSubject(subject)				
			.signWith(signatureAlgorithm, signingKey);
	
	builder.setExpiration(new Date(nowMillis + ttlMillis));		

	return builder.compact();
}
 
Example 8
Source File: JwtUtil.java    From mogu_blog_v2 with Apache License 2.0 5 votes vote down vote up
/**
 * 生成jwt token user
 *
 * @param userOpenId
 * @param userId
 * @param isUser
 * @param shopId
 * @return
 */
public static String createJWT(String userOpenId, Long userId, boolean isUser, Long shopId) {
    log.info("userOpenId" + userOpenId + "userId" + userId + "isUser" + isUser + "shopId" + shopId);
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

    long nowMillis = System.currentTimeMillis();
    Date now = new Date(nowMillis);

    //生成签名密钥
    byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Secret);
    Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

    //添加构成JWT的参数
    JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
            .claim("user_id", userId)
            .claim("shop_id", shopId)
            .claim("is_user", isUser)
            .claim("user_open_id", userOpenId)
            .signWith(signatureAlgorithm, signingKey);
    //添加Token过期时间
    if (expiresSecond >= 0) {
        long expMillis = nowMillis + expiresSecond;
        Date exp = new Date(expMillis);
        builder.setExpiration(exp).setNotBefore(now);
    }

    //生成JWT
    String compact = builder.compact();
    log.info("生成jwt===========" + compact);
    return compact;

}
 
Example 9
Source File: JWTUtils.java    From NetworkDisk_Storage with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 由字符串生成加密key
 * 
 * @return
 */
public static Key generalKey(SignatureAlgorithm signatureAlgorithm) {
	byte[] apiKeySecretBytes = SECRETKEY.getBytes();
       Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
	//byte[] encodedKey = Base64.decodeBase64(stringKey);
	//SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
	return signingKey;
}
 
Example 10
Source File: TokenUtils.java    From XUpdateService with Apache License 2.0 5 votes vote down vote up
/**
 * 生成Token
 *
 * @param id        编号
 * @param issuer    该JWT的签发者,是否使用是可选的
 * @param subject   该JWT所面向的用户,是否使用是可选的;
 * @param ttlMillis 签发时间 (有效时间,过期会报错)
 * @return token String
 */
public static String createJwtToken(String id, String issuer, String subject, long ttlMillis) {

    // 签名算法 ,将对token进行签名
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

    // 生成签发时间
    long nowMillis = System.currentTimeMillis();
    Date now = new Date(nowMillis);

    // 通过秘钥签名JWT
    byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET);
    Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

    // Let's set the JWT Claims
    JwtBuilder builder = Jwts.builder().setId(id)
            .setIssuedAt(now)
            .setSubject(subject)
            .setIssuer(issuer)
            .signWith(signatureAlgorithm, signingKey);

    // if it has been specified, let's add the expiration
    if (ttlMillis >= 0) {
        long expMillis = nowMillis + ttlMillis;
        Date exp = new Date(expMillis);
        builder.setExpiration(exp);
    }

    // Builds the JWT and serializes it to a compact, URL-safe string
    return builder.compact();

}
 
Example 11
Source File: DefaultJwtBuilder.java    From jjwt with Apache License 2.0 5 votes vote down vote up
@Override
public JwtBuilder signWith(SignatureAlgorithm alg, byte[] secretKeyBytes) throws InvalidKeyException {
    Assert.notNull(alg, "SignatureAlgorithm cannot be null.");
    Assert.notEmpty(secretKeyBytes, "secret key byte array cannot be null or empty.");
    Assert.isTrue(alg.isHmac(), "Key bytes may only be specified for HMAC signatures.  If using RSA or Elliptic Curve, use the signWith(SignatureAlgorithm, Key) method instead.");
    SecretKey key = new SecretKeySpec(secretKeyBytes, alg.getJcaName());
    return signWith(key, alg);
}
 
Example 12
Source File: JwtUtils.java    From withme3.0 with MIT License 5 votes vote down vote up
public static String createJWT(String authUser) {
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
    byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(CONSTANT.SECRET_KEY);
    Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
    JwtBuilder builder = Jwts.builder()
            .setHeaderParam("typ", "jwt")
            .setHeaderParam("alg", "HS256")
            .setPayload(authUser)
            .signWith(signatureAlgorithm, signingKey);
    return builder.compact();
}
 
Example 13
Source File: JwtHelper.java    From mogu_blog_v2 with Apache License 2.0 5 votes vote down vote up
public String refreshToken(String token, String base64Security, long TTLMillis) {
    String refreshedToken;
    try {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        // 生成签名密钥
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Security);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        final Claims claims = parseJWT(token, base64Security);
        claims.put("creatDate", new Date());
        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
                .setClaims(claims)
                .setSubject(getUsername(token, base64Security))
                .setIssuer(getIssuer(token, base64Security))
                .setAudience(getAudience(token, base64Security))
                .signWith(signatureAlgorithm, signingKey);
        //添加Token过期时间
        if (TTLMillis >= 0) {
            long expMillis = nowMillis + TTLMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp).setNotBefore(now);
        }
        refreshedToken = builder.compact();
    } catch (Exception e) {
        refreshedToken = null;
    }
    return refreshedToken;
}
 
Example 14
Source File: JwtHelper.java    From mogu_blog_v2 with Apache License 2.0 5 votes vote down vote up
/**
 * 构建jwt
 *
 * @param userName       账户名
 * @param adminUid       账户id
 * @param roleName       账户拥有角色名
 * @param audience       代表这个Jwt的接受对象
 * @param issuer         代表这个Jwt的签发主题
 * @param TTLMillis      jwt有效时间
 * @param base64Security 加密方式
 * @return
 */
public String createJWT(String userName, String adminUid, String roleName,
                        String audience, String issuer, long TTLMillis, String base64Security) {
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
    long nowMillis = System.currentTimeMillis();
    Date now = new Date(nowMillis);
    //生成签名密钥
    byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Security);
    Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
    //添加构成JWT的参数
    JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
            .claim("adminUid", adminUid)
            .claim("role", roleName)
            .claim("creatTime", now)
            .setSubject(userName)
            .setIssuer(issuer)
            .setAudience(audience)
            .signWith(signatureAlgorithm, signingKey);
    //添加Token过期时间
    if (TTLMillis >= 0) {
        long expMillis = nowMillis + TTLMillis;
        Date exp = new Date(expMillis);
        builder.setExpiration(exp).setNotBefore(now);
    }
    //生成JWT
    return builder.compact();
}
 
Example 15
Source File: JwtUtil.java    From mogu_blog_v2 with Apache License 2.0 5 votes vote down vote up
public static String createSysUserJWT(Long shopId, Long sysUserId, String loginUserName, String loginPassWord, boolean isShop) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        //生成签名密钥
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Secret);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        //添加构成JWT的参数
        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
                .claim("shop_id", shopId)
                .claim("sys_user_id", sysUserId)
                .claim("is_shop", isShop)
                .claim("login_username", loginUserName)
                .claim("login_password", loginPassWord)
//	                .claim("user_open_id", userOpenId)
                .signWith(signatureAlgorithm, signingKey);
        //添加Token过期时间
        if (expiresSecond >= 0) {
            long expMillis = nowMillis + expiresSecond;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp).setNotBefore(now);
        }

        //生成JWT
        String compact = builder.compact();
        log.info("生成jwt===========" + compact);
        return compact;
    }
 
Example 16
Source File: JsonWebTokenAuthenticator.java    From presto with Apache License 2.0 5 votes vote down vote up
public Key getKey(SignatureAlgorithm algorithm)
{
    if (algorithm.isHmac()) {
        if (hmacKey == null) {
            throw new UnsupportedJwtException(format("JWT is signed with %s, but no HMAC key is configured", algorithm));
        }
        return new SecretKeySpec(hmacKey, algorithm.getJcaName());
    }

    if (publicKey == null) {
        throw new UnsupportedJwtException(format("JWT is signed with %s, but no key is configured", algorithm));
    }
    return publicKey;
}
 
Example 17
Source File: MacSigner.java    From jjwt with Apache License 2.0 4 votes vote down vote up
public MacSigner(SignatureAlgorithm alg, byte[] key) {
    this(alg, new SecretKeySpec(key, alg.getJcaName()));
}
 
Example 18
Source File: MacProvider.java    From jjwt with Apache License 2.0 4 votes vote down vote up
/**
 * Generates a new secure-random secret key of a length suitable for creating and verifying HMAC signatures
 * according to the specified {@code SignatureAlgorithm} using the specified SecureRandom number generator.  This
 * implementation returns secure-random key sizes as follows:
 *
 * <table> <caption>Key Sizes</caption> <thead> <tr> <th>Signature Algorithm</th> <th>Generated Key Size</th> </tr> </thead> <tbody> <tr>
 * <td>HS256</td> <td>256 bits (32 bytes)</td> </tr> <tr> <td>HS384</td> <td>384 bits (48 bytes)</td> </tr> <tr>
 * <td>HS512</td> <td>512 bits (64 bytes)</td> </tr> </tbody> </table>
 *
 * @param alg    the signature algorithm that will be used with the generated key
 * @param random the secure random number generator used during key generation
 * @return a new secure-random secret key of a length suitable for creating and verifying HMAC signatures according
 * to the specified {@code SignatureAlgorithm} using the specified SecureRandom number generator.
 * @see #generateKey()
 * @see #generateKey(SignatureAlgorithm)
 * @since 0.5
 * @deprecated since 0.10.0 - use {@link #generateKey(SignatureAlgorithm)} instead.
 */
@Deprecated
public static SecretKey generateKey(SignatureAlgorithm alg, SecureRandom random) {

    Assert.isTrue(alg.isHmac(), "SignatureAlgorithm argument must represent an HMAC algorithm.");

    KeyGenerator gen;

    try {
        gen = KeyGenerator.getInstance(alg.getJcaName());
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("The " + alg.getJcaName() + " algorithm is not available.  " +
            "This should never happen on JDK 7 or later - please report this to the JJWT developers.", e);
    }

    return gen.generateKey();
}
 
Example 19
Source File: MacSigner.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public MacSigner(SignatureAlgorithm alg, byte[] key) {
    this(alg, new SecretKeySpec(key, alg.getJcaName()));
}
 
Example 20
Source File: JwtHelper.java    From kisso with Apache License 2.0 2 votes vote down vote up
/**
 * 字符串密钥生成加密 Key
 *
 * @param signKey            密钥
 * @param signatureAlgorithm 签名算法
 * @return
 */
public static SecretKey getSecretKey(String signKey, SignatureAlgorithm signatureAlgorithm) {
    return new SecretKeySpec(signKey.getBytes(), signatureAlgorithm.getJcaName());
}