dvsekhvalnov / jose-jwt Goto Github PK
View Code? Open in Web Editor NEWUltimate Javascript Object Signing and Encryption (JOSE), JSON Web Token (JWT) and Json Web Keys (JWK) Implementation for .NET and .NET Core
License: MIT License
Ultimate Javascript Object Signing and Encryption (JOSE), JSON Web Token (JWT) and Json Web Keys (JWK) Implementation for .NET and .NET Core
License: MIT License
Calling to this method:
var payload = new Dictionary<string, object>()
{
{ "sub", "[email protected]" },
{ "exp", 1300819380 }
};
var privateKey = new X509Certificate2(@"C:\path\to\jwt-2048.p12", "1", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet).PrivateKey as RSACryptoServiceProvider;
string token = Jose.JWT.Encode(payload, privateKey, JwsAlgorithm.RS256);
Throwing this exception
**Unhandled Exception: System.Security.Cryptography.CryptographicException: Invalid algorithm specified.
at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
at System.Security.Cryptography.Utils.SignValue(SafeKeyHandle hKey, Int32 keyNumber, Int32 calgKey, Int32 calgHash, Byte[] hash, Int32 cbHash, ObjectHandleOnStack retSignature)
at System.Security.Cryptography.Utils.SignValue(SafeKeyHandle hKey, Int32 keyNumber, Int32 calgKey, Int32 calgHash, Byte[] hash)
at System.Security.Cryptography.RSACryptoServiceProvider.SignHash(Byte[] rgbHash, Int32 calgHash)
at System.Security.Cryptography.RSAPKCS1SignatureFormatter.CreateSignature(Byte[] rgbHash)
at Jose.RsaUsingSha.Sign(Byte[] securedInput, Object key)
at Jose.JWT.EncodeBytes(Byte[] payload, Object key, JwsAlgorithm algorithm, IDictionary2 extraHeaders) at Jose.JWT.Encode(String payload, Object key, JwsAlgorithm algorithm, IDictionary
2 extraHeaders)
at Jose.JWT.Encode(Object payload, Object key, JwsAlgorithm algorithm, IDictionary`2 extraHeaders)**
First of all, thank you so much for this robust JWT library! I was, probably like many others, a reluctant user of System.IdentityModel.Tokens.Jwt
in the past, but that library seems to be no longer maintained.
I work for a company that has a very strict OSS rules. We are not allowed to use NuGet packages that cannot be tied back to a specific GitHub release. We're currently using jose-jwt 2.0.2 from nuget.org. Do you think it's possible that you could create an official release on GitHub so that we can continue to use your great library? I noticed you have branches for a few different versions but, unfortunately, that won't satisfy our gatekeepers. :(
Hi,
I'm hoping to get a strong-named version of this file to integrate into an enterprise project.
There are a few options to get this, and I'd like to know what your preferred method is:
Thanks.
Hello,
I cannot used jose-jwt in my Asp.net 4.5.2 signed web application because it is requiring a signed assembly for jose-jwt.
If I remove signature on my web app it works.
Can you please sign your assembly for us to be able to use it?
Or maybe there is another way to do it?
Thank you.
Right now, ConcatKDF (SP800_56A_CONCAT) is not supported under netcore. And therefore ECDH key management family of algorithms unsupported as well.
Fix as netcore supports concatkdf or find other way to implement it directly in a library.
currently unable to work with large blocks of data. would be nice to have this as a stream reader/writer.
I was just pointed to this article here and wanted to know if there is something that needs to be done in JOSE-JWT?
See https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/
Hi,
Im not exactly sure if this is issue for jose-jwt library, but i dont know where else i can find answer.
I try to create token with:
string token = Jose.JWT.Encode(payload, key, JwsAlgorithm.ES256, headers);
It accepts key as CngKey object. But i only have *.p8 file in which is this content:
-----BEGIN PRIVATE KEY-----
MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgj6QsqUei+3Zz9sER
MrG/hQ511dfa3425vsdfvasdf+asqw33oZIzj0DAQehRANCAATHizygGyqvLkbv
3EkjCW1++MItok65sNjiUBKQQuN1SKi5Kn4NjbZ55zX5EfiELBq+PieeyDtUsPut
UGvS8FUT
-----END PRIVATE KEY-----
It is private key for signing tokens for Apple Push Notifications interface.
How can i construct CngKey object out of that file? I tried like this:
string privateKey = "MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgj6QsqUei+3Zz9sERMrG/hQ511dfa3425vsdfvasdf+asqw33oZIzj0DAQehRANCAATHizygGyqvLkbv3EkjCW1++MItok65sNjiUBKQQuN1SKi5Kn4NjbZ55zX5EfiELBq+PieeyDtUsPutUGvS8FUT"; if (CngKey.Exists(privateKey)) { key = CngKey.Open(privateKey); } else { key = CngKey.Create(CngAlgorithm.ECDsaP256, privateKey); }
This creates a key file in keystore, but thing does not work very well. I know this is not the right approach.
Can you please provide some help? It may be useful for future jose-jwt features, like creating signed tokens with ES256 with only private key in string format.
Summary: I cannot construct right CngKey object out of *.p8 file in which is private key.
Thanks
EDIT: I may have found a bug in my code, just a moment!
I'm trying to sign and then encrypt a token. I saw #15, but that method doesn't appear to be working. Any ideas?
If I only sign the token, no encryption, the token is valid.
Generating the token:
var signedToken = Jose.JWT.Encode(payload, Globals.JwtSigningKey, Jose.JwsAlgorithm.HS256);
var encryptedToken = Jose.JWT.Encode(signedToken, Globals.JwtEncryptionKey, Jose.JweAlgorithm.DIR, Jose.JweEncryption.A256GCM);
return encryptedToken;
Decoding the token:
var decryptedToken = Jose.JWT.Decode(token, Globals.JwtEncryptionKey, Jose.JweAlgorithm.DIR, Jose.JweEncryption.A256GCM);
var decodedJson = Jose.JWT.Decode(decryptedToken, Globals.JwtSigningKey);
return decodedJson;
The generated token looks like this:
eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0..BCS3zCOB6GoY92cF.6mgN34S6aGzOGzQ9ye_jL6ee3Ez8UrvdVnLzCY3N0EfDoZXzEBAUjZc6DfMsuES3K9J8FsU7NbrsIEAfi5Kh4YcvSZ0c28bly6PmbWtk5wzZhgX95n1ovMnuJsVfGyg7gKqw5ZOJ_MJIWKDEX1UrN93wWl95q4SDF98dTF4-g_a7SGzgqfLIVK3q7-Gkm6NCNhVmp46_t97DMMhleWHzqNoOB6_FeyJ6PrFlS_toHSgrq-1ysPh4l8OO9D4C--QrEu2PE4-m3Rt4-PvAtnZl-bPINgv073DArN3ZSB8EfEi-zBYcU7s8RXXs_6uawRS0z3c3L2z3I-kTBLH-_Lkawb7GyEFqNp8fx-hKvLXMx6M.3b2jBZKQYUQ1gde11b_DzA
Hello,
We use a vendor provided authentication solution where the JWT do not correctly implement the specifications. Namely the alg
and enc
headers are not set to the correct value.
Currently the mapping between the header values and the algorithm used is static and seems not modifiable by user of the library.
It seems there is some code for aiming in this direction in JWT.cs but it does not seem to be publicly accessible.
Would you be interested in a PR allowing to customize the mappings ?
I'm getting NotSupportedException with the message "Method is not supported." when running an application using the jose-jwt library on any computer other than my development computer. It works perfectly on the development computer. The entire build directory contents is being placed on the test computer, but is still generating the error.
Below is the code generating the error (some things have been changed like the payload contents since they contain sensitive information).
DateTimeOffset expiration = new DateTimeOffset(DateTime.Now);
var payload = new Dictionary<string, object>()
{
{ "sub", "[email protected]" },
{ "exp", expiration.ToUnixTimeSeconds() }
};
RSA pKey = new X509Certificate2(@"C:\directory\comb.pfx").GetRSAPrivateKey();
return Jose.JWT.Encode(payload, pKey, Jose.JwsAlgorithm.RS256);
I've been using this as I develop on my Windows machine and it's awesome! I'm publishing to an Ubuntu machine, however, and I'm getting an exception that bcrypt.dll could not be found. That's obviously something on Windows machines and not Ubuntu. Is there something I can do to fix this? I tried manually copying bcrypt.dll from my Windows machine, the same error occurs.
I'm specifically calling this code to encrypt my tokens. Signing works correctly, but encrypting does not.
// JwtSigningKey is a byte array
// JwtEncryptionKey is a byte array
var payload = new Jwt
{
// create JWT
};
var signedToken = JWT.Encode(payload, JwtSigningKey, JwsAlgorithm.HS256);
return JWT.Encode(signedToken, JwtEncryptionKey, JweAlgorithm.DIR, JweEncryption.A256GCM, JweCompression.DEF);
Can you release this with a strong name?
We've had issues in the past with the wrong versions of DLLs being deployed and we use strong names to ensure that the right versions of DLLs are deployed. That's not so much an issue with your DLL, but if your DLL is not strong named, it'll mean we have to turn off strong names in our assemblies.
Cheers,
Clay
In JOSE-JWT it is named JWT
and in JOSE-PCL it is named Jwt
.
Could you align to a single style. Jwt
is preferable
Dear,
How we must implement and use JWE (JSON Web Encryption) and encrypt JWT (JSON Wen Token) tokens?
Thanks.
It would be desirable to have a single jose-jwt codebase/package that works on all .NET Standard platforms. The idea being that if I make my own .NET Standard library that uses jose-jwt functionality, I can reference jose-jwt and it will "just work" on all .NET Standard platforms that my library itself targets.
For example, UWP support would be desirable. On installing the library into a brand new UWP project (just blank UWP app), I get the following error message:
Restoring packages for 'App8'.
Restoring packages for C:\Source\App8\App8\project.json...
System.Security.Cryptography.Csp 4.0.0 provides a compile-time reference assembly for System.Security.Cryptography.Csp on UAP,Version=v10.0, but there is no run-time assembly compatible with win10-arm.
One or more packages are incompatible with UAP,Version=v10.0 (win10-arm).
System.Security.Cryptography.Csp 4.0.0 provides a compile-time reference assembly for System.Security.Cryptography.Csp on UAP,Version=v10.0, but there is no run-time assembly compatible with win10-arm-aot.
System.Reflection.Emit.ILGeneration 4.0.1 provides a compile-time reference assembly for System.Reflection.Emit.ILGeneration on UAP,Version=v10.0, but there is no run-time assembly compatible with win10-arm-aot.
One or more packages are incompatible with UAP,Version=v10.0 (win10-arm-aot).
System.Security.Cryptography.Csp 4.0.0 provides a compile-time reference assembly for System.Security.Cryptography.Csp on UAP,Version=v10.0, but there is no run-time assembly compatible with win10-x64.
One or more packages are incompatible with UAP,Version=v10.0 (win10-x64).
System.Security.Cryptography.Csp 4.0.0 provides a compile-time reference assembly for System.Security.Cryptography.Csp on UAP,Version=v10.0, but there is no run-time assembly compatible with win10-x64-aot.
System.Reflection.Emit.ILGeneration 4.0.1 provides a compile-time reference assembly for System.Reflection.Emit.ILGeneration on UAP,Version=v10.0, but there is no run-time assembly compatible with win10-x64-aot.
One or more packages are incompatible with UAP,Version=v10.0 (win10-x64-aot).
System.Security.Cryptography.Csp 4.0.0 provides a compile-time reference assembly for System.Security.Cryptography.Csp on UAP,Version=v10.0, but there is no run-time assembly compatible with win10-x86.
One or more packages are incompatible with UAP,Version=v10.0 (win10-x86).
System.Security.Cryptography.Csp 4.0.0 provides a compile-time reference assembly for System.Security.Cryptography.Csp on UAP,Version=v10.0, but there is no run-time assembly compatible with win10-x86-aot.
System.Reflection.Emit.ILGeneration 4.0.1 provides a compile-time reference assembly for System.Reflection.Emit.ILGeneration on UAP,Version=v10.0, but there is no run-time assembly compatible with win10-x86-aot.
One or more packages are incompatible with UAP,Version=v10.0 (win10-x86-aot).
Package restore failed for 'App8'.
Package restore failed. Rolling back package changes for 'App8'.
========== Finished ==========
Time Elapsed: 00:00:01.9820806
Testing JOSW-JWT I was getting "Invalid algorithm specified" errors with certificates that were working fine using Microsoft's JwtSecurityTokenHandler.
Following the advice of http://hintdesk.com/c-how-to-fix-invalid-algorithm-specified-when-signing-with-sha256/ I regenerated the certificates using the -sp "Microsoft Enhanced RSA and AES Cryptographic Provider" -sy 24 options in makecert and then was able to generate the token with JOSE-JWT. And also to verify with JOSE-JWT the token generated with JwtSecurityTokenHandler and viceversa.
By I wonder why it is necessary to specify the enhanced provider for JOSE-JWT and not for JwtSecurityTokenHandler.
I have an .Net Core1.0 application and was trying to decode the JWT token using Jose.Decode() method. I am having a X509Certificate2 type certificate against which the token should be validated.
Most of the samples decodes the token using the below code:
`var publicKey = new X509Certificate2(@"certs\certificate_pub.crt", "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet).PublicKey.Key;
var decodedToken = JWT.Decode(token, publicKey);`
When I tried the same code it seems like there is no PublicKey.Key property, instead the PublicKey.EncodedKeyValue is available. What should I do to make the Decode working? How the certificate should be manipulated for getting the required key?
Any help would be appreciated.
Then I saw this MSDN:
NotSupportedException: This method call is not supported. This exception is thrown starting with the .NET Framework 4.6.
Remarks: In the .NET Framework 4.5.2 and earlier versions of the .NET Framework, this method was abstract. However, the only implementation by a derived class, RSACryptoServiceProvider.DecryptValue, also threw a NotSupportedException exception.
The assumption in the API currently seems to be that the payload is a JSON object (either serialized by jose-jwt or by the caller). This is more restrictive than the actual JOSE specifications, which allow any arbitrary data to be processed.
It would be desirable to use jose-jwt with arbitrary data (e.g. in the form of a byte[]
API).
First, my compliments on the library. It's extremely useful and saved me a ton of time.
When a JWE contains a nested JWT, per the spec https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32 the cty: header parameter is required and must be "JWT". There appears to be no way to adjust the JOSE header to include the content type parameter in this library.
A small nit to be sure but would be great to have an optional parameter or overload that supports this.
Thanks again for the great contribution.
It would be cleaner to list your dependencies explicitly - otherwise you are referencing way to many assemblies (that you don't need).
This references the whole netstandard lib:
https://github.com/dvsekhvalnov/jose-jwt/blob/master/jose-jwt/project.json#L69
We use JweAlgorithm.A256KW, JweEncryption.A256CBC_HS512 encryption.
On FIPS enabled environment this fails with:
Message=System.InvalidOperationException: This implementation is not part of the Windows Platform FIPS
validated cryptographic algorithms.
at System.Security.Cryptography.AesManaged..ctor()
at Jose.AesKeyWrap.AesEnc(Byte[] sharedKey, Byte[] plainText)
at Jose.AesKeyWrap.Wrap(Byte[] cek, Byte[] kek)
at Jose.AesKeyWrapManagement.WrapNewKey(Int32 cekSizeBits, Object key, IDictionary2 header) at Jose.JWT.Encode(String payload, Object key, JweAlgorithm alg, JweEncryption enc, Nullable
1
compression, IDictionary`2 extraHeaders)
Which encryption is FIPS compliant?
When adding 2.01 to a Xamarin project - I get
Could not install package 'System.Security.Cryptography.Cng 4.2.0'. You are trying to install this package into a project that targets 'Xamarin.iOS,Version=v1.0', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.
More of a question than an issue. I use the Issuer claim (iss) in the incoming jwt to pull a shared secret from a local DB for signature verification. I'd like to use Decode for this but it doesn't have a path that bypasses signature verification. So a couple of questions:
Thanks in advance.
Frank
Some examples mentioning cast to RSACng
, which is unsafe and not really expected.
Update examples to use valid casts to RSA
interface.
I would want to use your library in an application requiring JWT with RS256. The version on NuGet does not yet support this. Could you update your NuGet package?
The changes in #61 added some optional parameters (e.g. Payload, Decode), which breaks compatibility with existing calling code. Calls to these methods generate MissingMethodExceptions. If you're following semantic versioning, the major version should be incremented. I suspect the intent wasn't to break compatibility, though, so perhaps overloads should be added and the 2.3.0 package should be pulled.
Apologies if this is an idiotic question, and it may not even be an issue per se, but maybe someone else will learn from this as well.
I'm using core and trying to decode a JWT token utilizing a RS256 public key stored inside a certificate file. I've read the cert into a X509Certificate2
, but I'm not really sure how to convert that to requisite RSA
type for the Jose.JWT.Decode
method. In standard .NET, it appears that you can massage a X509Certificate2
into a RSACryptoServiceProvider
and utilize that for decoding, but I'm not really sure where to go from where I am.
Any insight?
Here's what I'm trying (paraphrased a bit)
var byte[] keyContents; //this is set somewhere else
var string token; //this is also set somewhere else
var cert = X509Certificate2(keyContents, "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);
var derp = Jose.JWT.Decode(token, cert.PublicKey); // this blows up because PublicKey is not a RSA
Sorry this a dumb question.
Can we use a file containing a public cert only to verify that the key is valid?
scenario:
services have only access to the public key, and auth server has access to the public/private key.
auth server signs and hands out jwt tokens, clients use them on services which services verify using the public cert.
I would assume that this a common problem. But your docs say
Encode
var payload = new Dictionary<string, object>()
{
{ "sub", "[email protected]" },
{ "exp", 1300819380 }
};
var privateKey=new X509Certificate2("my-key.p12", "password", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet).PrivateKey as RSACryptoServiceProvider;
string token=Jose.JWT.Encode(payload, privateKey, JwsAlgorithm.RS256);
Decode
var payload = new Dictionary<string, object>()
{
{ "sub", "[email protected]" },
{ "exp", 1300819380 }
};
var privateKey=new X509Certificate2("my-key.p12", "password", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet).PrivateKey as RSACryptoServiceProvider;
string token=Jose.JWT.Encode(payload, privateKey, JwsAlgorithm.RS256);
both of which I understand is using the private key? or is the doc not correct.
I'm just looking to confirm we can use the public cert to decode and verify.
I'd try myself but we aren't using .p12 files, so there is extra work involved in loading the .key /.cert files
Hi
Can you give an estimate on when AesEnc/Dec functionality (jose-jwt/crypto/AesKeyWrap.cs) is going to implemented for NetStandard 1.4?
/Christian
Close
Is there any plans to support JSON Web Keys (JWK) in the future?
Installing the package shouldn't add your LICENSE file to the target project. You can specify the package license via the licenseUrl and could set requireLicenseAcceptance to true to force a user to accept the license when installing.
Are there plans to support .NET Core. I know there are still in the beta phase, but for my project this would be a criteria, because we want to use .NET Core once all our dependencies are compatible with it.
So I think this might be more of a ASP.NET core question than jose-jwt - but I configured the asp.net core with UseJwtBearerAuthentication
as in the front page. This works fine if I send in a unencrypted, signed token but fails when I send in an encrypted token. I've tried
String encryptionKey = "hex string here";
byte[] key = encryptionKey.ToByteArray();
tokenValidationParams.TokenDecryptionKey = new SymmetricSecurityKey(key);
but this just ends in IDX10600: Decryption failed. There are no security keys for decryption.
Is there an example showing how to use encrypted tokens?
I noticed there's a few places where XXXManaged implementations are being used instead of CSP or CNG. Is there a particular reason for that? Would it be reasonable to switch those out to use CSP or CNG? I've got a fork where I've been testing these changes: master...SteveSyfuhs:feature/convert-to-provider
E.g.
https://github.com/dvsekhvalnov/jose-jwt/blob/a77bc9bec23964cceb58fe2b581250672ab9667b/JWT/jwe/AesCbcHmacEncryption.cs
https://github.com/dvsekhvalnov/jose-jwt/blob/a77bc9bec23964cceb58fe2b581250672ab9667b/JWT/crypto/AesKeyWrap.cs
https://github.com/dvsekhvalnov/jose-jwt/blob/a77bc9bec23964cceb58fe2b581250672ab9667b/JWT/jws/RsaUsingSha.cs
I am having difficulty loading an existing ecdsa (ES256) private key PEM file into a CNG key which is a requirement to call the encode method.
The directions state "the CngKey loaded via CngKey.Open(..) method from Key Storage Provider", but I haven't had any luck doing so. Since I don't have a key storage provider setup I was using the CngKey.Import() method instead, but that is returning an error "Invalid Parameter".
Code below:
byte[] b = Convert.FromBase64String(privateKey); CngKey cng = CngKey.Import(b, CngKeyBlobFormat.EccPrivateBlob); string token = Jose.JWT.Encode(payload, privateKey, JwsAlgorithm.ES256);
Can someone please point me in the right direction? Thanks!
The current version of your library only supports the standard .NET framework. Windows 8 or Windows Phone 8.1 apps cannot use System.Security.Cryptography but have to rely on Windows.Security.Cryptography. This API offers similar functionalities but works in a slightly different way.
I have created a quick modified version of your framework to rely on this new API (I removed or disabled most of the functionality I didn't needed).
Example of a modification I have done:
https://github.com/pieterderycke/FxSyncNet/blob/master/JWT.Universal/jws/RsaUsingSha.cs
Could you make support for Windows (Phone) 8.1 official?
A tip if you would want to add support:
One project for .NET 4.x with all the files added and you could work with conditional compilation symbols to implement specific functionalities in different ways depending on the framework (standard .NET vs. WinRT API's).
A second project (type Windows Runtime Component) with all the files added as linked items. Other conditional compilation symbols defined to allow the other code to be compiled. (See for an example: https://github.com/pieterderycke/Jace/blob/master/Jace/Util/MemoryCache.cs)
Your NuGet package could then add the correct DLL depending on the type of application the user is adding it to (.NET 4.x vs Windows (Phone) 8.1)
Hi,
in your code examples is (except in the first one) a variable named "payload" which is called "json" later...
var payload = new Dictionary<string, object>() // "payload"
{
{ "sub", "[email protected]" },
{ "exp", 1300819380 }
};
var secretKey = new byte[]{164,60,194,0,161,189,41,38,130,89,141,164,45,170,159,209,69,137,243,216,191,131,47,250,32,107,231,117,37,158,225,234};
string token=Jose.JWT.Encode(json, secretKey, JwsAlgorithm.HS256) // "json"
Is there any way to add additional header parameters besides "alg" and "enc?" I would like to have "kid" as well.
Inside private static byte[] DecodeBytes(string token, object key = null, JwsAlgorithm? jwsAlg = null, JweAlgorithm? jweAlg = null, JweEncryption? jweEnc = null)
There's the line:
string algorithm = (string) JWT.jsMapper.Parse<Dictionary<string, object>>(Encoding.UTF8.GetString(bytes1))["alg"];
(Looking at this through R# in VS, possible it's not char for char exact)
So I see you're looking for alg, which you expect to be a string. However you're not deserializing Dictionary<string,string>
. I assume this is for supporting the extraHeaders.
Using https://github.com/kevin-montrose/Jil deserializing Dictionary<string, object>
, the objects created are dynamic objects since you asked for an object and string. This dynamic object is not directly castable to string. It does return the expected value when you use .ToString()
My recommendation would be changing this line of code to be similar to
var o = JWT.jsMapper.Parse<Dictionary<string, object>>(Encoding.UTF8.GetString(bytes1))["alg"];
string algorithm = o as string ?? o.ToString();
.NET Framework 4.6 introduced X509Certificate2.GetRSAPrivateKey()
which returns an RSACng
and enables modern cryptographic algorithms to be used without the need to re-import keys. It would be desirable for jose-jwt to support this natively, as exportable keys are a security problem.
Not sure how to best integrate this, especially as it seems to be .NET 4.6+ only (or perhaps I am mistaken). Regardless, I am attaching a sample project that demonstrates the implementation by overriding the relevant IKeyManagement
and IJwsAlgorithm
implementations.
jose-jwt integrated project running on linux + nginx will have such a problem.
I do not know what to do;please help me ,please!
I would like to remove the alg and typ headers since they expose internal security details unnecessarily. Either the messages match my configured algorithm or they don't. This also has a side benefit of a reduction in message size, which every byte counts when it comes to headers sent with every single mobile request.
This is more a question than a real issue.
Wondering if (and how) I could generate a token which is signed with key 1 and crypted with key 2 (and of course with specific algorithms).
or change JweAlgorithms[JweAlgorithm.DIR] = "dir" to JweAlgorithms[JweAlgorithm.DIR] = "DIR"
I noticed an article claiming that many JOSE libraries are vulnerable to some sort of cryptographic attack: http://blog.intothesymmetry.com/2017/03/critical-vulnerability-in-json-web.html
Is jose-jwt also affected?
I'm having trouble following the C# examples provided to create and decode a token when using elliptical encryption. I've posted the test file I used up at https://gist.github.com/jehrenzweig/95a176f00236be526f2641e19c2582a7
-- encoding works fine, but when I try to decode the token the following exception is thrown:
An unhandled exception of type 'System.Security.Cryptography.CryptographicException' occurred in System.Core.dll
Additional information: Key does not exist.
I am using the jose-jwt library and want to create an encrypted JWT in C# using the RS256 algorithm for encryption. I have no experience with cryptography, so please excuse my ignorance. I see the following example in the docs:
var payload = new Dictionary<string, object>()
{
{ "sub", "[email protected]" },
{ "exp", 1300819380 }
};
var privateKey=new X509Certificate2("my-key.p12", "password", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet).PrivateKey as RSACryptoServiceProvider;
string token=Jose.JWT.Encode(payload, privateKey, JwsAlgorithm.RS256);
which shows the use of a p12
file, but how do I use an RSA key file of the form below? I am looking at the docs for X509Certificate2, but I see no option for RSA private keys.
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCqGKukO1De7zhZj6+H0qtjTkVxwTCpvKe4eCZ0FPqri0cb2JZfXJ/DgYSF6vUp
wmJG8wVQZKjeGcjDOL5UlsuusFncCzWBQ7RKNUSesmQRMSGkVb1/3j+skZ6UtW+5u09lHNsj6tQ5
1s1SPrCBkedbNf0Tp0GbMJDyR4e9T04ZZwIDAQABAoGAFijko56+qGyN8M0RVyaRAXz++xTqHBLh
3tx4VgMtrQ+WEgCjhoTwo23KMBAuJGSYnRmoBZM3lMfTKevIkAidPExvYCdm5dYq3XToLkkLv5L2
pIIVOFMDG+KESnAFV7l2c+cnzRMW0+b6f8mR1CJzZuxVLL6Q02fvLi55/mbSYxECQQDeAw6fiIQX
GukBI4eMZZt4nscy2o12KyYner3VpoeE+Np2q+Z3pvAMd/aNzQ/W9WaI+NRfcxUJrmfPwIGm63il
AkEAxCL5HQb2bQr4ByorcMWm/hEP2MZzROV73yF41hPsRC9m66KrheO9HPTJuo3/9s5p+sqGxOlF
L0NDt4SkosjgGwJAFklyR1uZ/wPJjj611cdBcztlPdqoxssQGnh85BzCj/u3WqBpE2vjvyyvyI5k
X6zk7S0ljKtt2jny2+00VsBerQJBAJGC1Mg5Oydo5NwD6BiROrPxGo2bpTbu/fhrT8ebHkTz2epl
U9VQQSQzY1oZMVX8i1m5WUTLPz2yLJIBQVdXqhMCQBGoiuSoSjafUhV7i1cEGpb88h5NBYZzWXGZ
37sJ5QsW+sJyoNde3xH8vdXhzU7eT82D6X/scw9RZz+/6rCJ4p0=
-----END RSA PRIVATE KEY-----
Finally, what is the difference between the two options listed in the docs, and how do I choose between the two?
-------------------------- OPTION 1 --------------------------
RS-* and PS-* family
CLR:
RS256, RS384, RS512 and PS256, PS384, PS512 signatures require
RSACryptoServiceProvider (usually private) key of corresponding
length. CSP need to be forced to use Microsoft Enhanced RSA and AES
Cryptographic Provider. Which usually can be done be re-importing
RSAParameters. See http://clrsecurity.codeplex.com/discussions/243156
for details.-------------------------- OPTION 2 --------------------------
CORECLR: RS256, RS384, RS512 signatures require RSA (usually private) key of corresponding length.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.