I have a generate a token from a key in flutter.This token will serve as the header(authorisation) for the API call request. I am using the https://pub.dev/packages/dart_jsonwebtoken plugin to generate the token
I am able to generate the token using HS256 algorithm. But in my case I have to generate the token using RS256 algorithm.When I try to generate using RS256 algorithm it throws the following error Instance of 'JWTInvalidError'. You can refer the screenshot as well.
The key is valid because in Java code the person was able to implement that.WHat is missing?
This is the code I have implemented using flutter dart_jsonwebtoken package:
import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart';
String token;
void dartJsonWebTokenGenerator() {
Duration delay = new Duration( minutes:3);
final jwt = JWT(
payload:
{
"version": "13",
'user_id': 'XXXXXXXXX',
},
issuer: 'https://github.com/jonasroussel/jsonwebtoken',
audience: 'live-tv',
);
// Sign it (default with HS256 algorithm)
token = jwt.sign(PrivateKey('XXXXXXXXXXXXXXXXXXXXXXXXX'),
algorithm: JWTAlgorithm.RS256,expiresIn: delay );
print('Signed token: $token\n');
}
The equivalent Java code which is to be implemented:
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;
}
}
Along with this I have tried the jose library,corsac_jwt and a few more but I am not getting the proper results in the first place.So if you have any library you can recommend to me ,your are most welcome