In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces you based on Java verification jwttoken code how to write, the content is very detailed, interested friends can refer to, hope to be helpful to you.
1.HS256 symmetric encryption
Package jwt; import java.io.FileInputStream;import java.io.IOException;import java.security.KeyFactory;import java.security.PrivateKey;import java.security.PublicKey;import java.security.interfaces.RSAPrivateKey;import java.security.interfaces.RSAPublicKey;import java.security.spec.PKCS8EncodedKeySpec;import java.security.spec.X509EncodedKeySpec;import java.util.Base64;import java.util.Date;import java.util.Vector;import java.util.Map; import sun.misc.BASE64Decoder; import com.auth0.jwt.JWT;import com.auth0.jwt.algorithms.Algorithm Import com.auth0.jwt.exceptions.JWTVerificationException;import com.auth0.jwt.interfaces.Claim;import com.auth0.jwt.interfaces.DecodedJWT; public class JWTValidator {private static String JWT_Type = "JWT"; protected boolean validated; protected Object [] claims; public JWTValidator () {setValidated (false); setClaims (null);} public String Generate (String secret, String issuer, String audience, String subject) {try {Algorithm algorithm = Algorithm.HMAC256 (secret) / / HS256 String token = JWT.create () .withIssuer (issuer) .withaudience (audience) .withSubject (subject) .sign (algorithm); System.out.println (token); return token;} catch (Exception exception) {/ / UTF-8 encoding not supported return ";}} public void Validate (String token, String secret, String issuer, String audience, String subject) {DecodedJWT jwt = null; setValidated (false); if (token = null | | secret = null | | issuer = null | audience = null | | subject = = null) return Try {jwt = JWT.require (Algorithm.HMAC256 (secret.getBytes ()). Build (). Verify (token);} catch (JWTVerificationException e) {return;} if (jwt = = null | | jwt.getType () = = null | |! jwt.getType (). ContentEquals (JWT_Type)) return; if (! jwt.getIssuer (). ContentEquals (issuer) | |! jwt.getAudience (). Contains (audience) | |! jwt.getSubject (). ContentEquals (subject)) return; Date now = new Date () If ((jwt.getNotBefore ()! = null & & jwt.getNotBefore (). After (now)) | | (jwt.getExpiresAt ()! = null & & jwt.getExpiresAt (). Before (now)) return; setValidated (true); Map claimsMap = jwt.getClaims (); Vector claimsVector = new Vector (); if (claimsMap! = null) {for (Map.Entry entry: claimsMap.entrySet ()) {String key = entry.getKey () If (key! = null & &! key.matches ("aud | sub | iss | exp | iat") {/ / claimsVector.add (new Claim (key, entry.getValue (). AsString ();} setClaims (claimsVector.isEmpty ()? Null: claimsVector.toArray ();} public boolean isValidated () {return validated;} public void setValidated (boolean val) {validated = val;} public Object [] getClaims () {return claims;} public void setClaims (Object [] val) {claims = (val = = null? New Object [0]: val);}}
2.RS256 asymmetric encryption, which needs to be verified by public cert
Package jwt; import junit.framework.TestCase;import org.apache.commons.codec.binary.Base64;import org.apache.commons.io.IOUtils;import org.jose4j.jws.AlgorithmIdentifiers;import org.jose4j.jws.JsonWebSignature;import org.jose4j.jwt.JwtClaims;import org.jose4j.jwt.consumer.JwtConsumer;import org.jose4j.jwt.consumer.JwtConsumerBuilder;import org.jose4j.lang.JoseException;import sun.security.util.DerInputStream;import sun.security.util.DerValue; import java.io.ByteArrayInputStream;import java.io.FileInputStream;import java.io.FileNotFoundException Import java.io.IOException;import java.math.BigInteger;import java.security.*;import java.security.cert.CertificateException;import java.security.cert.CertificateFactory;import java.security.cert.X509Certificate;import java.security.spec.InvalidKeySpecException;import java.security.spec.RSAPrivateCrtKeySpec;import java.security.spec.X509EncodedKeySpec;import java.text.SimpleDateFormat;import java.util.UUID; public class JWTValidatorForRSA extends TestCase {public void testCreateToken () throws IOException {System.out.println (createToken ());} public void testVerifyToken () throws Exception {String token = createToken () System.out.println (token); String pkeyPath = "D:\\ temp\\ idsrv4.crt"; JwtClaims jwtClaims = verifyToken (token,pkeyPath); System.out.println (jwtClaims.getClaimValue ("name")); System.out.println (new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss") .format (jwtClaims.getIssuedAt (). GetValueInMillis ()); System.out.println (new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss") .format (jwtClaims.getExpirationTime (). GetValueInMillis () } / * generate jwt,SHA256 encryption * @ return * @ throws IOException * / public String createToken () throws IOException {String privateKeyPath = "D:\\ temp\\ idsrv4.key"; PrivateKey privateKey = getPrivateKey (getStringFromFile (privateKeyPath)); final JwtClaims claims = new JwtClaims (); claims.setClaim ("name", "jack"); claims.setSubject ("a@a.com"); claims.setAudience ("test") / / used to verify whether the signature is valid, and the verifier must contain these contents before passing claims.setExpirationTimeMinutesInTheFuture (- 1); / / 60U24U30); claims.setIssuedAtToNow (); / / Generate the payload final JsonWebSignature jws = new JsonWebSignature (); jws.setAlgorithmHeaderValue (AlgorithmIdentifiers.RSA_USING_SHA256); jws.setPayload (claims.toJson ()); jws.setKeyIdHeaderValue (UUID.randomUUID (). ToString ()); / / Sign using the private key jws.setKey (privateKey); try {return jws.getCompactSerialization () } catch (JoseException e) {return null;}} / * verify jwt * @ param token * @ return * @ throws Exception * / public JwtClaims verifyToken (String token,String publicKeyPath) throws Exception {try {PublicKey publicKey = getPublicKey (publicKeyPath) JwtConsumer jwtConsumer = new JwtConsumerBuilder () .setRequireExpirationTime () .setVerificationKey (publicKey) .setExpectedAudience ("test") / / used to verify whether the signature is legal. Multiple signatures can be set, and items must be set. If the jwt does not contain these items, it does not pass .build (); return jwtConsumer.processToClaims (token);} catch (Exception e) {throw new RuntimeException (e) }} private String getStringFromFile (String filePath) throws IOException {/ / Generation method: install openssl and execute openssl genrsa-out private.pem 2048 return IOUtils.toString (new FileInputStream (filePath)) } / * get PublicKey object * @ param publicKeyBase64 * @ return * @ throws NoSuchAlgorithmException * @ throws InvalidKeySpecException * @ throws CertificateException * @ throws FileNotFoundException * / private PublicKey getPublicKey (String publicKeyPath) throws NoSuchAlgorithmException, InvalidKeySpecException, CertificateException, FileNotFoundException {/ * Not work: data isn't an object ID (tag = 2) String pem = publicKeyBase64 .replaceAll ("\\-* BEGIN.*CERTIFICATE\\-*") .replaceAll ("\-* END.*CERTIFICATE\ -", "") Java.security.Security.addProvider (new org.bouncycastle.jce.provider.BouncyCastleProvider ()); System.out.println (pem); X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec (Base64.decodeBase64 (pem)); KeyFactory keyFactory = KeyFactory.getInstance ("RSA"); PublicKey publicKey = keyFactory.generatePublic (pubKeySpec); * / CertificateFactory fact = CertificateFactory.getInstance ("X.509"); FileInputStream is = new FileInputStream (publicKeyPath); X509Certificate cer = (X509Certificate) fact.generateCertificate (is); PublicKey publicKey = cer.getPublicKey (); System.out.println (publicKey); return publicKey } / * get PrivateKey object * @ param privateKeyBase64 * @ return * / private PrivateKey getPrivateKey (String privateKeyBase64) {String privKeyPEM = privateKeyBase64 .replaceAll ("\\-* BEGIN.*KEY\\-*", ") .replaceAll ("\-* END.*KEY\\-* ","); / / Base64 decode the data byte [] encoded = Base64.decodeBase64 (privKeyPEM); try {DerInputStream derReader = new DerInputStream (encoded); DerValue [] seq = derReader.getSequence (0) If (seq.length < 9) {throw new GeneralSecurityException ("Could not read private key");} / / skip version seq [0]; BigInteger modulus = seq [1] .getBigInteger (); BigInteger publicExp = seq [2] .getBigInteger (); BigInteger privateExp = seq [3] .getBigInteger (); BigInteger primeP = seq [4] .getBigInteger (); BigInteger primeQ = seq [5] .getBigInteger (); BigInteger expP = seq [6] .getBigInteger (); BigInteger expQ = seq [7] .getBigInteger (); BigInteger crtCoeff = seq [8] .getBigInteger () RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec (modulus, publicExp, privateExp, primeP, primeQ, expP, expQ, crtCoeff); KeyFactory factory = KeyFactory.getInstance ("RSA"); return factory.generatePrivate (keySpec);} catch (Exception e) {e.printStackTrace ();} return null;}}
On how to write Java-based verification jwttoken code to share here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.