Is my RSA key correctly generated - rsa

I use python pycryptodome rto generate my private and public key. This is one example of a public key that I am generating:
(n=0xf56efd1888065abb3ef6e6b1e6e0039ff1fa0b09e1f1ab9869ad933e1f48527c182957f9a767110524c362ac4c460f752d2011ef827ed9680fe58a078f3e8355d9bea6e1285a7a51b3f5022c66f72331a1053fb8a0033b28838026fadfa11da8b0bcb98476ef1c80f53f9814762c1191965733f883ee1d686624123b28140b5b91fcadf33bfe02e196e0f10bdd80cd5babbd6c10179a84d9325424d2b365f7a8274ce6c454b582dba3289c3cea83ae117c5567dba33a1434b9276dc4ab88fbeec68483913fe6c70424aa19165f19d6d7f158eafedbd81046a7bcdd46be0b4ef8f86069a28a98c78e38ff0f413b1cf76aac674f1c04c7b5ff23540f12398c3927, e=0x10001)
I generate it using this piece of code:
keyPair = RSA.generate(bits=2048)
publicKey = f"(n={hex(keyPair.n)}, e={hex(keyPair.e)})"
Somehow, this doesn't look correct to me, because usually, when I create a key using mac os or other method, I have something like
---BEGIN PRIVATE KEY aksdjbvioasv.....(key itself here....) ---END PUBLIC KEY
What am I msising so that my RSA key is generated correctly?

I solved it by doing
pubKey = keyPair.publickey()
pubKeyPEM = pubKey.exportKey()
print("pubKey PEM is:")
print(pubKeyPEM)
Now I get the proper format, that I can now write into a file!

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

jsonwebtoken.verify method giving error from keycloak token

I use the /auth/realms//protocol/openid-connect/certs endpoint and hardcode the x5c public key returned from this endpoint to try to get this code working (wrapped in BEGIN RSA/END RSA tags) like so:
let x5c = "MIICnTCCAYUCBgF9TkI2ijANBgkqhkiG9w0BAQsFADASMRAwDgYDVQQDDAdldmlkZW5zMB4XDTIxMTEyMzE5MjMyMVoXDTMxMTEyMzE5MjUwMVowEjEQMA4GA1UEAwwHZXZpZGVuczCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALgx8kfUyhUz6146LcXJHykE5d/kfkJGHZ1+AH4wfk0Z1rGeNqRUH7bllutre2xrq/EfuKGkuUul8uf7WH3GTyOFJyr1MECnzilYdN8onobpVHXr3SwANCACMsh6tFc6oiQT0XEt1ovzTzB6vxA6qmmsdLPG9giJ9eNqJNHHQiIJosF3yBBoNFDiQDonRNdWNQz5JVxbsdIOhFrdD+mDU0ry9FIs6qMAvD84QVBOzJr/IOCdSy3bfWYyAUsLHqoJbytAzl5EgjVSU2UT+HLs7M2wfZoRGITztmvkcPjqd7PnSOuuAimonwP7uKHtvG+edRabyHaBDSemEA1LUs7+FGkCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAIh4QCe6Y3fJtDV6nBi/E3CGo/SIjDCmNnOV413QtmwODZSWFqo6pxs2fJoDb8jIkTf+l8/bI+mKEesXK1CptBpXXyo7Il0jhk5M0c1VT7EkLa/jkVFNr0CoB3UmH56/29Qp8+Xr8TaejGjgS8HoxAMpSFrtjPlKElCcy8dVQgRMxFonry5Iipd4vutc8Afe/GLzJew0IJ5Az1VUum3bJD0IfeecB8F+YOMmaET0oJIQyfdUxVI985Ui30q4K8/p34+WqwvNy2x4vuulvDVRBsHG64PStzhqZQfsfi59lOps4WvYlQ1JEHTu3acZMyTzij6wrVTAFoh1C3FptZ0wPoQ==";
let pemEncoded = `-----BEGIN RSA PUBLIC KEY-----\n${x5c}\n-----END RSA PUBLIC KEY-----\n`;
const payload = verify(token, pemEncoded, { "algorithms": ["RS256"] }));
But I don't think I've got correct PEM and I've been at it all day trying to find how to setup this certificate for verification. The error says "error:0D0680A8:asn1 encoding routines:asn1_check_tlen:wrong tag". The token is valid, but it doesn't like my certificate. Any idea what I've got wrong here?
What's the correct way to pass this certificate to the jsonwebtoken.verify method in this case? Thanks!
That is certificate, so:
let pemEncoded = `-----BEGIN CERTIFICATE-----\n${x5c}\n-----END CERTIFICATE-----\n`;

How to get publicKey in RSA_encrypt key-pair generation algorithm in STRING format in flutter

I am currently working on encryption in my flutter app wherein I am using RSA key-pair generator to get public and private key using the following code-
import 'package:rsa_encrypt/rsa_encrypt.dart';
import 'package:pointycastle/api.dart' as crypto;
//Future to hold our KeyPair
Future<crypto.AsymmetricKeyPair> futureKeyPair;
//to store the KeyPair once we get data from our future
crypto.AsymmetricKeyPair keyPair;
Future<crypto.AsymmetricKeyPair<crypto.PublicKey, crypto.PrivateKey>> getKeyPair()
{
var helper = RsaKeyHelper();
return helper.computeRSAKeyPair(helper.getSecureRandom());
}
Now I want to get the keyPair.publicKey in string format but if i print keyPair.publicKey, it shows "Instance of RSA publicKey" . How can I get it in string format??
It is always best to use standardized formats when saving public keys. For RSA public keys you can store them in layers, much like a Matroesjka doll.
Encode the public key in the ASN.1 / DER format specified in the PKCS#1 RSA standard;
Encode that public key in a format called SubjectPublicKeyInfo which is part of the X.509 specifications - it indicates that this is indeed an RSA key;
Apply so called PEM "ASCII armor", which consists of a header & footer line indicating the generic SubjectPublicKeyFormat (just PUBLIC KEY), with a multi-line base 64 encoding of the public key from step 2 in between.
Sounds like a lot of work, but if you look here you'll find handy methods called encodePublicKeyToPem and parsePublicKeyFromPem that do these 3 steps for you (it actually does both 1 and 2 in the same function, which is a bit of a shame but not that important).
These keys are rather portable and are also usable by e.g. OpenSSL or PGP.

CryptoAPI - how to extract RSA public key from private

Using windows CryptoAPI, is it possible to get public RSA key from a private key which was imported (not generated)?
If I use CryptGenKey, I can call CryptExportPublicKeyInfo and CryptImportPublicKeyInfo to obtain the public key handle. However, when I try to do the same thing with private key decoded from PEM and imported using:
CryptImportKey(hCSP, pKeyBuf, cbKeyBuf, 0, CRYPT_EXPORTABLE, &hPrivKey)
import of the private key succeeds and I have a valid handle but the subsequent call to CryptExportPublicKeyInfo fails with "Key does not exist" error. It looks like there's another call missing between CryptImportKey and CryptExportPublicKeyInfo, but I can not find that API call.
The problem with exporting/importing the public key was because private key was generated using AT_SIGNATURE, instead of AT_EXCHANGE. See the explanation and the example code

Decryption with the public key in iphone

I have a public key and an encrypted string. I could encrypt with the publickey successfully.But when i try to decrypt using the publickey it fails. I mean when i pass the publickey toseckeyDecrypt it fails.
I have Googled and found out that, by default kSecAttrCanDecrypt is false for public keys.So When i import the public key, i have added this particular line ,
[publicKeyAttr setObject:(id)kCFBooleanTrue forKey:(id)kSecAttrCanDecrypt];
But there is no improvement it still fails. Please somebody help.
EDIT:
Apple's Certificate,Key and Trust Services Says,
kSecAttrCanEncrypt Default false for private keys, true for public keys.
kSecAttrCanDecrypt Default true for private keys, false for public keys.
Which means, the values can be changed right?. My server does not sign(Convert as a digest) the content. They just encrypt using the private key which is to be decrypted at my(in iphone) end. Is that possible?.
The point of asymmetric cryptography is that you encrypt with the public key and decrypt with the private key.
EDIT: If you're signing and verifying, you should use the associated APIs. For example, you can check this capability with kSecAttrCanSign and kSecAttrCanVerify.