I've implemented the basic OpenID connect flow in my java application and it seems to work fine.
I'd like to use an existing java library to verify the id token, as detailed here on a Salesforce page about implementing OpenId connect.
Are there any existing libraries that implement this well? I've got the response parsed, I just need to find some simple way to verify the id token is valid.
The following example will validate an id_token from an OAuth2 call for Salesforce, without any 3rd party libraries. Note that you'll have to supply a valid id_token below to test this out.
package jwt_validate_signature_sf_no_third_party;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.RSAPublicKeySpec;
import org.apache.commons.codec.binary.Base64;
public class Main
{
// Sample id_token that needs validation. This is probably the only field you need to change to test your id_token.
// If it doesn't work, try making sure the MODULUS and EXPONENT constants are what you're using, as detailed below.
public static final String id_token = "YOUR_ID_TOKEN_HERE";
public static final String[] id_token_parts = id_token.split("\\.");
// Constants that come from the keys your token was signed with.
// Correct values can be found from using the "kid" value and looking up the "n (MODULUS)" and "e (EXPONENT)" fields
// at the following url: https://login.salesforce.com/id/keys
// MAJOR NOTE: This url will work for 90% of your use cases, but for the other 10%
// you'll need to make sure you get the "kid" value from the instance url that
// the api responses from Salesforce suggest for your token, as the kid values *will* be different.
// e.g. Some users would need to get their kid values from https://na44.salesforce.com/id/keys for example.
// The following 2 values are hard coded to work with the "kid=196" key values.
public static final String MODULUS = "5SGw1jcqyFYEZaf39RoxAhlq-hfRSOsneVtsT2k09yEQhwB2myvf3ckVAwFyBF6y0Hr1psvu1FlPzKQ9YfcQkfge4e7eeQ7uaez9mMQ8RpyAFZprq1iFCix4XQw-jKW47LAevr9w1ttZY932gFrGJ4gkf_uqutUny82vupVUETpQ6HDmIL958SxYb_-d436zi5LMlHnTxcR5TWIQGGxip-CrD7vOA3hrssYLhNGQdwVYtwI768EvwE8h4VJDgIrovoHPH1ofDQk8-oG20eEmZeWugI1K3z33fZJS-E_2p_OiDVr0EmgFMTvPTnQ75h_9vyF1qhzikJpN9P8KcEm8oGu7KJGIn8ggUY0ftqKG2KcWTaKiirFFYQ981PhLHryH18eOIxMpoh9pRXf2y7DfNTyid99ig0GUH-lzAlbKY0EV2sIuvEsIoo6G8YT2uI72xzl7sCcp41FS7oFwbUyHp_uHGiTZgN7g-18nm2TFmQ_wGB1xCwJMFzjIXq1PwEjmg3W5NBuMLSbG-aDwjeNrcD_4vfB6yg548GztQO2MpV_BuxtrZDJQm-xhJXdm4FfrJzWdwX_JN9qfsP0YU1_mxtSU_m6EKgmwFdE3Yh1WM0-kRRSk3gmNvXpiKeVduzm8I5_Jl7kwLgBw24QUVaLZn8jC2xWRk_jcBNFFLQgOf9U";
public static final String EXPONENT = "AQAB";
public static final String ID_TOKEN_HEADER = base64UrlDecode(id_token_parts[0]);
public static final String ID_TOKEN_PAYLOAD = base64UrlDecode(id_token_parts[1]);
public static final byte[] ID_TOKEN_SIGNATURE = base64UrlDecodeToBytes(id_token_parts[2]);
public static String base64UrlDecode(String input)
{
byte[] decodedBytes = base64UrlDecodeToBytes(input);
String result = new String(decodedBytes, StandardCharsets.UTF_8);
return result;
}
public static byte[] base64UrlDecodeToBytes(String input)
{
Base64 decoder = new Base64(-1, null, true);
byte[] decodedBytes = decoder.decode(input);
return decodedBytes;
}
public static void main(String args[])
{
dumpJwtInfo();
validateToken();
}
public static void dump(String data)
{
System.out.println(data);
}
public static void dumpJwtInfo()
{
dump(ID_TOKEN_HEADER);
dump(ID_TOKEN_PAYLOAD);
}
public static void validateToken()
{
PublicKey publicKey = getPublicKey(MODULUS, EXPONENT);
byte[] data = (id_token_parts[0] + "." + id_token_parts[1]).getBytes(StandardCharsets.UTF_8);
try
{
boolean isSignatureValid = verifyUsingPublicKey(data, ID_TOKEN_SIGNATURE, publicKey);
System.out.println("isSignatureValid: " + isSignatureValid);
}
catch (GeneralSecurityException e)
{
e.printStackTrace();
}
}
public static PublicKey getPublicKey(String MODULUS, String EXPONENT)
{
byte[] nb = base64UrlDecodeToBytes(MODULUS);
byte[] eb = base64UrlDecodeToBytes(EXPONENT);
BigInteger n = new BigInteger(1, nb);
BigInteger e = new BigInteger(1, eb);
RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(n, e);
try
{
PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(rsaPublicKeySpec);
return publicKey;
}
catch (Exception ex)
{
throw new RuntimeException("Cant create public key", ex);
}
}
private static boolean verifyUsingPublicKey(byte[] data, byte[] signature, PublicKey pubKey) throws GeneralSecurityException
{
Signature sig = Signature.getInstance("SHA256withRSA");
sig.initVerify(pubKey);
sig.update(data);
return sig.verify(signature);
}
}
Note if you're not opposed to using a third party library, I'd totally suggest using this, as it works great. I couldn't use it for business reasons, but was glad to find it as it helped me understand how this process works, validated an id_token, I'm sure in a much more robust way.
Also, to be certain this request was signed by the same client, ensure the aud parameter in the payload matches your own client key given to you by Salesforce.
As part of Spring Security OAuth, the Spring team has developed a library called Spring Security JWT that allows manipulation of JWTs, including decoding and verifying tokens.
See the following helper class for example:
https://github.com/spring-projects/spring-security-oauth/blob/master/spring-security-jwt/src/main/java/org/springframework/security/jwt/JwtHelper.java
The library is in version 1.0.0-RELEASE and available in the maven repo.
Related
Hi Guys I am really confused about so many things.All I know is that I have to generate a token at the end of the day.I am given some RSA private key which is some "XYZ............dsdsfm",(obviously I can't reveal it because of security issues),from there I have to generate some token which will serve as a header for authorisation of my API http request.
The problem is these internet related stuff of JsonWebKey and all that is not in my domain,but still I tried learning them but it is not very clear.I tried to implement some code which was written in Java by someone (and that guy knows only Java and not flutter),in flutter.
For Flutter implementation I tried two plugin in pub.dev...But I am not getting the proper output.
The first one was https://pub.dev/packages/jose>I tried what is similar in the example page of it as shown:
import 'dart:convert';
import 'dart:io';
import 'package:crypto_keys/crypto_keys.dart';
import 'package:jose/jose.dart';
import 'package:x509/x509.dart';
String pkey="XXXXXXXXXXXXXsfds";
void keyGenerator() async {
//await example1();
await example2();
// await example3();
// await example4();
// await example5();
// await example6();
// await example7();
// await example8();
}
// decode and verify a JWS
void example1() async {
var encoded = pkey;
// create a JsonWebSignature from the encoded string
var jws = JsonWebSignature.fromCompactSerialization(encoded);
// extract the payload
var payload = jws.unverifiedPayload;
print('content of jws: ${payload.stringContent}');
print('protected parameters: ${payload.protectedHeader.toJson()}');
// create a JsonWebKey for verifying the signature
var jwk = JsonWebKey.fromJson({
'kty': 'RSA',
'alg': 'RS256',
});
var keyStore = JsonWebKeyStore()..addKey(jwk);
// verify the signature
var verified = await jws.verify(keyStore);
print('signature verified: $verified');
}
// create a JWS
void example2() async {
// create a builder
var builder = JsonWebSignatureBuilder();
// set the content
builder.stringContent = 'It is me';
// set some protected header
builder.setProtectedHeader('createdAt', DateTime.now().toIso8601String());
// add a key to sign, you can add multiple keys for different recipients
builder.addRecipient(
JsonWebKey.fromJson({
'kty': 'RSA',
'kid': pkey,
}),
algorithm: 'RS256');
// build the jws
var jws = builder.build();
// output the compact serialization
print('jws compact serialization: ${jws.toCompactSerialization()}');
// output the json serialization
print('jws json serialization: ${jws.toJson()}');
}
// decode and decrypt a JWE
void example3() async {
var encoded = 'eyJhbGciOiJSU0ExXzUiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0.'
'UGhIOguC7IuEvf_NPVaXsGMoLOmwvc1GyqlIKOK1nN94nHPoltGRhWhw7Zx0-kFm'
'1NJn8LE9XShH59_i8J0PH5ZZyNfGy2xGdULU7sHNF6Gp2vPLgNZ__deLKxGHZ7Pc'
'HALUzoOegEI-8E66jX2E4zyJKx-YxzZIItRzC5hlRirb6Y5Cl_p-ko3YvkkysZIF'
'NPccxRU7qve1WYPxqbb2Yw8kZqa2rMWI5ng8OtvzlV7elprCbuPhcCdZ6XDP0_F8'
'rkXds2vE4X-ncOIM8hAYHHi29NX0mcKiRaD0-D-ljQTP-cFPgwCp6X-nZZd9OHBv'
'-B3oWh2TbqmScqXMR4gp_A.'
'AxY8DCtDaGlsbGljb3RoZQ.'
'KDlTtXchhZTGufMYmOYGS4HffxPSUrfmqCHXaI9wOGY.'
'9hH0vgRfYgPnAHOd8stkvw';
// create a JsonWebEncryption from the encoded string
var jwe = JsonWebEncryption.fromCompactSerialization(encoded);
// create a JsonWebKey for decrypting the signature
var jwk = JsonWebKey.fromJson(
{
'kty': 'RSA',
'n': 'sXchDaQebHnPiGvyDOAT4saGEUetSyo9MKLOoWFsueri23bOdgWp4Dy1Wl'
'UzewbgBHod5pcM9H95GQRV3JDXboIRROSBigeC5yjU1hGzHHyXss8UDpre'
'cbAYxknTcQkhslANGRUZmdTOQ5qTRsLAt6BTYuyvVRdhS8exSZEy_c4gs_'
'7svlJJQ4H9_NxsiIoLwAEk7-Q3UXERGYw_75IDrGA84-lA_-Ct4eTlXHBI'
'Y2EaV7t7LjJaynVJCpkv4LKjTTAumiGUIuQhrNhZLuF_RJLqHpM2kgWFLU'
'7-VTdL1VbC2tejvcI2BlMkEpk1BzBZI0KQB0GaDWFLN-aEAw3vRw',
'e': 'AQAB',
'd': 'VFCWOqXr8nvZNyaaJLXdnNPXZKRaWCjkU5Q2egQQpTBMwhprMzWzpR8Sxq'
'1OPThh_J6MUD8Z35wky9b8eEO0pwNS8xlh1lOFRRBoNqDIKVOku0aZb-ry'
'nq8cxjDTLZQ6Fz7jSjR1Klop-YKaUHc9GsEofQqYruPhzSA-QgajZGPbE_'
'0ZaVDJHfyd7UUBUKunFMScbflYAAOYJqVIVwaYR5zWEEceUjNnTNo_CVSj'
'-VvXLO5VZfCUAVLgW4dpf1SrtZjSt34YLsRarSb127reG_DUwg9Ch-Kyvj'
'T1SkHgUWRVGcyly7uvVGRSDwsXypdrNinPA4jlhoNdizK2zF2CWQ',
'p': '9gY2w6I6S6L0juEKsbeDAwpd9WMfgqFoeA9vEyEUuk4kLwBKcoe1x4HG68'
'ik918hdDSE9vDQSccA3xXHOAFOPJ8R9EeIAbTi1VwBYnbTp87X-xcPWlEP'
'krdoUKW60tgs1aNd_Nnc9LEVVPMS390zbFxt8TN_biaBgelNgbC95sM',
'q': 'uKlCKvKv_ZJMVcdIs5vVSU_6cPtYI1ljWytExV_skstvRSNi9r66jdd9-y'
'BhVfuG4shsp2j7rGnIio901RBeHo6TPKWVVykPu1iYhQXw1jIABfw-MVsN'
'-3bQ76WLdt2SDxsHs7q7zPyUyHXmps7ycZ5c72wGkUwNOjYelmkiNS0',
'dp': 'w0kZbV63cVRvVX6yk3C8cMxo2qCM4Y8nsq1lmMSYhG4EcL6FWbX5h9yuv'
'ngs4iLEFk6eALoUS4vIWEwcL4txw9LsWH_zKI-hwoReoP77cOdSL4AVcra'
'Hawlkpyd2TWjE5evgbhWtOxnZee3cXJBkAi64Ik6jZxbvk-RR3pEhnCs',
'dq': 'o_8V14SezckO6CNLKs_btPdFiO9_kC1DsuUTd2LAfIIVeMZ7jn1Gus_Ff'
'7B7IVx3p5KuBGOVF8L-qifLb6nQnLysgHDh132NDioZkhH7mI7hPG-PYE_'
'odApKdnqECHWw0J-F0JWnUd6D2B_1TvF9mXA2Qx-iGYn8OVV1Bsmp6qU',
'qi': 'eNho5yRBEBxhGBtQRww9QirZsB66TrfFReG_CcteI1aCneT0ELGhYlRlC'
'tUkTRclIfuEPmNsNDPbLoLqqCVznFbvdB7x-Tl-m0l_eFTj2KiqwGqE9PZ'
'B9nNTwMVvH3VRRSLWACvPnSiwP8N5Usy-WRXS-V7TbpxIhvepTfE0NNo'
},
);
var keyStore = JsonWebKeyStore()..addKey(jwk);
// decrypt the payload
var payload = await jwe.getPayload(keyStore);
print('decrypted content: ${payload.stringContent}');
}
// create a JWE
void example4() async {
// create a builder
var builder = JsonWebEncryptionBuilder();
// set the content
builder.stringContent = 'This is my bigest secret';
// set some protected header
builder.setProtectedHeader('createdAt', DateTime.now().toIso8601String());
// add a key to encrypt the Content Encryption Key
var jwk = JsonWebKey.fromJson(
{
'kty': 'RSA',
'n': 'sXchDaQebHnPiGvyDOAT4saGEUetSyo9MKLOoWFsueri23bOdgWp4Dy1Wl'
'UzewbgBHod5pcM9H95GQRV3JDXboIRROSBigeC5yjU1hGzHHyXss8UDpre'
'cbA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w9LsWH_zKI-hwoReoP77cOdSL4AVcra'
'Hawlkpyd2TWjE5evgbhWtOxnZee3cXJBkAi64Ik6jZxbvk-RR3pEhnCs',
'dq': 'o_8V14SezckO6CNLKs_btPdFiO9_kC1DsuUTd2LAfIIVeMZ7jn1Gus_Ff'
'7B7IVx3p5KuBGOVF8L-qifLb6nQnLysgHDh132NDioZkhH7mI7hPG-PYE_'
'odApKdnqECHWw0J-F0JWnUd6D2B_1TvF9mXA2Qx-iGYn8OVV1Bsmp6qU',
'qi': 'eNho5yRBEBxhGBtQRww9QirZsB66TrfFReG_CcteI1aCneT0ELGhYlRlC'
'tUkTRclIfuEPmNsNDPbLoLqqCVznFbvdB7x-Tl-m0l_eFTj2KiqwGqE9PZ'
'B9nNTwMVvH3VRRSLWACvPnSiwP8N5Usy-WRXS-V7TbpxIhvepTfE0NNo'
},
);
builder.addRecipient(jwk, algorithm: 'RSA1_5');
// set the content encryption algorithm to use
builder.encryptionAlgorithm = 'A128CBC-HS256';
// build the jws
var jwe = builder.build();
// output the compact serialization
print('jwe compact serialization: ${jwe.toCompactSerialization()}');
// output the json serialization
print('jwe json serialization: ${jwe.toJson()}');
}
// decode and verify and validate a JWT
void example5() async {
var encoded = 'eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.'
'eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFt'
'cGxlLmNvbS9pc19yb290Ijp0cnVlfQ.'
'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk';
// decode the jwt, note: this constructor can only be used for JWT inside JWS
// structures
var jwt = JsonWebToken.unverified(encoded);
// output the claims
print('claims: ${jwt.claims}');
// create key store to verify the signature
var keyStore = JsonWebKeyStore()
..addKey(JsonWebKey.fromJson({
'kty': 'oct',
'k':
'AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow'
}));
var verified = await jwt.verify(keyStore);
print('verified: $verified');
// alternatively, create and verify the JsonWebToken together, this is also
// applicable for JWT inside JWE
jwt = await JsonWebToken.decodeAndVerify(encoded, keyStore);
// validate the claims
var violations = jwt.claims.validate(issuer: Uri.parse('alice'));
print('violations: $violations');
}
// create a JWT
void example6() async {
var claims = JsonWebTokenClaims.fromJson({
'exp': Duration(hours: 4).inSeconds,
'aud':"live-tv",
'iat':DateTime.now().toString(),
});
// create a builder, decoding the JWT in a JWS, so using a
// JsonWebSignatureBuilder
var builder = JsonWebSignatureBuilder();
// set the content
builder.jsonContent = claims.toJson();
// add a key to sign, can only add one for JWT
builder.addRecipient(
JsonWebKey.fromJson({
'kty': 'RSA',
'kid':pkey,
}),
algorithm: 'HS256');
// build the jws
var jws = builder.build();
// output the compact serialization
print('jwt compact serialization: ${jws.toCompactSerialization()}');
}
// create a JWT, sign with RS512
void example7() async {
var claims = JsonWebTokenClaims.fromJson({
'exp': Duration(hours: 4).inSeconds,
'iss': 'alice',
});
// create a builder, decoding the JWT in a JWS, so using a
// JsonWebSignatureBuilder
var builder = JsonWebSignatureBuilder();
// set the content
builder.jsonContent = claims.toJson();
// add a key to sign, can only add one for JWT
var key = JsonWebKey.fromPem(File('example/jwtRS512.key').readAsStringSync());
builder.addRecipient(key, algorithm: 'RS512');
// build the jws
var jws = builder.build();
// output the compact serialization
print('jwt compact serialization: ${jws.toCompactSerialization()}');
}
// generate a key for use with ES256 signing
void example8() async {
var alg = JsonWebAlgorithm.getByName('ES256');
var key = alg.generateRandomKey();
print(JsonEncoder.withIndent(' ').convert(key));
final hash = utf8.encode('TEST');
var sig = key.sign(hash);
final valid = key.verify(hash, sig);
print('valid? $valid');
}
I tried each example at a time modifying each of those.Few of them said saying "Compact serialisation should have 3 parts",then I did a bit of research and realised that the token to be generated should have 3 parts.The other error in example 2 was that the JSONWebKey can't be signed.
There is another library I used and that was https://pub.dev/packages/corsac_jwt.
The code is below:
import 'package:corsac_jwt/corsac_jwt.dart';
// ..setClaim('13', {'userId': 'xxxx'})
String pkey="sdfdsfdsfds";
void tokenGenerator() {
var builder = new JWTBuilder();
var token = builder
..audience="live-tv"
..issuedAt= new DateTime.now()
..expiresAt = new DateTime.now().add(new Duration(minutes: 3))
..getToken(); // returns token without signature
var signer = new JWTRsaSha256Signer(privateKey: pkey);
var signedToken = builder.getSignedToken(signer);
print("token");
print(signedToken); // prints encoded JWT
var stringToken = signedToken.toString();
var decodedToken = new JWT.parse(stringToken);
// Verify signature:
print(decodedToken.verify(signer)); // true
// Validate claims:
// var validator = new JWTValidator() ;// uses DateTime.now() by default
// // set claims you wish to validate
// Set<String> errors = validator.validate(decodedToken);
// print(errors); // (empty list)
}
But here I got the error invalid private key.If I changed it to public,I got invalid public key as well.
I honestly am I a very chaotic situation mentally with time running out to implement.My team mates are know only one thing I know only flutter only.
By the way the Java code we are trying to implement in flutter is given below.Basically what it does is it takes a StringKey,converts to a PrivateKey and then the token
import android.util.Log;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class RSAKeyGenerator {
private static PrivateKey getPrivateKey() throws GeneralSecurityException {
String pKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
KeyFactory kf = KeyFactory.getInstance("RSA");
byte[] decode;
decode = android.util.Base64.decode(pKey, android.util.Base64.DEFAULT);
PKCS8EncodedKeySpec keySpecPKCS8 = new PKCS8EncodedKeySpec(decode);
return kf.generatePrivate(keySpecPKCS8);
}
public static String getJwtToken() {
final long VALIDITY_MS = TimeUnit.MINUTES.toMillis(60);
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
Date exp = new Date(nowMillis + VALIDITY_MS);
PrivateKey privateKey = null;
try {
privateKey = getPrivateKey();
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
String jws = Jwts.builder()
.claim("version", "13")
.claim("user_id", "xxxxxxxxxxxxxxxxxxx")
.setIssuedAt(now)
.setExpiration(exp)
.signWith(privateKey, SignatureAlgorithm.RS256)
.setAudience("live-tv")
.compact();
Log.d("111__", jws);
SpUtil.Companion.getInstance().putString(J_TOKEN, jws);
return jws;
}
}
After hours of research,trial and errors and consulting my team mates I have arrived at the final conclusion.This works.The mistake I was doing was the RSA key I was passing it as a string like key="xxxxxxxxxxxx",but it should be in the format below
Hope this helps someone
import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart';
String token;
String dartJsonWebTokenGenerator() {
Duration delay = new Duration(minutes: 300);
final jwt = JWT(
payload: {
'version': '13',
'user_id': 'xxxxxxxxxxxxxxxxx',
},
audience: 'live-tv',
);
// Sign it (default with HS256 algorithm)
token = jwt.sign(PrivateKey('''-----BEGIN RSA PRIVATE KEY-----
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx7
wIxAoKDcHD7mv2R//I0QncGzT1I7cccrhIUB1gXH9wWdTXrafhACXrJ2Drfjg/YN
9q4TiKH1k2+zTfdU1IDxd6OX2cPNkwn/vpZeZ1pZqVoimRRJbJg8RhXYvZgd6Nfj
Zdw6LY3Zzm3XbLbTUmbVM5ARDweksnr6cg7HmR2OQ5j5UFuhRyIUTSCDbAmDeyHS
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx70YmgZPR
PIncbKBjLzQe5RB/szyswCAiLxfk7rCrUhPpvdJ4fnDgdXQE26t/CBFb8fpOHtiL
1FtxgURmX/Nh+OhO7pPvK4X7g2GarMdQ3Y6288/STQu/d8yEQDwcro6X9ribay46
Ss69AGJxGJbazUI9fNMETLpR6kIHKli7G7gtTFVY02YPKpqgYs1HFbIgV++gHTaw
XLU3PqroxKkhTuI8JCei1pphS/PAc3S/o0mPxTYLfiojYG/6IDd8WsGonwwk2hqd
e3ad0S56JZNN812vshc8NFMbEU2UzA7L0INf6X+GAhoZojUjZciKwAN/i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REohbcwsctYbhL2UlcBE3QDTqdLnGJEowKCAQBwlBtw/BD5cefTcUB90XtuUpLG
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
moP4L4wBlad2aZYKnkZ87RZIa09wyf5hnPXQkQAHMRYxuaxvQUq/bSDO6JUbrGMp
J2LQgCreNAF7MsIDU2ijVHJNWp9m6LC1Osb1iMp/fZDy+hkAAHP5xDfDedwKmXLV
2kSdWPZebq1iIRyJ+BlbXAEgDMkp+k6mebq+kyH4+3odWvw8bRkmD/g1t/bS
-----END RSA PRIVATE KEY-----'''),
algorithm: JWTAlgorithm.RS256, expiresIn: delay);
print('Signed token: $token\n');
return token;
}
I used the DES algorithm to encrypt the username and password in jdbc.properties, and used the PropertyPlaceholderConfigurer for decryption, but found that this class has been deprecated. So use PropertySourcesPlaceholderConfigurer to replace.
The bean has been added in spring-dao.xml, and the class is filled with the class containing the decryption method inherited from PropertySourcesPlaceholderConfigurer.
I put a breakpoint on the first line of the decryption method, and then started tomcat to send an access request. At this point, the backend should call the database. But if the decryption class inherits from PropertySourcesPlaceholderConfigurer, the first line of the decryption method will not be executed. If the decryption class inherits from PropertyPlaceholderConfigurer, the first line of the decryption method is executed. I don't know why this is the case, should I use the deprecated PropertyPlaceholderConfigurer?
spring.version: 5.2.0.RELEASE
Part of spring-dao.xml
<!--<context:property-placeholder location="classpath:jdbc.properties" />-->
<bean class="com.imooc.o2o.util.EncryptPropertySourcesPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
<property name="fileEncoding" value="UTF-8" />
</bean>
EncryptPropertySourcesPlaceholderConfigurer.java (My decryption algorithm class)
package com.imooc.o2o.util;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
public class EncryptPropertySourcesPlaceholderConfigurer extends PropertySourcesPlaceholderConfigurer {
// Fields to be encrypted
private String[] encryptPropNames = {"jdbc.username", "jdbc.password"};
/**
* Transform key attributes
* #param propertyName
* #param propertyValue
* #return
*/
#Override
protected String convertProperty(String propertyName, String propertyValue) {
if (isEncryptProp(propertyName)) {
// Decrypting encrypted fields
String decryptValue = DESUtil.getDecryptString(propertyValue);
return decryptValue;
} else {
return propertyValue;
}
}
/**
* Whether the attribute is encrypted
* #param propertyName
* #return
*/
private boolean isEncryptProp(String propertyName) {
// If it is equal to the field to be encrypted, it has been encrypted
for (String encryptPropertyName : encryptPropNames) {
if (encryptPropertyName.equals(propertyName)) {
return true;
}
}
return false;
}
}
DESUtil.java
package com.imooc.o2o.util;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.security.Key;
import java.security.SecureRandom;
import java.util.Base64;
/**
* DES is a symmetric encryption algorithm. The so-called symmetric encryption algorithm is an algorithm that uses the same key for encryption and decryption.
*/
public class DESUtil {
private static Key key;
private static String KEY_STR = "myKey";
private static String CHAR_SET_NAME = "UTF-8";
private static String ALGORITHM = "DES";
static {
try {
// Generate DES Algorithm Object
KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM);
// Apply SHA1 security policy
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
// Setting the key seed
secureRandom.setSeed(KEY_STR.getBytes());
// Initialize SHA1-based algorithm objects
generator.init(secureRandom);
// Generate a key object
key = generator.generateKey();
generator = null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// Get encrypted information
public static String getEncryptString(String str) {
// Based on BASE64 encoding, receive byte [] and convert to String
Base64.Encoder encoder = Base64.getEncoder();
try {
// Encoded as UTF-8
byte[] bytes = str.getBytes(CHAR_SET_NAME);
// Get the encrypted object
Cipher cipher = Cipher.getInstance(ALGORITHM);
// Initialize password information
cipher.init(Cipher.ENCRYPT_MODE, key);
// encryption
byte[] doFinal = cipher.doFinal(bytes);
// byte[] to encode a good String and return
return encoder.encodeToString(doFinal);
} catch (Exception e) {
throw new RuntimeException();
}
}
// Get the decrypted information
public static String getDecryptString(String str) {
// Based on BASE64 encoding, receive byte[] and convert to String
Base64.Decoder decoder = Base64.getDecoder();
try {
// Decode string into byte []
byte[] bytes = decoder.decode(str);
// Get the decrypted object
Cipher cipher = Cipher.getInstance(ALGORITHM);
// Initialize decryption information
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] doFinal = cipher.doFinal(bytes);
// Returns the decrypted information
return new String(doFinal, CHAR_SET_NAME);
} catch (Exception e) {
throw new RuntimeException();
}
}
/**
* Get the string to be encrypted
* #param args
*/
public static void main(String[] args) {
System.out.println(getEncryptString(""));
System.out.println(getEncryptString(""));
}
}
Answer my own question, maybe because I did not use Spring Boot.
The implementation logic of these two classes is different. Spring Boot use PropertySourcesPlaceholderConfigurer.
This answer is not accurate. I am a beginner and I have not figured it out in many places. Please understand if the deviation is large.
I need to tweak an API https://sandbox.api.visa.com/cybersource/payments/flex/v1/keys?apikey={apikey}
I am imitating the official document X-Pay Token,but it fail with "Token validation failed" error.
{
"responseStatus": {
"status": 401,
"code": "9159",
"severity": "ERROR",
"message": "Token validation failed",
"info": ""
}
}
Below is my x-pay-token generation code.
import java.math.BigInteger;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SignatureException;
public class T {
private static String resoucePath = "payments/flex/v1/keys";
private static String queryString = "apikey=6DC0NMXO53QQFE6NFOLE213HXA-pvG6xE-1NtuCd5oOQr-O-s";
private static String requestBody = "{encryptionType:RsaOaep256}";
private static String sharedSecret = "gAynzAGf89+V}3{Q4Jx5cp-/R#Y#PEv#1XvxnjQC";
public static void main(String[] args) throws SignatureException {
System.out.println(T.generateXpaytoken(resoucePath, queryString, requestBody, sharedSecret));
}
public static String generateXpaytoken(String resourcePath, String queryString, String requestBody, String sharedSecret) throws SignatureException {
String timestamp = timeStamp();
String beforeHash = timestamp + resourcePath + queryString + requestBody;
String hash = hmacSha256Digest(beforeHash, sharedSecret);
String token = "xv2:" + timestamp + ":" + hash;
return token;
}
private static String timeStamp() {
return String.valueOf(System.currentTimeMillis() / 1000L);
}
private static String hmacSha256Digest(String data, String sharedSecret) throws SignatureException {
return getDigest("HmacSHA256", sharedSecret, data, true);
}
private static String getDigest(String algorithm, String sharedSecret, String data, boolean toLower) throws SignatureException {
try {
Mac sha256HMAC = Mac.getInstance(algorithm);
SecretKeySpec secretKey = new SecretKeySpec(sharedSecret.getBytes(StandardCharsets.UTF_8), algorithm);
sha256HMAC.init(secretKey);
byte[] hashByte = sha256HMAC.doFinal(data.getBytes(StandardCharsets.UTF_8));
String hashString = toHex(hashByte);
return toLower ? hashString.toLowerCase() : hashString;
} catch (Exception e) {
throw new SignatureException(e);
}
}
private static String toHex(byte[] bytes) {
BigInteger bi = new BigInteger(1, bytes);
return String.format("%0" + (bytes.length << 1) + "X", bi);
}
}
somebody can help me please?
The URL you are using:
https://sandbox.api.visa.com/cybersource/payments/flex/v1/keys?apikey={apikey}
Should be:
https://sandbox.api.visa.com/cybersource/payments/flex/v1/keys?apikey=6DC0NMXO53QQFE6NFOLE213HXA-pvG6xE-1NtuCd5oOQr-O-s
As on Feb 2020, If some one still has issue below points can help resolve issue.
Please make sure you have generated API Key and Secret for your sandbox project.
You can get these details in Dashboard -> Project -> Credentials -> Inbound and Authentication Keys -> API Key / Secret.
Please check the "Status" of the Key which should be Active.
If your "Credentials" tab does not have details for "Inbound and Authentication Keys" Please make sure to add the respective API then this section automatically appears.
Visa has "Visa Developer Center PlayGround" [similar to SoapUI/Postman] tool where you can easily test your API's. Unfortunately this is only supported with Windows as on Feb 2020, In future they may release the same for Mac/Linux too.
You can find this tool in Dashboard -> Project -> Assets -> Bottom of the page.
I am having problem to make work jaspyt in this scenario:
StrongTextEncryptor textEncryptor = new StrongTextEncryptor();
textEncryptor.setPassword("myPassword");
String myEncryptedParam = textEncryptor.encrypt("myClearMessage");
myObject.setCallbackUrl("http://myhost/notification?myparam="+myEncryptedParam);
When I receive the callback url and try to decrypt the param 'myParam' provided in the url WITH THE SAME STRONGTEXTENCRYPTOR used in the request, it raises an exception:
org.jasypt.exceptions.EncryptionOperationNotPossibleException
at org.jasypt.encryption.pbe.StandardPBEByteEncryptor.decrypt(StandardPBEByteEncryptor.java:1055)
at org.jasypt.encryption.pbe.StandardPBEStringEncryptor.decrypt(StandardPBEStringEncryptor.java:725)
at org.jasypt.util.text.StrongTextEncryptor.decrypt(StrongTextEncryptor.java:118)
at com.softlysoftware.caligraph.util.Util.decryptMessage(Util.java:30)
Digging a bit more in the exception I get:
BadPaddingException: Given final block not properly padded
If I test the encryption/decryption process without httprequest, works ok.
The problem is that StrongTextEncryptor uses StandardPBEStringEncryptor which in turn uses Base64 to encode the ciphertexts. The problem is that Base64 has a / character which is not URL-safe. When you try to decrypt, the parameter parser that you use probably drops those / characters which makes the ciphertext incomplete.
The easiest solution is probably to change the offending characters with replace all:
myEncryptedParam.replaceAll("/", "_").replaceAll("\\+", "-");
and back again before you try to decrypt:
receivedParam.replaceAll("_", "/").replaceAll("-", "\\+");
This transforms the encoding from the normal Base64 encoding to the "URL and Filename safe" Base 64 alphabet.
Building on Artjom's answer, here is a Jasypt text encryptor wrapper
import org.jasypt.util.text.TextEncryptor;
public class UrlSafeTextEncryptor implements TextEncryptor {
private TextEncryptor textEncryptor; // thread safe
public UrlSafeTextEncryptor(TextEncryptor textEncryptor) {
this.textEncryptor = textEncryptor;
}
public String encrypt(String string) {
String encrypted = textEncryptor.encrypt(string);
return encrypted.replaceAll("/", "_").replaceAll("\\+", "-");
}
public String decrypt(String encrypted) {
encrypted = encrypted.replaceAll("_", "/").replaceAll("-", "\\+");
return textEncryptor.decrypt(encrypted);
}
}
and corresponding test case
import org.jasypt.util.text.StrongTextEncryptor;
import org.jasypt.util.text.TextEncryptor;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class UrlSafeTextEncryptorTest {
private String password = "12345678";
protected TextEncryptor encryptor;
protected UrlSafeTextEncryptor urlSafeEncryptor;
#Before
public void init() {
StrongTextEncryptor encryptor = new StrongTextEncryptor(); // your implementation here
encryptor.setPassword(password);
this.encryptor = encryptor;
this.urlSafeEncryptor = new UrlSafeTextEncryptor(encryptor);
}
#Test
public void scramble_roundtrip_urlSafe() {
int i = 0;
while(true) {
String key = Integer.toString(i);
String urlSafeEncrypted = urlSafeEncryptor.encrypt(key);
Assert.assertFalse(urlSafeEncrypted, urlSafeEncrypted.contains("/"));
Assert.assertEquals(key, urlSafeEncryptor.decrypt(urlSafeEncrypted));
if(urlSafeEncrypted.contains("_")) {
break;
}
i++;
}
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 3 years ago.
Improve this question
I am working on a web application developed using Java and AngularJS and chose to implement token authentication and authorization.
For the exercise purpose, I've come to the point where I send the credentials to the server, generate a random token store it and send it back to the client.
At every request to the server I'm attaching the token in the header and it works perfectly.
For the authentication point of view is perfect and wouldn't need more.
However, I now want to keep track of the user type (admin, regular user...), as well as it's id, or any other unique field; as I understood I have to encrypt that in the token that I'm sending back to the client during the log in action. Is that correct?
Is there any JWT library that you used and can generate, encrypt and decrypt such tokens?
A link to the library's API and Maven dependency would be much appreciated.
Thanks
JJWT aims to be the easiest to use and understand JWT library for the JVM and Android:
https://github.com/jwtk/jjwt
If anyone in the need for an answer,
I used this library: http://connect2id.com/products/nimbus-jose-jwt
Maven here: http://mvnrepository.com/artifact/com.nimbusds/nimbus-jose-jwt/2.10.1
By referring to https://jwt.io/ you can find jwt implementations in many languages including java. Also the site provide some comparison between these implementation (the algorithms they support and ....).
For java these are mentioned libraries:
https://github.com/jwtk/jjwt
https://github.com/auth0/java-jwt ( A tutorial at https://auth0.com/docs/server-apis/java)
https://bitbucket.org/b_c/jose4j
https://bitbucket.org/connect2id/nimbus-jose-jwt
This library seems to work well: https://code.google.com/p/jsontoken/ .
It depends on Google Guava. Here are the Maven artifacts:
<dependency>
<groupId>com.googlecode.jsontoken</groupId>
<artifactId>jsontoken</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
The library is in fact used by Google Wallet.
Here is how to create a jwt, and to verify it and deserialize it:
import java.security.InvalidKeyException;
import java.security.SignatureException;
import java.util.Calendar;
import java.util.List;
import net.oauth.jsontoken.JsonToken;
import net.oauth.jsontoken.JsonTokenParser;
import net.oauth.jsontoken.crypto.HmacSHA256Signer;
import net.oauth.jsontoken.crypto.HmacSHA256Verifier;
import net.oauth.jsontoken.crypto.SignatureAlgorithm;
import net.oauth.jsontoken.crypto.Verifier;
import net.oauth.jsontoken.discovery.VerifierProvider;
import net.oauth.jsontoken.discovery.VerifierProviders;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.joda.time.DateTime;
import com.google.common.collect.Lists;
import com.google.gson.JsonObject;
/**
* Provides static methods for creating and verifying access tokens and such.
* #author davidm
*
*/
public class AuthHelper {
private static final String AUDIENCE = "NotReallyImportant";
private static final String ISSUER = "YourCompanyOrAppNameHere";
private static final String SIGNING_KEY = "LongAndHardToGuessValueWithSpecialCharacters#^($%*$%";
/**
* Creates a json web token which is a digitally signed token that contains a payload (e.g. userId to identify
* the user). The signing key is secret. That ensures that the token is authentic and has not been modified.
* Using a jwt eliminates the need to store authentication session information in a database.
* #param userId
* #param durationDays
* #return
*/
public static String createJsonWebToken(String userId, Long durationDays) {
//Current time and signing algorithm
Calendar cal = Calendar.getInstance();
HmacSHA256Signer signer;
try {
signer = new HmacSHA256Signer(ISSUER, null, SIGNING_KEY.getBytes());
} catch (InvalidKeyException e) {
throw new RuntimeException(e);
}
//Configure JSON token
JsonToken token = new net.oauth.jsontoken.JsonToken(signer);
token.setAudience(AUDIENCE);
token.setIssuedAt(new org.joda.time.Instant(cal.getTimeInMillis()));
token.setExpiration(new org.joda.time.Instant(cal.getTimeInMillis() + 1000L * 60L * 60L * 24L * durationDays));
//Configure request object, which provides information of the item
JsonObject request = new JsonObject();
request.addProperty("userId", userId);
JsonObject payload = token.getPayloadAsJsonObject();
payload.add("info", request);
try {
return token.serializeAndSign();
} catch (SignatureException e) {
throw new RuntimeException(e);
}
}
/**
* Verifies a json web token's validity and extracts the user id and other information from it.
* #param token
* #return
* #throws SignatureException
* #throws InvalidKeyException
*/
public static TokenInfo verifyToken(String token)
{
try {
final Verifier hmacVerifier = new HmacSHA256Verifier(SIGNING_KEY.getBytes());
VerifierProvider hmacLocator = new VerifierProvider() {
#Override
public List<Verifier> findVerifier(String id, String key){
return Lists.newArrayList(hmacVerifier);
}
};
VerifierProviders locators = new VerifierProviders();
locators.setVerifierProvider(SignatureAlgorithm.HS256, hmacLocator);
net.oauth.jsontoken.Checker checker = new net.oauth.jsontoken.Checker(){
#Override
public void check(JsonObject payload) throws SignatureException {
// don't throw - allow anything
}
};
//Ignore Audience does not mean that the Signature is ignored
JsonTokenParser parser = new JsonTokenParser(locators,
checker);
JsonToken jt;
try {
jt = parser.verifyAndDeserialize(token);
} catch (SignatureException e) {
throw new RuntimeException(e);
}
JsonObject payload = jt.getPayloadAsJsonObject();
TokenInfo t = new TokenInfo();
String issuer = payload.getAsJsonPrimitive("iss").getAsString();
String userIdString = payload.getAsJsonObject("info").getAsJsonPrimitive("userId").getAsString();
if (issuer.equals(ISSUER) && !StringUtils.isBlank(userIdString))
{
t.setUserId(new ObjectId(userIdString));
t.setIssued(new DateTime(payload.getAsJsonPrimitive("iat").getAsLong()));
t.setExpires(new DateTime(payload.getAsJsonPrimitive("exp").getAsLong()));
return t;
}
else
{
return null;
}
} catch (InvalidKeyException e1) {
throw new RuntimeException(e1);
}
}
}
public class TokenInfo {
private ObjectId userId;
private DateTime issued;
private DateTime expires;
public ObjectId getUserId() {
return userId;
}
public void setUserId(ObjectId userId) {
this.userId = userId;
}
public DateTime getIssued() {
return issued;
}
public void setIssued(DateTime issued) {
this.issued = issued;
}
public DateTime getExpires() {
return expires;
}
public void setExpires(DateTime expires) {
this.expires = expires;
}
}
This is based on code here: https://developers.google.com/wallet/instant-buy/about-jwts
And Here: https://code.google.com/p/wallet-online-sample-java/source/browse/src/com/google/wallet/online/jwt/util/WalletOnlineService.java?r=08b3333bd7260b20846d7d96d3cf15be8a128dfa
IETF has suggested jose libs on it's wiki:
http://trac.tools.ietf.org/wg/jose/trac/wiki
I would highly recommend using them for signing. I am not a Java guy, but seems like jose4j seems like a good option. Has nice examples as well: https://bitbucket.org/b_c/jose4j/wiki/JWS%20Examples
Update: jwt.io provides a neat comparison of several jwt related
libraries, and their features. A must check!
I would love to hear about what other java devs prefer.
I found this to be small and complete https://github.com/auth0/java-jwt
This page keeps references to implementations in various languages, including Java, and compares features: http://kjur.github.io/jsjws/index_mat.html
If you only need to parse unsigned unencrypted tokens you could use this code:
boolean parseJWT_2() {
String authToken = getToken();
String[] segments = authToken.split("\\.");
String base64String = segments[1];
int requiredLength = (int)(4 * Math.ceil(base64String.length() / 4.0));
int nbrPaddings = requiredLength - base64String.length();
if (nbrPaddings > 0) {
base64String = base64String + "====".substring(0, nbrPaddings);
}
base64String = base64String.replace("-", "+");
base64String = base64String.replace("_", "/");
try {
byte[] data = Base64.decode(base64String, Base64.DEFAULT);
String text;
text = new String(data, "UTF-8");
tokenInfo = new Gson().fromJson(text, TokenInfo.class);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
https://github.com/networknt/jsontoken
This is a fork of original google jsontoken
It has not been updated since Sep 11, 2012 and depends on some old packages.
What I have done:
Convert from Joda time to Java 8 time. So it requires Java 8.
Covert Json parser from Gson to Jackson as I don't want to include two Json parsers to my projects.
Remove google collections from dependency list as it is stopped long time ago.
Fix thread safe issue with Java Mac.doFinal call.
All existing unit tests passed along with some newly added test cases.
Here is a sample to generate token and verify the token. For more information, please check https://github.com/networknt/light source code for usage.
I am the author of both jsontoken and Omni-Channel Application Framework.