I've tried using my public key vs. using the private key, putting a b in front, doing 3 vs. 1 quotes vs. one quote (and many more things I see here on Stackoverflow) and I keep getting the following error:
ValueError: Could not deserialize key data.
Any ideas?
import jwt
secret_key='''MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwE...pTeoOgWZ'''
token = '''eyJraWQiOiI4NkQ4OEtmIiwiNG2Bua1WoKEI8T..._cXnyThWA'''
#public_key = '''iGaLqP6y-SJCCBq5Hv6pGDbG_SQ11MNj...Mb0jcOTmBRZA2QuYw-zHLwQ'''
payload = jwt.decode(token, secret_key, algorithms=['RS256'])
return payload
Try with the complete public key including the begin and end delimiters and use """ or ''' for a multiline string:
import jwt
token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.K71d-kndywmuxJR-SzDqTARcHJBsHezMeRtDwn4S0NMd3ZmW1LKKqoVQv8rMNam4HK6hsSmB0sqIpKfiLFn73HC1j9-fdBafZNy-9eL4cNr1ldwxj5jD6CwPMjT0mOB01liHFPiIfHDabYV2FzFEV8oaX8CxVL7_CLLv2I01NHo"
pubkey = """-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCcbV4zk01saMn/VzIDN7rOY8D
BTYGnH6fnYB/wTKBHme6MpuOv+4d48ZKDseP8EcTFQmmAmKeKRGJUzSJ9cN2KlND
a4y2gkEsqh8a9U/7492hVWNB6JkSPrdqrkRho9/q9gCcDlTZROY/RDuf3Y1F1riV
tiFvXvfCp75fpLceIQIDAQAB
-----END PUBLIC KEY-----"""
payload = jwt.decode(token, pubkey, algorithms=['RS256'])
print(payload)
Output:
{'sub': '1234567890', 'name': 'John Doe', 'iat': 1516239022}
(no worries about the key, I just created it online just for demonstration purpose)
I figured it out. My public key above wasn't actually a public key. It is a RSA key modulus. I had to use this tutorial to take this RSA key modulus and the exponent to generate a public key. When i did this, then the JWT.decode functionality worked just fine.
Thanks #jps for your help!
Related
I am trying to convert this java code for generating JWT token in python.
String privateKeyContent = privateKey
.replaceAll(Definitions.ApiGeneral.LINE_BREAKER, "")
.replace(Definitions.AuthProperty.PRIVATE_KEY_START, "")
.replace(Definitions.AuthProperty.PRIVATE_KEY_END, "");
PKCS8EncodedKeySpec keySpecPKCS8 = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyContent));
KeyFactory kf = KeyFactory.getInstance(Definitions.AuthProperty.RSA_KEY_FACTORY);
PrivateKey privKey = kf.generatePrivate(keySpecPKCS8);
String jwtAudUrl = System.getenv(Definitions.IamProperty.IAM_URL_KEY) + System.getenv(Definitions.IamProperty.JWT_AUD_URI_KEY);
String jwtToken = Jwts.builder()
.setAudience(jwtAudUrl)
.setSubject(serviceId)
.setIssuer(serviceId)
.setExpiration(new Date(new Date().getTime() + TimeUnit.MINUTES.toMillis(Definitions.AuthProperty.JWT_TOKEN_EXPIRY_IN_MINUTES)))
.signWith(privKey)
.compact();
Python:
import jwt
serviceID = "abc"
secret = '-----BEGIN RSA PRIVATE KEY-----MIIEogIBAAKCAQEAhstYtRbkgQkFwlVr8QjSCQqqRTDMKWHdIGRYBpXcQmvKfagId9nBA2Ygh7cOrT9g8MhxYo8U1jYmPQpv6gf3LgO/J0qspLdaAhZP6LusA/HHJBR7kjTXBsLcsEDyd8S0UioBYP3DLvtWhGIR2f4o7SH1TlE96tldV6FZKGO2NHsJrJwTd+ym0AeZe0b7QZLe43LBCTLdqk05U34jrknJliSAEbGqYg4h6nrJsKBC/0pmiQ9ptD1N/Kl4bqffMWIbZq2bPP6jFrmBLe+7yTeVMKltVbJZys4nHhyYngBtbAxynXeB2tpE8If7cK75fj42MlFgquEiEZZVSzNNmrmPOwIDAQABAoH/B18Xes/Fr0jPB9GkFYpl8hijNyV0BM9VSHA0YCfR49ABQt3tmKBP7d+n58QbCV5t7r0Hdlxcx1ouvSfU9vd4jQunaH6s8lU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CD1CboTvDfmkD+opkLM6YZpW9CRT7Szn7ivdFr5KqGQZUZOwn3k=-----END RSA PRIVATE KEY-----'
due_date = datetime.now() + timedelta(minutes=10)
header = {"alg": "RS256"}
expiry = int(due_date.timestamp())
payload = {"iss": serviceID, "sub": serviceID, "exp": expiry, "aud": iam_url + "/oauth2/access_token"}
priv_rsakey = serialization.load_pem_private_key(secret.encode('utf8'), password=None, backend=default_backend())
token=jwt.encode(payload, priv_rsakey, algorithm='RS256')
However, I keep on getting this error :
ValueError: ('Could not deserialize key data. The data may be in an incorrect format, it may be encrypted with an unsupported algorithm, or it may be an unsupported key type (e.g. EC curves with explicit parameters).', [_OpenSSLErrorWithText(code=503841036, lib=60, reason=524556, reason_text=b'error:1E08010C:DECODER routines::unsupported')])
Can someone please help me with this ?
The issue is precisely identified in the error message: Your private key is incorrectly formatted. A PEM encoded key consists of the Base64 encoded body, which contains a line break after every 64 characters, and a header and footer on separate lines. Your key is missing the line breaks.
load_pem_private_key() expects at least header and footer on separate lines, but is tolerant about line breaks in the body, i.e. they are optional. So you have to pass your key e.g. like this:
secret = '-----BEGIN RSA PRIVATE KEY-----\nMIIEogIBAAKCAQEAhstYtRbkgQkFwlVr8QjSCQqqRTDMKWHdIGRYBpXcQmvKfagId9nBA2Ygh7cOrT9g8MhxYo8U1jYmPQpv6gf3LgO/J0qspLdaAhZP6LusA/HHJBR7kjTXBsLcsEDyd8S0UioBYP3DLvtWhGIR2f4o7SH1TlE96tldV6FZKGO2NHsJrJwTd+ym0AeZe0b7QZLe43LBCTLdqk05U34jrknJliSAEbGqYg4h6nrJsKBC/0pmiQ9ptD1N/Kl4bqffMWIbZq2bPP6jFrmBLe+7yTeVMKltVbJZys4nHhyYngBtbAxynXeB2tpE8If7cK75fj42MlFgquEiEZZVSzNNmrmPOwIDAQABAoH/B18Xes/Fr0jPB9GkFYpl8hijNyV0BM9VSHA0YCfR49ABQt3tmKBP7d+n58QbCV5t7r0Hdlxcx1ouvSfU9vd4jQunaH6s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wwfh9uH9jAhk9OEvoNg3F3mQl6hjmHPd1xUNvRTqwnV+VvQnw7Aeq2TZMcAKwbXf3+p430wMsxR6m0Y7rGi0FIxWbILp0RK9AoGBAIfiPBXnGYOsOysRtb42FHQN9WgI+eoZof10IFz6XWr12Bda8Wicz5vGcsWUx9YeFxdXTQOOJ5CASEiDwW5hOlqK4YBqSqolWv3YO4Gz9i00TOFs4py8EVSr3z6ekq5UbkHwY7exxLPei/dfYuE/WSN/UfJWWyev1M+r4oz7iobzAoGAKe8S56LvWT+P6/l0l3txuvqPLxmAHKKGm69ecxHprskfr/JJm91PaBMb27VmfKgY5eXSsJkL4svvUebQQCt7CmIhQ1mtmo0zGrKPvG4cqRde5rYintogyQXuRFtHmmsp4PM1PnNOAnHQ9BU/kx1PMQL712A8MXK5i6bOfxY3W2ECgYEAp9cw3NeMSy/WcXyZoyNFUdEQiHTJGPBtELjHWRnjMU1454EkWYYPiYXUnElfxP6InxHgMNbGVsd1BUEhXOdSUS5bO/WBOOPqSh6MIGfKFuMN/9SI/Y/UZKltCD1CboTvDfmkD+opkLM6YZpW9CRT7Szn7ivdFr5KqGQZUZOwn3k=
-----END RSA PRIVATE KEY-----'''
With this change the code works (after adding the missing iam_url and the missing import statements).
Note that PKCS8EncodedKeySpec in the Java code expects a DER encoded private key in PKCS#8 format, while in the Python code a PEM encoded private key in PKCS#1 format is applied.
A DER encoded key results from a PEM encoded key by removing header, footer and all line breaks, and Base64 decoding the rest. The Cryptography library supports the import of a DER encoded private key with load_der_private_key():
import base64
secret = base64.b64decode('MIIEogIBAAKCAQEAhstYtRbkgQkFwlVr8QjSCQqqRTDMKWHdIGRYBpXcQmvKfagId9nBA2Ygh7cOrT9g8MhxYo8U1jYmPQpv6gf3LgO/J0qspLdaAhZP6LusA/HHJBR7kjTXBsLcsEDyd8S0UioBYP3DLvtWhGIR2f4o7SH1TlE96tldV6FZKGO2NHsJrJwTd+ym0AeZe0b7QZLe43LBCTLdqk05U34jrknJliSAEbGqYg4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4svvUebQQCt7CmIhQ1mtmo0zGrKPvG4cqRde5rYintogyQXuRFtHmmsp4PM1PnNOAnHQ9BU/kx1PMQL712A8MXK5i6bOfxY3W2ECgYEAp9cw3NeMSy/WcXyZoyNFUdEQiHTJGPBtELjHWRnjMU1454EkWYYPiYXUnElfxP6InxHgMNbGVsd1BUEhXOdSUS5bO/WBOOPqSh6MIGfKFuMN/9SI/Y/UZKltCD1CboTvDfmkD+opkLM6YZpW9CRT7Szn7ivdFr5KqGQZUZOwn3k=')
priv_rsakey = serialization.load_der_private_key(secret, password=None, backend=default_backend())
load_pem_private_key() and load_der_private_key() support both PKCS#8 and PKCS#1 format.
Tried to decode the JWT provided by the google. I have used phone number authentication with google and returned verifyIdToken which is a jwt token. I have tried to verify with the jwt package available in python but it throws error.
When I tried to verify the signature with jwt.io It give a verified signature but it python can't.
Here is the link about the documentation of the google
The public key used is
-----BEGIN CERTIFICATE-----\nMIIDHDCCAgSgAwIBAgIICc/DAoum8fgwDQYJKoZIhvcNAQEFBQAwMTEvMC0GA1UE\nAxMmc2VjdXJldG9rZW4uc3lzdGVtLmdzZXJ2aWNlYWNjb3VudC5jb20wHhcNMjIw\nNTAzMDkzODM5WhcNMjIwNTE5MjE1MzM5WjAxMS8wLQYDVQQDEyZzZWN1cmV0b2tl\nbi5zeXN0ZW0uZ3NlcnZpY2VhY2NvdW50LmNvbTCCASIwDQYJKoZIhvcNAQEBBQAD\nggEPADCCAQoCggEBAK7kUdLrSbHeVqsGd2KC2Kt4Bup69/+2cXmfGALrYFGsKdkE\nUdeV8Mdtbqtk5njUAzXibrZb+x3jfyG/WJZXbFXgBPkSHIsIcwFFnIMQMHRfXXwV\nq1Qe5U52x2ztSYGPtz3UNBUUXsHZLplGdljtjagDqNYX1vYA6ZXItQPr1ycM0i1f\nV7j96qQ0OJjir94B1j5cTVHHtZsqoJgcJXdDabF5zC6G1X3Gxh3OftJBqM0dqWjl\nLmgGQ6CtYRmB10zqotJNa3v9Q6jT0flNpLOswnEW8t44/sjRl3sf2Tv3IMrihZYB\n2CaEvL1b9DAvWfAucrG7x8BKBKTs5u2bowqPKlcCAwEAAaM4MDYwDAYDVR0TAQH/\nBAIwADAOBgNVHQ8BAf8EBAMCB4AwFgYDVR0lAQH/BAwwCgYIKwYBBQUHAwIwDQYJ\nKoZIhvcNAQEFBQADggEBAJpMc+noeLGaKXlBrW30vEnp9KjN+bhf4WipBSV4KlQx\nwxYnZov6hrxhctz0D0rhQmIHNlmgIFkG/ej9sszz4z08MZAxrPUJsaGoIY2e4PQ3\nYOzNHFp4VssK9D1L5jxRxf+/jf0fJf/ZfFKxCzz8tWfpZitHlzmOoSMuUBTIFXmB\nvQuUWeOu3pAT7Z+ddpaLvxbE264Ybd9ujxuFWzmXJCNHh+dOruymEZrpwoOkoAaH\nll7Jr2nEaY/SUCK4QZne3FXIc07rbs9l4C8+yrcG5RkAsVH9gdgtHDgFWLFnxGb8\nQQ8yX4+6Fq/3xWzUWg4PvAIb4aX8Fwc59uBFc7yeSvg=\n-----END CERTIFICATE-----\n
I tried removing \n and I verified it with jwt.io it worked but it doesn't work in the python the code I wrote is
import jwt
key = "-----BEGIN CERTIFICATE-----MIIDHDCCAgSgAwIBAgIICc/DAoum8fgwDQYJKoZIhvcNAQEFBQAwMTEvMC0GA1UEAxMmc2VjdXJldG9rZW4uc3lzdGVtLmdzZXJ2aWNlYWNjb3VudC5jb20wHhcNMjIwNTAzMDkzODM5WhcNMjIwNTE5MjE1MzM5WjAxMS8wLQYDVQQDEyZzZWN1cmV0b2tlbi5zeXN0ZW0uZ3NlcnZpY2VhY2NvdW50LmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK7kUdLrSbHeVqsGd2KC2Kt4Bup69/+2cXmfGALrYFGsKdkEUdeV8Mdtbqtk5njUAzXibrZb+x3jfyG/WJZXbFXgBPkSHIsIcwFFnIMQMHRfXXwVq1Qe5U52x2ztSYGPtz3UNBUUXsHZLplGdljtjagDqNYX1vYA6ZXItQPr1ycM0i1fV7j96qQ0OJjir94B1j5cTVHHtZsqoJgcJXdDabF5zC6G1X3Gxh3OftJBqM0dqWjlLmgGQ6CtYRmB10zqotJNa3v9Q6jT0flNpLOswnEW8t44/sjRl3sf2Tv3IMrihZYB2CaEvL1b9DAvWfAucrG7x8BKBKTs5u2bowqPKlcCAwEAAaM4MDYwDAYDVR0TAQH/BAIwADAOBgNVHQ8BAf8EBAMCB4AwFgYDVR0lAQH/BAwwCgYIKwYBBQUHAwIwDQYJKoZIhvcNAQEFBQADggEBAJpMc+noeLGaKXlBrW30vEnp9KjN+bhf4WipBSV4KlQxwxYnZov6hrxhctz0D0rhQmIHNlmgIFkG/ej9sszz4z08MZAxrPUJsaGoIY2e4PQ3YOzNHFp4VssK9D1L5jxRxf+/jf0fJf/ZfFKxCzz8tWfpZitHlzmOoSMuUBTIFXmBvQuUWeOu3pAT7Z+ddpaLvxbE264Ybd9ujxuFWzmXJCNHh+dOruymEZrpwoOkoAaHll7Jr2nEaY/SUCK4QZne3FXIc07rbs9l4C8+yrcG5RkAsVH9gdgtHDgFWLFnxGb8QQ8yX4+6Fq/3xWzUWg4PvAIb4aX8Fwc59uBFc7yeSvg=-----END CERTIFICATE-----"
token = "XXXXXXXXX"
payload = jwt.decode(token, key.encode(), algorithms=['RS256',])
print(payload)
the error that throwed is
raise ValueError(
ValueError: ('Could not deserialize key data. The data may be in an incorrect format, it may be encrypted with an unsupported algorithm, or it may be an unsupported key type (e.g. EC curves with explicit parameters).', [_OpenSSLErrorWithText(code=75497580, lib=9, reason=108, reason_text=b'error:0480006C:PEM routines::no start line')])
I haven't included the token because it contains data.
I was able to reproduce the following:
import jwt
key = "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu1SU1LfVLPHCozMxH2Mo4lgOEePzNm0tRgeLezV6ffAt0gunVTLw7onLRnrq0/IzW7yWR7QkrmBL7jTKEn5u+qKhbwKfBstIs+bMY2Zkp18gnTxKLxoS2tFczGkPLPgizskuemMghRniWaoLcyehkd3qqGElvW/VDL5AaWTg0nLVkjRo9z+40RQzuVaE8AkAFmxZzow3x+VJYKdjykkJ0iT9wCS0DRTXu269V264Vf/3jvredZiKRkgwlL9xNAwxXFg0x/XFw005UWVRIkdgcKWTjpBP2dPwVZ4WWC+9aGVd+Gyn1o0CLelf4rEjGoXbAAEgAqeGUxrcIlbjXfbcmwIDAQAB\n-----END PUBLIC KEY-----\n"
token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMn0.NHVaYe26MbtOYhSKkoKYdFVomg4i8ZJd8_-RU8VNbftc4TSMb4bXP3l3YlNWACwyXPGffz5aXHc6lty1Y2t4SWRqGteragsVdZufDn5BlnJl9pdR_kdVFUsra2rWKEofkZeIC4yWytE58sMIihvo9H1ScmmVwBcQP6XETqYd0aSHp1gOa9RdUPDvoXQ5oqygTqVtxaDr6wUFKrKItgBMzWIdNZ6y7O9E0DhEPTbE9rfBo6KTFsHAZnMg4k68CDp2woYIaXbmYTWcvbzIuHO7_37GT79XdIwkm95QJ7hYC9RiwrV7mesbY4PAahERJawntho0my942XheVLmGwLMBkQ"
payload = jwt.decode(token, key.encode(), algorithms=['RS256',])
print(payload)
>>> {'sub': '1234567890', 'name': 'John Doe', 'admin': True, 'iat': 1516239022}
I noticed that in your public key there are some escape characters \n inside your string (this may be causing your problem). You should only remove \n that appear inside the key and include them at the beginning and at the end. Try changing your public key to:
key = "-----BEGIN CERTIFICATE-----\nMIIDHDCCAgSgAwIBAgIICc/DAoum8fgwDQYJKoZIhvcNAQEFBQAwMTEvMC0GA1UEAxMmc2VjdXJldG9rZW4uc3lzdGVtLmdzZXJ2aWNlYWNjb3VudC5jb20wHhcNMjIwNTAzMDkzODM5WhcNMjIwNTE5MjE1MzM5WjAxMS8wLQYDVQQDEyZzZWN1cmV0b2tlbi5zeXN0ZW0uZ3NlcnZpY2VhY2NvdW50LmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK7kUdLrSbHeVqsGd2KC2Kt4Bup69/+2cXmfGALrYFGsKdkEUdeV8Mdtbqtk5njUAzXibrZb+x3jfyG/WJZXbFXgBPkSHIsIcwFFnIMQMHRfXXwVq1Qe5U52x2ztSYGPtz3UNBUUXsHZLplGdljtjagDqNYX1vYA6ZXItQPr1ycM0i1fV7j96qQ0OJjir94B1j5cTVHHtZsqoJgcJXdDabF5zC6G1X3Gxh3OftJBqM0dqWjlLmgGQ6CtYRmB10zqotJNa3v9Q6jT0flNpLOswnEW8t44/sjRl3sf2Tv3IMrihZYB2CaEvL1b9DAvWfAucrG7x8BKBKTs5u2bowqPKlcCAwEAAaM4MDYwDAYDVR0TAQH/BAIwADAOBgNVHQ8BAf8EBAMCB4AwFgYDVR0lAQH/BAwwCgYIKwYBBQUHAwIwDQYJKoZIhvcNAQEFBQADggEBAJpMc+noeLGaKXlBrW30vEnp9KjN+bhf4WipBSV4KlQxwxYnZov6hrxhctz0D0rhQmIHNlmgIFkG/ej9sszz4z08MZAxrPUJsaGoIY2e4PQ3YOzNHFp4VssK9D1L5jxRxf+/jf0fJf/ZfFKxCzz8tWfpZitHlzmOoSMuUBTIFXmBvQuUWeOu3pAT7Z+ddpaLvxbE264Ybd9ujxuFWzmXJCNHh+dOruymEZrpwoOkoAaHll7Jr2nEaY/SUCK4QZne3FXIc07rbs9l4C8+yrcG5RkAsVH9gdgtHDgFWLFnxGb8QQ8yX4+6Fq/3xWzUWg4PvAIb4aX8Fwc59uBFc7yeSvg=\n-----END CERTIFICATE-----\n"
I'm writting a little program using SSL sockets. A client sends values to a server and when the server gets the value it checks the client's public key to make sure he's expected to send something. So at first the server is getting all the public keys like this :
cert = f.read()
crtObj = crypto.load_certificate(crypto.FILETYPE_PEM, cert)
pubKeyObject = crtObj.get_pubkey()
pubKeyString = crypto.dump_publickey(crypto.FILETYPE_PEM,pubKeyObject)
with this method, the public key is :
b'-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA7GIzek5JgfFzFCGwnx7X\ncE4QULV/9uyoGgd9HbHYyYcItEcSPU39ORXCrNQGxh09k4oFPBYntjD2gIORF8V4\n6EAC10bFaT18OuM1F/37v+K/+BuvCDTqcS9Y0CRalwPFVYB+yttvZ8fnvO2l/TxF\nsLmZh0yY/ajaHxey/ppUQycGy4xA8XD6VlWFM7+I0t/19rrLN9iMFSym/TgYpBbn\nxyZel8rMW/ACS09nSprEu1BuI+myhhej+cuy3wU8byRTwANpqHxsx5cTwp642TVx\nBKbuO8GHAzEKcrFZnrKcsXr9emWV5ouYiVzehOT4Pd3I2W8qSy6x/Ovv/iS3ojT4\ndQIDAQAB\n-----END PUBLIC KEY-----\n'
and when the server wants to get it from the socket connection like this :
test1 = writer.get_extra_info('ssl_object')
der =test1.getpeercert(binary_form=True)
test = test1.getpeercert()
cert = x509.Certificate.load(der)
pubkey= cert.public_key.unwrap()
print(pem.armor("PUBLIC KEY", pubkey.contents).decode("ASCII"))
the public key printed is :
-----BEGIN PUBLIC KEY-----
AoIBAQDsYjN6TkmB8XMUIbCfHtdwThBQtX/27KgaB30dsdjJhwi0RxI9Tf05FcKs
1AbGHT2TigU8Fie2MPaAg5EXxXjoQALXRsVpPXw64zUX/fu/4r/4G68INOpxL1jQ
JFqXA8VVgH7K229nx+e87aX9PEWwuZmHTJj9qNofF7L+mlRDJwbLjEDxcPpWVYUz
v4jS3/X2uss32IwVLKb9OBikFufHJl6Xysxb8AJLT2dKmsS7UG4j6bKGF6P5y7Lf
BTxvJFPAA2mofGzHlxPCnrjZNXEEpu47wYcDMQpysVmespyxev16ZZXmi5iJXN6E
5Pg93cjZbypLLrH86+/+JLeiNPh1AgMBAAE=
-----END PUBLIC KEY-----
So I don't know if it's a matter of format or if it's really not the same public key I'm getting... but it should be.
Sorry for the long post and thank you very much for reading.
Most(if not all) base64 encoding variants use A-Z, a-z, 0-9 characters to represent data the total is 62 character and some base64 encodings varies in the last 2 characters but most of them use + and / which will complete 64. So the above 2 keys seems to be completely different and the second key is also padded because of = sign at end. The standard base64 encoding is RFC 4648 variant which use + and / and make padding as optional not mandatory like RFC 4880 openpgp base64 encoding.
It was in fact the same keys but the way of getting it was wrong : here the right one from the ssl object :
test1 = writer.get_extra_info('ssl_object')
der =test1.getpeercert(binary_form=True)
crtObj = crypto.load_certificate(crypto.FILETYPE_ASN1, der)
pubKeyObject = crtObj.get_pubkey()
pubKeyString = crypto.dump_publickey(crypto.FILETYPE_PEM, pubKeyObject)
I would like to learn about creating JWT using RSA public and private key. I am a beginner to learn securing my services. I am using pyjwt right now. I got something error with my testing, here it is:
SAMPLEKEY:
privatekey = """-----BEGIN RSA PRIVATE KEY-----MIICXQIBAAKBgQCkC2AfenNMfrU4oMfMZt9aZGBbFjzBTjV9Yttp0GHeVjIKboTwLkiKNqSKrm2Jralbteii2J9h6BeUBpv3B/Os7M0eNeM8B+5Rzm44vcmkzdtufTuX2utjoz8BFjelXw5og2i67NtxgiSHv2x1KCHbGZG+jpDOgjorxFusKbeGjQIDAQABAoGADbMJfvd543x9Y9JBfTdmFaVmSpUL09TVMLhtvGNzmN635RkfrvMeibRQf2hbq3C+QPNrDxZqEQIR3gHDSpj2Z2tGrE95a5o8+I3NBARkKOz41lMFm2AnXZLsM0ma+8S61j8AtELgFuKZWyi2t9A3Otf1+vayZVS/F8pyof0wD10CQQDXDloBpki887jVXtnIauV3Z1744P/uvVkWZOMTMiNF5Xh8SRPn2mNR80vUAAN5SL7zjGyDQeoYKZMRJaLFGsaPAkEAw0bCyz2aA+aWaTM1iyK4XK9/dNPoztE0lmeaHXvI7d1Zp0ipbLwewt4gRbSL7UpxdRQy0ELep4HoSTLt2dQPIwJBANCtS2c4XHKFKIBa5oaUO4+OjdiAM7gMoeqaAMG6sAF99ljbbGZZQnDd3WGclcJVdXzMcOs4xZeml99WnsgWAD8CQAWIfsKFh1Su9voaIl1D6ZduvZzQ2Frr4KKWYu6M8F+VExJDY9GZ7wE0jBONjx11K4vWu63dBzQV4UAZulWexaMCQQCmfoq0l1JtnYhV3LhEN3E8gwUK/0456An5YKunwO8nPrBsrdt/TQ6ZAUzh7JkmabV3h2KXQ+H0/cvfWBOhYaov-----END RSA PRIVATE KEY-----"""
publickey = """-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCkC2AfenNMfrU4oMfMZt9aZGBbFjzBTjV9Yttp0GHeVjIKboTwLkiKNqSKrm2Jralbteii2J9h6BeUBpv3B/Os7M0eNeM8B+5Rzm44vcmkzdtufTuX2utjoz8BFjelXw5og2i67NtxgiSHv2x1KCHbGZG+jpDOgjorxFusKbeGjQIDAQAB-----END PUBLIC KEY-----"""
Here is my sample code:
#app.route('/token')
def token():
encodedToken = jwt.encode({'userid':'1'}, publickey, algorithm = 'RS256')
print(jwt.decode(encodedToken, privatekey, verify=True, algorithms='RS256'))
return "OKE"
And, I am getting this error when running it:
Is there any solution into this ?
Thanks
Basically you'll want to switch the keys, use the private key for "encoding" (signing) and public for "decoding" (verification).
This issue is reported on GitHub here: https://github.com/jpadilla/pyjwt/issues/81
And marked as "closed".
I'm trying to generate/read a RSA-keypair from the publicKey and the privateKey as a String.
Something like this:
priK = "-----BEGIN RSA PRIVATE KEY-----MIIBOQIBAAJAVJhUS0gLqXLOmVv2xG23oFPwim9+rVxGhLUXqKShQCvB3iRMOHn7/GNJumpwmnglcsNXuqAhN0OxqKGGJdtYdwIDAQABAkBP0VrXnSbDvvuIX+k59Xvo3sp7FDAmSoaO+H9WM9+ht5H/f/geIrSEXSIkFLnzniMwtOJ422GmkDkL1F67HuDhAiEAlNauDiq3RqoXufbauyPEOG9fMS2pvB+auT2XCHJhhKsCIQCRgIo7WIRZYnNpNRWaoppUQK3g+aM8sdeBYpbs2nwDZQIgZXIxrmxFAUAb7d+oVFdbfc/DRSTHhPbRoaKuF87GUwMCIFmzaATsLjO42TPMETSS+BfnBAtFe5hIf3Z5pFgC3h9tAiEAgYjug92fmVvE+CcRSg6at7meSEbK/Kxg7Ar4mlkXMlI=-----END RSA PRIVATE KEY-----"
pubK = "-----BEGIN PUBLIC KEY-----MFswDQYJKoZIhvcNAQEBBQADSgAwRwJAVJhUS0gLqXLOmVv2xG23oFPwim9+rVxGhLUXqKShQCvB3iRMOHn7/GNJumpwmnglcsNXuqAhN0OxqKGGJdtYdwIDAQAB-----END PUBLIC KEY-----"
keyPair = RSA.importKey(priK + pubK)
My error that I'm getting is:
in importKey
if lines[1].startswith(b('Proc-Type:4,ENCRYPTED')):
I don't even know if it's possible like that. I didn't really find information about that.
RSA.importKey(key) imports one key. It cannot import concatenated keys.
If you import a private key, then you can extract a public key from that, because common PKCS#1 and PKCS#8 format have all the necessary information to create public key. So, you don't even need to concatenate the public key to it.
Use:
privateKey = RSA.importKey(priK)
publicKey = privateKey.publickey()