How to encrypt JWT secret code for protect it in case of APK decompilation? - jwt

I have a problem with JWT. If someone decompiles my APK, they can see the secret code I used to create my token. Example code, the code is secret:
String originalInput = "secret";
String encodedString =Base64Utils.encode(originalInput.getBytes());
String jwt = Jwts.builder().claim("emailId","test123#gmail.com").claim("user", "123456")
.claim("phoneNo", "1111111111")
.signWith(SignatureAlgorithm.HS256, encodedString)
.compact();

As there are a client (the APK) and a backend, you should use an asymmetric algorithm such as RS256, PS256 or ES256, not a symmetric one (HS256).
If the issuer of the token is your backend, you only need the public key on client side (your APK). This key can safely be shipped as it is public.
If the client is the issuer, key should not be shipped with your application but generated on the device and securely stored using the Keystore API (https://developer.android.com/training/articles/keystore). The associated public key should be sent to the backend. This means that each client has a uniquely generated private key.

Related

Keycloak public key is not base64url encoded

I copied public key from my realm settings and tried to validate in https://jwt.io. It says "Error: Looks like your JWT header is not encoded correctly using base64url". I am using the key to authenticate by sending it has client_assertion. Any help on how to get or generate correct JWT in Keycloak is so much appreciated
Header and Payload section is blank in jwt.io
This is steps to create Public Key and create a JWT
Switching Algorithm is "RS256" in JWT.io
the public key and private key will generate by JWO.io
Update header and payload section
the token will be generate in Encoded section
if you want to generate public key from Keycloak.
call cert API and copy n value
paste this node java-script and run it by "node get-publick-key.js"
//getPem = function(modulus_base);
var getPem = require('rsa-pem-from-mod-exp');
//modulus should be a base64/base64Url string
var modulus = "388m-vc59JVeHP6kbHRtykkky41sby3gldYs8JY3I6xrI_cUs7dbCLDeVtPq78359sGujTtVrT6-P_VOPQqwJEWQQJ3Yvw5zpX510o5UBHob-qmbTopvB0tiJPBi-GXU_Vwx84unR6udVaXXg_FODxqP-vQS7wPwt_omdPW8a5gp8H3uhqEckNxGd2Cp7mFwC2rcwEjBpZBFGoQo8lvGpYBCzzPfSEkET-CvAnrMM8AhqtC0qRhBBfOdzYDclxJYmXb2wz8OhIflgySOMrhdG-oqugp4wxLk2fE528Sz6tdhFwRgWwcOKFxvPNW6-0puRCbW3vKV89jhXMuwtE6aXQ";
//exponent should be base64/base64url
var exponent = "AQAB";
var pem = getPem(modulus, exponent);
console.log(pem);
it will be print public key
-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEA388m+vc59JVeHP6kbHRtykkky41sby3gldYs8JY3I6xrI/cUs7db
CLDeVtPq78359sGujTtVrT6+P/VOPQqwJEWQQJ3Yvw5zpX510o5UBHob+qmbTopv
B0tiJPBi+GXU/Vwx84unR6udVaXXg/FODxqP+vQS7wPwt/omdPW8a5gp8H3uhqEc
kNxGd2Cp7mFwC2rcwEjBpZBFGoQo8lvGpYBCzzPfSEkET+CvAnrMM8AhqtC0qRhB
BfOdzYDclxJYmXb2wz8OhIflgySOMrhdG+oqugp4wxLk2fE528Sz6tdhFwRgWwcO
KFxvPNW6+0puRCbW3vKV89jhXMuwtE6aXQIDAQAB
-----END RSA PUBLIC KEY-----
I have written a Java program using JJWT library to generate JWT from the JKS file that is generated from Client-Keys-Generate new keys and certificate section and was able to validate JWT and signature in jwt.io

ACM PCA Issue certificate for client authentication and signing data

I'm trying to implement MTLS client authentication using AWS ACM Private CA to issue X.509 client certificates.
The certificate and the correlating private key is supposed to be stored in a password protected PKCS#12 file.
The private key will also be used by the client to sign data.
If I request a new certificate using aws-acm-sdk:
RequestCertificateResult response = acm.requestCertificate(new RequestCertificateRequest()
.withCertificateAuthorityArn(CA_ARN)
.withIdempotencyToken("1234")
.withDomainName("localhost.com"));
return response.getCertificateArn();
And then export the it using the arn, I get a certificate, certificateChain and a privateKey as strings.
ExportCertificateResult response = acm.exportCertificate(new ExportCertificateRequest()
.withCertificateArn(certificateArn)
.withPassphrase(ByteBuffer.wrap(password.getBytes())));
String certificate = response.getCertificate();
String certificateChain = response.getCertificateChain();
String privateKey = response.getPrivateKey();
But I'm not able to add any type of identifier that let's me tie the certificate to a user during authentication (I'm using Java and Spring security x509 authentication, which extracts e.g. the subject CN (Common Name) from the certificate which then can be used to identify a user).
If I want to add custom attributes to the certificate, I need to issue a certificate through the aws-acm-pca-sdk:
IssueCertificateRequest request = new IssueCertificateRequest()
.withCertificateAuthorityArn(CA_ARN)
.withCsr(stringToByteBuffer(getCSR()))
.withTemplateArn("arn:aws:acm-pca:::template/EndEntityClientAuthCertificate_APIPassthrough/V1")
.withSigningAlgorithm(SigningAlgorithm.SHA256WITHRSA)
.withValidity(new Validity()
.withValue(365L)
.withType(ValidityPeriodType.DAYS))
.withIdempotencyToken(userId)
.withApiPassthrough(new ApiPassthrough()
.withSubject(new ASN1Subject()
.withCustomAttributes(List.of(
new CustomAttribute()
.withObjectIdentifier("1.3.6.1.4.1") // CustomOID
.withValue("userId")))));
return acmPca.issueCertificate(request).getCertificateArn();
But if I use the sdk to get the certificate, it doesn't contain any private key.
GetCertificateResult response = acmPca.getCertificate(new GetCertificateRequest()
.withCertificateAuthorityArn(CA_ARN)
.withCertificateArn(certificateArn));
String certificate = response.getCertificate();
String certificateChain = response.getCertificateChain();
So, when I read documentation I found that I need to import it to ACM in order to export it and get the private key.
But in order to import it to ACM I also need to provide the private key..
But as I understand it, the private key should be used when issuing the certificate in the first place?
Should I create a new public/private key pair using KMS or what am I supposed to do?
Im confused.. Please help!
I had misinterpreted the responsibility of the PCA.
The PCA is only responsible for issuing certificates, not keys or even CSR (Certificate Signing Requests).
I assumed that the CSR were created by PCA, so the getCSR() method actually fetched the CA's CSR from PCA, while the actual CSR should be generated internally using a private key which has been generated either programmatically or using KMS.

Signing JWT token with per-user key rather than application-wide

Normally, JWT tokens are signed with an application-wide secret or an asymmetric key pair. However, I am integrating into a system that uses a per-user secret that is in fact the salt of the password in the Users table (called private_key there).
I find this system a bit odd. It was apparently meant to make sure that if a user changed his password, the issued tokens would stop working. But it does kill the main advantage of JWT: for any other system to be able to accept the token without having to call the Auth service to validate it. In this case, decoding the token requires to decode it without validation, fetching the database user/private key and then validating it.
The .net code:
List<Claim> claims = new List<Claim>()
{
new Claim("UserUUID", user.UserUUID.ToString())
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(user.PrivateKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _configuration["JwtIssuer"],
audience: _configuration["JwtIssuer"],
claims: claims,
expires: expirationDate,
signingCredentials: creds);
return Ok(new
{
access_token = new JwtSecurityTokenHandler().WriteToken(token),
expires_on = expirationDate
});
Is this actually reasonable and if there is an issue other than validation issues, why is it bad ?
I have seen a similar question but it doesn't address whether this scheme is a good idea, bad idea or just useless burden.

How to setup public key for verifying JWT tokens from Keycloak?

I'm writing backend microservice that receives requests from front-end which have Authorisation: Bearer ... header, with token obtained from keycloak (which is inside docker container).
I got the RSA public key to verify the signature of that token from Keys section of realm settings, but it seems that when container with keycloak restarts, it regenerates pair of keys, and my public key set in service config becomes invalid.
What is the proper way to work with RSA public key from keycloak? Is there some way to configure it to use a fixed pair of keys for realm? Are keys exported when realm exports? Or I have to get the public key from keycloak using url like http://keycloak:8080/auth/realms/:realm_name:, which I rather not to do because this adds a dependency between keycloak and backend.
You should verify the JWT token's signature based on the issuer identity server's /.well-known/jwks endpoint.
1) Query the issuer identity server's /.well-known/jwks endpoint (JWKS stands for JSON Web Key Set)
2) From the JWKS, get the JWK (JSON Web Key) with the same kid (Key ID) as the Bearer token we are verifying. To get the kid from your JWT token, first decode it using jwt.io's Debugger tool.
3) As long as identity server-issued tokens are verified with an asymmetric cryptography algorithm (e.g.: RS256), we can verify the signature with the Public Key only (so you won't need the Private Key)
4) The Public Key can be retrieved from the JWK (it is the x5c entry in the JWK JSON )
5) Verify the JWT Bearer token's signature with this Public Key.
For example, in Java you can verify it like this:
// verify JWT signature based on Access Identity's JWKS RSA public key (RS256)
try {
Jwk jwk = new UrlJwkProvider(new URL(issuer + Constants.JWKS_ENDPOINT)).get(decodedJWT.getKeyId());
final PublicKey publicKey = jwk.getPublicKey();
if (!(publicKey instanceof RSAPublicKey)) {
throw new IllegalArgumentException("Key with ID " + decodedJWT.getKeyId() + " was found in JWKS but is not a RSA-key.");
}
Algorithm algorithm = Algorithm.RSA256((RSAPublicKey) publicKey, null);
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer(issuer)
.build(); //Reusable verifier instance
verifier.verify(bearerToken);
LOGGER.info("Token verified!");
} catch (Exception e) {
LOGGER.error(e.getMessage());
throw new InvalidAccessTokenException("JWTVerificationException - Invalid token signature.");
}

How to verify String using JWSVerifier

New to JWT
I want to verify my string token which is generated as below
String productkey:which is signed and encoded format.
String publickey:Generated key from simmulator and store as string
JWSVerifier verifier= new ECSDVerifier(ECKey.parse(publickey))
Boolean test=verifier.verify(productkey);
Please suggest which appropriate method I have to used.
If you are new to JWT, I would suggest you to use JJwt API. You can easily sign your tokens and verify them.
Snippet to generate JWT token:
Jwts.builder()
.setClaims(payload)
.setExpiration(expiryDate)
.signWith(SignatureAlgorithm.RS256, privateKey )
.compact();
Snippet to verify the token with public key:
Jwts.parser()
.setSigningKey(publicKey )
.parseClaimsJws(jwtToken)
JJwt Maven/Gradle link
Hope this helps.