I create a keypair in serverside with openssl.
string serverPublicKey;
string serverPrivateKey;
using (var serverRsa = new OpenSSL.Crypto.RSA())
{
serverRsa.GenerateKeys(512, 65537, null, null);
serverPublicKey = serverRsa.PublicKeyAsPEM;
serverPrivateKey = serverRsa.PrivateKeyAsPEM;
}
On client side (Xamarin) I would like to import the public key with PCLCrypto, but I get always the error "Unexpected format or unsupported key", see code below.
var publicServerKey = _serverKeys.RsaKey;
var keyBuffer = Encoding.UTF8.GetBytes(publicServerKey);
var asym = WinRTCrypto.AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithm.RsaPkcs1);
var key = asym.ImportPublicKey(keyBuffer, CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey);
How can I Import teh public key, to encrypt data?
Related
I'm trying to encrypt a license file in PHP and decrypt it for verification in an application in C# Sharp but I'm stuck, tried different examples but they either don't work or require a 1MB library
Generating a key pair via:
$dn = array(
"countryName" => "UA",
"stateOrProvinceName" => "test",
"localityName" => "test1",
"organizationName" => "test2",
"organizationalUnitName" => "test3",
"commonName" => "test4",
"emailAddress" => "test5#gmail.com"
);
$privkey = openssl_pkey_new(array(
"private_key_bits" => 4096,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
));
// Create CSR
$csr = openssl_csr_new($dn, $privkey, array('digest_alg' => 'sha512'));
// Create a self-signed certificate with a lifetime of 365 days
$x509 = openssl_csr_sign($csr, null, $privkey, $days=365, array('digest_alg' => 'sha512'));
// Save in the file
$filePrivKey = 'private.key';
openssl_pkey_export_to_file($privkey, $filePrivKey);
// CSR - Export to file
$csrFile = 'cert.crt';
openssl_csr_export_to_file($csr, $csrFile);
//$x509csrFile crt
$x509csrFile = 'x509cert.crt';
openssl_x509_export_to_file($x509 ,$x509csrFile);
// Publick key
$pub_key = openssl_pkey_get_public(file_get_contents('x509cert.crt'));
$keyData = openssl_pkey_get_details($pub_key);
file_put_contents('key.pub', $keyData['key']);
I encrypt in PHP using a private key
// I’ll get the key to the file
$pathPriv = 'private.key';
$PrivKey = file_get_contents($pathPriv);
$LicenseKey = '05.05.2020 | example#gmail.com | Nikname';
openssl_private_encrypt($LicenseKey, $encrypted, $PrivKey);
$message = base64_encode($encrypted);
DecryptKey($message);
Trying to decrypt in C#.NET Framework
public MainWindow()
{
InitializeComponent();
string pubkey = System.IO.File.ReadAllText(#"publicKey.xml");
string message = "bPqM8JCgcGcBhWcJAxZyt6bqngL1POdQuehtWjsk3zE2m6YekpZdRu+c7B9lcLVLFqZ9K88uSC6o/7kUCBDDsxsZH8pvX7Yn11YSfUOgjfJJlThipibbmJl7KryQdYUxD8YEvUf0x2Q2ZlMaeMbKVk9IOSo87LKvSV5US7QmEz23ZiHiwQXNbI+txdwTHN8jyH2Byy7uHDz1BYwgpkmUk00BoXxO4kkz8P5Xgq5OHqisr2j/RvO2MkLHusOyAJYoXlyq/Fqn+EzFf4IPsdd/h5LQosd+Pyha9vR4RXJN+RT87KSXx0ZZuvQqUfYm3U6QzWzxBlPk1gOZ0nG2BWDcK9cJJWbKPn65K6c+U5109n7FRLQE7nnVPS9zU7D9sKm0+rOUGh0wDgClxfMsspESIpanuc/eMUZvIPZ98omNFny+r8Jf2aW4fcm4iydUMk3uRBIS7j1NVd4C5pR/vHTqSVcZDxiMRsLcAZ7PFwmjPik76eOmcxssiMS9CavOKe2h85uFhEfsaMCFim1lJ5rtznqc60l1iGa1/Pq3r0TdG0/RfIUOkZxr46HIwwXd6rfzGu2zwMMxl4Jfv6iWvpQk+DNmXv0Yw1w/Q9PF0i51mEen+z5nQSRJQsl8cmMBukOGTJ+X3ZELe848kni1luE20Icz/DSwv26QVVY6dZqiGV4=";
byte[] ciphertext = Convert.FromBase64String(message);
string decodedString = Encoding.UTF8.GetString(ciphertext);
}
public string decrypt(string elementToDesencrypt)
{
// string pem = System.IO.File.ReadAllText(pathPublicKey);
string pem = System.IO.File.ReadAllText(#"publicKey.xml");
byte[] Buffer = GetPublicKey();
System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
System.Security.Cryptography.RSAParameters rsaParam = rsa.ExportParameters(false);
rsaParam.Modulus = Buffer;
rsa.ImportParameters(rsaParam);
byte[] encryptedMessageByte = rsa.Decrypt(Convert.FromBase64String(elementToDesencrypt), false);
return Convert.ToBase64String(encryptedMessageByte);
}
I am getting an exception "The data size to be decrypted exceeds the maximum for this module, 512 bytes"
Is there a simple way to check if a given AsymmetricAlgorithm is a private or a public key? Consider the following example:
private void SavePrivateKey(AsymmetricAlgorithm asymmetricAlgorithm)
{
// if (asymmetricAlgorithm.IsPrivateKey == false)
// throw new ArgumentException();
}
private void SavePrivateKeys()
{
var certificate = CreateCertificate();
var privateKey = RSACertificateExtensions.GetRSAPrivateKey(certificate);
var publicKey = RSACertificateExtensions.GetRSAPublicKey(certificate);
SavePrivateKey(privateKey);
SavePrivateKey(publicKey); // this should throw an exception
}
private X509Certificate2 CreateCertificate()
{
CngKeyCreationParameters keyParams = new CngKeyCreationParameters();
keyParams.KeyUsage = CngKeyUsages.Signing;
keyParams.Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider;
keyParams.ExportPolicy = CngExportPolicies.AllowExport | CngExportPolicies.AllowPlaintextExport;
keyParams.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(2048), CngPropertyOptions.None));
var cngKey = CngKey.Create(CngAlgorithm.Rsa, Guid.NewGuid().ToString(), keyParams);
var rsaKey = new RSACng(cngKey);
var req = new CertificateRequest("cn=mycert", rsaKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pss);
var cert = req.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(5));
return cert;
}
Here, both private and public keys have the same type - RSACng. In theory I can try to export key parameters and see if the public key fails to export the private key params. But then I would not know if the export failed because it is a public key, or because it is missing export policies or something else went wrong. Also the underlying key type may be different, it could be RSACng, RSACryptoServiceProvider, DSA etc.
The ToXmlString() method takes in the includePrivateParameters parameter. If that parameter is set, and the AsymmetricAlgorithm object does not include information about the private key, ToXmlString() will throw a CryptographicException exception:
private void SavePrivateKey(AsymmetricAlgorithm aa)
{
System.Console.Write("This is ");
try
{
aa.ToXmlString(true);
}
catch(CryptographicException ce)
{
System.Console.Write("not ");
}
System.Console.WriteLine("a private key");
}
I'm writing a digital signing program using C# and I use RSACryptoServiceProvider class that generates public and private keys and signatures depending on the file. If in the program, I check the signature with the public key, signature and file, it works correctly but If I save my keys to any format in the file, In other words, I will change their format and return to the first state It doesn't work. because I can not turn it into RSAParameters correctly. please guide me?
Simple example test to show the change:
var publicParams = rsaWrite.ExportParameters(false); // Generate the public key.
var testpublicParams = publicParams;
string st = Encoding.ASCII.GetString(publicParams.Modulus);
testpublicParams.Modulus = Encoding.ASCII.GetBytes(st);
if(publicParams.Modulus != testpublicParams.Modulus) {
Console.WriteLine("The key has been changed.");
}
You can get PublicKey as string format and save it on the other text file.
public static string PublicKey(string certSubject)
{
var my = new X509Store(StoreName.My, StoreLocation.LocalMachine);
my.Open(OpenFlags.ReadOnly);
RSACryptoServiceProvider csp = null;
byte[] publicKeyByte = null;
foreach (var cert in my.Certificates)
{
if (cert.Subject.Contains(certSubject))
{
csp = (RSACryptoServiceProvider)cert.PublicKey.Key;
publicKeyByte = cert.PublicKey.EncodedKeyValue.RawData;
}
}
if (csp == null)
{
throw new Exception("No valid cert was found");
}
var publicKey = new StringBuilder();
publicKey.AppendLine("-----BEGIN PUBLIC KEY-----");
publicKey.AppendLine(Convert.ToBase64String(publicKeyByte, Base64FormattingOptions.InsertLineBreaks));
publicKey.AppendLine("-----END PUBLIC KEY-----");
return publicKey.ToString();
}
This code has two problems:
The use of Encoding.ASCII.GetBytes is wrong because it might have a non-ASCII characters so we use the Convert.ToBase64String.
publicParams.Modulus is C# byte array so != probably not the right answer so we use SequenceEqual.
And the key will not change.
var rsaWrite = new RSACryptoServiceProvider();
var publicParams = rsaWrite.ExportParameters(false); // Generate the public key.
var testpublicParams = publicParams;
string st = Convert.ToBase64String(publicParams.Modulus);
testpublicParams.Modulus = Convert.FromBase64String(st);
if (!publicParams.Modulus.SequenceEqual(testpublicParams.Modulus))
{
Console.WriteLine("The key has been changed.");
}
else
{
Console.WriteLine("The key has not been changed. :D");
}
I'm a newbie in jwt and after read a lot of web pages I've not found examples of how to generate a token (signed and encrypted) with keypairs generated from this website https://mkjwk.org/. I think it can't be very difficult. I think this is the way to generate the signed token (I don't know if it's correct):
RSACryptoServiceProvider rsaCrypto = new RSACryptoServiceProvider();
var payload = new Dictionary<string, object>()
{
{"jti", "ORIGEN_" + Guid.NewGuid().ToString()},
{"iat", DateTime.UtcNow},
{"exp", DateTime.UtcNow.AddYears(1)},
{"login", "USER" },
{"password", "PASSWORD" },
{"origen", "ORIGEN" }
};
// Contains both public and private keys to sign
var headers = new Dictionary<string, object>()
{
{ "kty", "RSA" },
{ "d", "A7Q8cttv_CSG4CJkX_xlU5lUoeRrCPZpyZx9eVaD7zi-tE7wDPKNmJPRP6uR_LA2YVXMmfY9w8q1_v_MiYxkYnFgZqNZlKdwucSQUlnfX5Tt806qh_323h5NnHrKweL-98_d8R4RuZXCWEQ3X0QDCVfccaLVVqLJy8S5zlx0aAVuBJxLxBHFRO700qdUN-RaMjHULoOnE1KbwmfKPfGlLL0YWPHQ9t-qIBh6OSZsDZh30K4VLF8sRXkGgn81_Byp4hK9tCfG98R6fWUM2_FCQrC9R1hO-KTsLffRzMboWe-2ymZGQfZKO-gtFaQH7_AjdVnQYMyKhSSCGYAAroSZAQ"},
{ "e", "AQAB" },
{ "use", "enc"},
{ "kid", "RPA" },
{ "alg", "RS256" },
{ "n", "qJPwMcHtb7xFGGczn20IiEtrPVehquyT6lxIJa_e4vcZE33uM6myVZWocTZWzTDmrNT3bJghEpLOhrgYatT3QnJIiTM9KAD01kYPc5cP5yo6Wmu0YjivqL3Rj7dUvi2pvl7juwYxt1_8zfdnBN5GpBIYcaY3ulVo_OSL7TOxJrua5IMhilQz6kqta3-Rgz3GSglOs94RHRvorYxMyHPQ6KhwSlh_zLzJQZ-0-AZ4yaMPdVwEaaEJpL-odYmRudX4E0t42dExLf_q1rpRfvTcdFSwfsJ7FmQcOtlc340WUgr4BHJfwrNIE4i-TFqrB4zSQJVKHlBfLeGKiYZQPD7igw" }
};
string tokenSigned = JWT.Encode(payload, rsaCrypto, JwsAlgorithm.RS256, headers);
I get a token (I think is signed) but if I put this token in this web site https://jwt.io/, I get an error "Invalid Signature".
Also I would like to encrypt this token with the public key. So I do this:
// Another public key to encrypt
headers = new Dictionary<string, object>()
{
{ "kty", "RSA" },
{ "e", "AQAB" },
{ "use", "enc"},
{ "alg", "RS256" },
{ "n", "ldMvqNDlz8-ABqEhqjtT0qvjKKbJMQ4J6GEi-7QrY-EUtyjCE7cOriHrYmbjt3o3zXwUTyOp0-twnF5j1HXFwVk7_XNsZz7LUmGNtmnqgB2iw2xhS7LAicN0RRgIbxWRDLOaaZ-49QumX6_r_jLNtIspKiFiuUNf2s0ipeAjWBFquiiqTMBd98z3pS-vC5y0CfzPbTSLSinikrHkIW2uO4FNHWZpoo8npn7vwWtAJjknWhaFi2s9P5kzUk4Mpbdx4DxUJ9ZvUi9SmdvH2vUzwGe0lxyvlw0DAMMWAT9TmsiKzBeXTY6rQ1-2Edn4F9S5kkPNOh1NqJoebz50-Bpl6w" }
};
string tokenEncrypted = JWT.Encode(payload, tokenSigned , JweAlgorithm.RSA_OAEP, JweEncryption.A256GCM, extraHeaders: headers);
But I always get the error "RsaKeyManagement alg expects key to be of RSACryptoServiceProvider type.". I've already search about this error but I don't have anything clear.
Please, anyone can help me? I'm not sure if I'm on the right way.
I use jose-jwt for .net because I've read that the library System.IdentityModel.Tokens.Jwt can't encrypt.
Thank you.
Regards.
In this case I had a jwk and I wanted to sign it with my private key and encrypt it with a customer public key with c# jose-jwt library. This jwk is the same all the time, so I only need to generate it once. To do that, you need to create an RSA object and then use the Encode method of the library to sign and encrypt.
A jwk has severals parameters:
JSON Web Key (JWK): A JSON object that represents a cryptographic key.
The members of the object represent properties of the key, including
its value.
These are some of the parameters:
p = 'RSA secret prime';
kty = 'Key Type';
q = 'RSA secret prime';
d = 'RSA secret exponent';
e = 'RSA public exponent';
kid = 'Key ID';
n = 'RSA public modulus';
use = 'Public Key Use';
alg = 'Algorithm'
But in my case I only had some of them: d, e, n, kty, use, kid, alg. The problem is that if you have e and d parameters, you also need p and q, because you can't construct private key with .NET without primes (P and Q).
The solution was to part the problem in two parts:
JAVA part: create a complete jwk with the Nimbus JOSE+JWT JAVA library:
C# parts:
Use the previous jwk to create an RSA object in C# with c# jose-jwt library. Like this:
var js = new JavaScriptSerializer();
// json is the result returned by java
var jwk = js.Deserialize<IDictionary<string, string>>(json);
byte[] p = Base64Url.Decode(jwk["p"]);
byte[] q = Base64Url.Decode(jwk["q"]);
byte[] d = Base64Url.Decode(jwk["d"]);
byte[] e = Base64Url.Decode(jwk["e"]);
byte[] qi = Base64Url.Decode(jwk["qi"]);
byte[] dq = Base64Url.Decode(jwk["dq"]);
byte[] dp = Base64Url.Decode(jwk["dp"]);
byte[] n = Base64Url.Decode(jwk["n"]);
RSA key = RSA.Create();
RSAParameters keyParams = new RSAParameters();
keyParams.P = p;
keyParams.Q = q;
keyParams.D = d;
keyParams.Exponent = e;
keyParams.InverseQ = qi;
keyParams.DP = dp;
keyParams.DQ = dq;
keyParams.Modulus = n;
key.ImportParameters(keyParams);
Once you have an RSA object, you can sign it:
var payload = new Dictionary<string, object>()
{
{"user", USER },
{"password", PASSWORD }
};
string tokenSigned = JWT.Encode(payload, key, JwsAlgorithm.RS256);
You can find the original solution in the library author web page.
Regards.
I'm trying to implement Firebase 3 Authentication mechanism using Custom Tokens (as described at https:// firebase.google.com/docs/auth/server/create-custom-tokens).
My server is ASP.NET MVC Application.
So according to the instructions (https://firebase.google.com/docs/server/setup) I've created a service account for my Firebase application and generated a key in '.p12' format.
After that according to instructions here (https://firebase.google.com/docs/auth/server/create-custom-tokens#create_custom_tokens_using_a_third-party_jwt_library) I tried to generate a custom token and sign it using the key received on the previous step. For token generation I used SystemIdentityModel.Tokens.Jwt library from Microsoft, so the code looks like the following:
var now = DateTime.UtcNow;
var tokenHandler = new JwtSecurityTokenHandler();
var key = new X509AsymmetricSecurityKey(new X509Certificate2(p12path, p12pwd));
var signinCredentials = new SigningCredentials(key, "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", "http://www.w3.org/2001/04/xmlenc#rsa-sha256");
Int32 nowInUnixTimestamp = (Int32)(now.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
var token = tokenHandler.CreateToken(
issuer: serviceAccountEmail,
audience: "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",
signingCredentials: signinCredentials,
subject: new ClaimsIdentity(new Claim[]
{
new Claim("sub", serviceAccountEmail),
new Claim("iat", nowInUnixTimestamp.ToString()),
new Claim("exp", (nowInUnixTimestamp + (60*60)).ToString()),
new Claim("uid", uid)
})
);
var tokenString = tokenHandler.WriteToken(token);
Then tried to sign in user in React Native application using Firebase Javascript SDK, with the following code:
//omitting initialization code
firebase.auth().signInWithCustomToken(firebaseJWT).catch(function(error) {
console.log('Error authenticating Firebase user. Code: ' + error.code + ' Message: ' + error.message);
});
But got an error from Firebase saying:
Error authenticating Firebase user. Code: auth/invalid-custom-token Message: The custom token format is incorrect. Please check the documentation.
Experimenting with adding different claims for token expiration control didn't help either.
Also I tried to generate tokens with "dvsekhvalnov/jose-jwt" library but can't get it working with "RS256" algorithm.
So the question:
Any suggestion on what am I doing wrong?
This pure .NET solution works for me, using the Org.BouncyCastle (https://www.nuget.org/packages/BouncyCastle/) and Jose.JWT (https://www.nuget.org/packages/jose-jwt/) libraries.
I followed these steps:
In the Firebase console click the 'cog' icon which is top left, next to the project name, and click 'Permissions'.
At the IAM and Admin page, click 'Service Accounts' on the left
Click 'Create Service Account' at the top, enter a 'Service Account Name', select 'Project->Editor' in the Role selection, tick the 'Furnish a new private key' checkbox and select JSON
Click 'Create' and download the Service Account JSON file and keep it safe.
Open the Service Account JSON file in a suitable text editor and put the values into the following code:
// private_key from the Service Account JSON file
public static string firebasePrivateKey=#"-----BEGIN PRIVATE KEY-----\nMIIE...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n...\n-----END PRIVATE KEY-----\n";
// Same for everyone
public static string firebasePayloadAUD="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit";
// client_email from the Service Account JSON file
public static string firebasePayloadISS="serviceaccountname#projectname.iam.gserviceaccount.com";
public static string firebasePayloadSUB="serviceaccountname#projectname.iam.gserviceaccount.com";
// the token 'exp' - max 3600 seconds - see https://firebase.google.com/docs/auth/server/create-custom-tokens
public static int firebaseTokenExpirySecs=3600;
private static RsaPrivateCrtKeyParameters _rsaParams;
private static object _rsaParamsLocker=new object();
void Main() {
// Example with custom claims
var uid="myuserid";
var claims=new Dictionary<string, object> {
{"premium_account", true}
};
Console.WriteLine(EncodeToken(uid, claims));
}
public static string EncodeToken(string uid, Dictionary<string, object> claims) {
// Get the RsaPrivateCrtKeyParameters if we haven't already determined them
if (_rsaParams == null) {
lock (_rsaParamsLocker) {
if (_rsaParams == null) {
StreamReader sr = new StreamReader(GenerateStreamFromString(firebasePrivateKey.Replace(#"\n","\n")));
var pr = new Org.BouncyCastle.OpenSsl.PemReader(sr);
_rsaParams = (RsaPrivateCrtKeyParameters)pr.ReadObject();
}
}
}
var payload = new Dictionary<string, object> {
{"claims", claims}
,{"uid", uid}
,{"iat", secondsSinceEpoch(DateTime.UtcNow)}
,{"exp", secondsSinceEpoch(DateTime.UtcNow.AddSeconds(firebaseTokenExpirySecs))}
,{"aud", firebasePayloadAUD}
,{"iss", firebasePayloadISS}
,{"sub", firebasePayloadSUB}
};
return Jose.JWT.Encode(payload, Org.BouncyCastle.Security.DotNetUtilities.ToRSA(_rsaParams), JwsAlgorithm.RS256);
}
private static long secondsSinceEpoch(DateTime dt) {
TimeSpan t = dt - new DateTime(1970, 1, 1);
return (long)t.TotalSeconds;
}
private static Stream GenerateStreamFromString(string s) {
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
To get this working in IIS I needed to change the application's pool identity and set the "load user profile" setting to true.
Haven't found a direct answer for the question so far, so for now ended up with the following solution:
Using instruction here generated a JSON file with service account details and created a basic Node.js server using Firebase server SDK that does generate correct custom tokens for Firebase with the following code:
var http = require('http');
var httpdispatcher = require('httpdispatcher');
var firebase = require('firebase');
var config = {
serviceAccount: {
projectId: "{projectId}",
clientEmail: "{projectServiceEmail}",
privateKey: "-----BEGIN PRIVATE KEY----- ... ---END PRIVATE KEY-----\n"
},
databaseURL: "https://{projectId}.firebaseio.com"
};
firebase.initializeApp(config);
const PORT=8080;
httpdispatcher.onGet("/firebaseCustomToken", function(req, res) {
var uid = req.params.uid;
if (uid) {
var customToken = firebase.auth().createCustomToken(uid);
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify({'firebaseJWT' : customToken}));
} else {
res.writeHead(400, {'Content-Type': 'text/plain'});
res.end('No uid parameter specified');
}
});
function handleRequest(request, response){
try {
//log the request on console
console.log(request.url);
//Disptach
httpdispatcher.dispatch(request, response);
} catch(err) {
console.log(err);
}
}
//create a server
var server = http.createServer(handleRequest);
//start our server
server.listen(PORT, function(){
console.log("Server listening on: http://localhost:%s", PORT);
});
Maybe someone will find this helpful.
#Elliveny's answer worked great for me. I am using it in a .NET Core 2.0 application and have built upon the accepted answer to turn this solution into a class that can be registered as a singleton dependency in the app services container, as well as have configuration passed in via constructor so that we can leverage .NET secrets for local development configuration and environment variables for production configuration.
I have also tidied up the stream handling a bit.
Note for .NET Core devs - you'll need to use Portable.BouncyCastle
You can test your encoded results by parsing the output JWT token with Jwt.IO
using Jose;
using Org.BouncyCastle.Crypto.Parameters;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
public class FirebaseTokenGenerator
{
// private_key from the Service Account JSON file
public static string firebasePrivateKey;
// Same for everyone
public static string firebasePayloadAUD = "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit";
// client_email from the Service Account JSON file
public static string firebasePayloadISS;
public static string firebasePayloadSUB;
// the token 'exp' - max 3600 seconds - see https://firebase.google.com/docs/auth/server/create-custom-tokens
public static int firebaseTokenExpirySecs = 3600;
private static RsaPrivateCrtKeyParameters _rsaParams;
private static object _rsaParamsLocker = new object();
public FirebaseTokenGenerator(string privateKey, string clientEmail)
{
firebasePrivateKey = privateKey ?? throw new ArgumentNullException(nameof(privateKey));
firebasePayloadISS = clientEmail ?? throw new ArgumentNullException(nameof(clientEmail));
firebasePayloadSUB = clientEmail;
}
public static string EncodeToken(string uid)
{
return EncodeToken(uid, null);
}
public static string EncodeToken(string uid, Dictionary<string, object> claims)
{
// Get the RsaPrivateCrtKeyParameters if we haven't already determined them
if (_rsaParams == null)
{
lock (_rsaParamsLocker)
{
if (_rsaParams == null)
{
using (var streamWriter = WriteToStreamWithString(firebasePrivateKey.Replace(#"\n", "\n")))
{
using (var sr = new StreamReader(streamWriter.BaseStream))
{
var pr = new Org.BouncyCastle.OpenSsl.PemReader(sr);
_rsaParams = (RsaPrivateCrtKeyParameters)pr.ReadObject();
}
}
}
}
}
var payload = new Dictionary<string, object> {
{"uid", uid}
,{"iat", SecondsSinceEpoch(DateTime.UtcNow)}
,{"exp", SecondsSinceEpoch(DateTime.UtcNow.AddSeconds(firebaseTokenExpirySecs))}
,{"aud", firebasePayloadAUD}
,{"iss", firebasePayloadISS}
,{"sub", firebasePayloadSUB}
};
if (claims != null && claims.Any())
{
payload.Add("claims", claims);
}
return JWT.Encode(payload, Org.BouncyCastle.Security.DotNetUtilities.ToRSA(_rsaParams), JwsAlgorithm.RS256);
}
private static long SecondsSinceEpoch(DateTime dt)
{
TimeSpan t = dt - new DateTime(1970, 1, 1);
return (long) t.TotalSeconds;
}
private static StreamWriter WriteToStreamWithString(string s)
{
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return writer;
}
}
The #Elliveny's code worked for me in locally but in azure throws an error : "The system cannot find the file specified". Due that I have changed a little bit the code and now works in both servers.
private string EncodeToken(string uid, Dictionary<string, object> claims)
{
string jwt = string.Empty;
RsaPrivateCrtKeyParameters _rsaParams;
using (StreamReader sr = new StreamReader(GenerateStreamFromString(private_key.Replace(#"\n", "\n"))))
{
var pr = new Org.BouncyCastle.OpenSsl.PemReader(sr);
_rsaParams = (RsaPrivateCrtKeyParameters)pr.ReadObject();
}
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
Dictionary<string, object> payload = new Dictionary<string, object> {
{"claims", claims}
,{"uid", uid}
,{"iat", secondsSinceEpoch(DateTime.UtcNow)}
,{"exp", secondsSinceEpoch(DateTime.UtcNow.AddSeconds(firebaseTokenExpirySecs))}
,{"aud", firebasePayloadAUD}
,{"iss", client_email}
,{"sub", client_email}
};
RSAParameters rsaParams = DotNetUtilities.ToRSAParameters(_rsaParams);
rsa.ImportParameters(rsaParams);
jwt = JWT.Encode(payload, rsa, Jose.JwsAlgorithm.RS256);
}
return jwt;
}