public void Equal(EllipticalCurve crv) { var key = ECJwk.GeneratePrivateKey(crv); Assert.True(key.Equals(key)); Assert.Equal(key, key); var publicKey = key.AsPublicKey(); Assert.NotEqual(key, publicKey); var copiedKey = ECJwk.FromJson(key.ToString()); Assert.Equal(key, copiedKey); // 'kid' is not a discriminant, excepted if the value is different. copiedKey.Kid = default; Assert.Equal(key, copiedKey); Assert.Equal(copiedKey, key); key.Kid = default; Assert.Equal(key, copiedKey); key.Kid = JsonEncodedText.Encode("X"); copiedKey.Kid = JsonEncodedText.Encode("Y"); Assert.NotEqual(key, copiedKey); Assert.NotEqual(key, Jwk.None); }
private static JwsDescriptorWrapper CreateDescriptor(SignatureAlgorithm algorithm) { var jwk = algorithm.Category switch { Cryptography.AlgorithmCategory.None => Jwk.None, Cryptography.AlgorithmCategory.EllipticCurve => ECJwk.GeneratePrivateKey(algorithm), Cryptography.AlgorithmCategory.Rsa => RsaJwk.GeneratePrivateKey(4096, algorithm), Cryptography.AlgorithmCategory.Aes => SymmetricJwk.GenerateKey(algorithm), Cryptography.AlgorithmCategory.AesGcm => SymmetricJwk.GenerateKey(algorithm), Cryptography.AlgorithmCategory.Hmac => SymmetricJwk.GenerateKey(algorithm), _ => throw new InvalidOperationException() }; var descriptor = new JwsDescriptor(jwk, algorithm) { Payload = new JwtPayload { { JwtClaimNames.Iat, EpochTime.UtcNow }, { JwtClaimNames.Exp, EpochTime.UtcNow + EpochTime.OneHour }, { JwtClaimNames.Iss, "https://idp.example.com/" }, { JwtClaimNames.Aud, "636C69656E745F6964" } } }; return(new JwsDescriptorWrapper(descriptor)); } }
public override void WriteTo() { var key = ECJwk.GeneratePrivateKey(SignatureAlgorithm.ES256); key.Kid = JsonEncodedText.Encode("kid-ec"); key.KeyOps.Add(JwkKeyOpsValues.Sign); key.Use = JwkUseValues.Sig; key.X5t = Base64Url.Decode("dGhpcyBpcyBhIFNIQTEgdGVzdCE"); key.X5tS256 = Base64Url.Decode("dGhpcyBpcyBhIFNIQTI1NiB0ZXN0ISAgICAgICAgICAgIA"); key.X5u = "https://example.com"; key.X5c.Add(Convert.FromBase64String("MIIDQjCCAiqgAwIBAgIGATz/FuLiMA0GCSqGSIb3DQEBBQUAMGIxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDTzEPMA0GA1UEBxMGRGVudmVyMRwwGgYDVQQKExNQaW5nIElkZW50aXR5IENvcnAuMRcwFQYDVQQDEw5CcmlhbiBDYW1wYmVsbDAeFw0xMzAyMjEyMzI5MTVaFw0xODA4MTQyMjI5MTVaMGIxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDTzEPMA0GA1UEBxMGRGVudmVyMRwwGgYDVQQKExNQaW5nIElkZW50aXR5IENvcnAuMRcwFQYDVQQDEw5CcmlhbiBDYW1wYmVsbDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL64zn8/QnHYMeZ0LncoXaEde1fiLm1jHjmQsF/449IYALM9if6amFtPDy2yvz3YlRij66s5gyLCyO7ANuVRJx1NbgizcAblIgjtdf/u3WG7K+IiZhtELto/A7Fck9Ws6SQvzRvOE8uSirYbgmj6He4iO8NCyvaK0jIQRMMGQwsU1quGmFgHIXPLfnpnfajr1rVTAwtgV5LEZ4Iel+W1GC8ugMhyr4/p1MtcIM42EA8BzE6ZQqC7VPqPvEjZ2dbZkaBhPbiZAS3YeYBRDWm1p1OZtWamT3cEvqqPpnjL1XyW+oyVVkaZdklLQp2Btgt9qr21m42f4wTw+Xrp6rCKNb0CAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAh8zGlfSlcI0o3rYDPBB07aXNswb4ECNIKG0CETTUxmXl9KUL+9gGlqCz5iWLOgWsnrcKcY0vXPG9J1r9AqBNTqNgHq2G03X09266X5CpOe1zFo+Owb1zxtp3PehFdfQJ610CDLEaS9V9Rqp17hCyybEpOGVwe8fnk+fbEL2Bo3UPGrpsHzUoaGpDftmWssZkhpBJKVMJyf/RuP2SmmaIzmnw9JiSlYhzo4tpzd5rFXhjRbg4zW9C+2qok+2+qDM1iJ684gPHMIY8aLWrdgQTxkumGmTqgawR+N5MDtdPTEQ0XfIBc2cJEUyMTY5MPvACWpkA6SdS4xSvdXK3IVfOWA==")); using var bufferWriter = new PooledByteBufferWriter(); key.Serialize(bufferWriter); var json = Encoding.UTF8.GetString(bufferWriter.WrittenSpan.ToArray()); Assert.Contains("\"kid\":\"kid-ec\"", json); Assert.Contains("\"key_ops\":[\"sign\"]", json); Assert.Contains("\"use\":\"sig\"", json); Assert.Contains("\"x5t\":\"dGhpcyBpcyBhIFNIQTEgdGVzdCE\"", json); Assert.Contains("\"x5t#S256\":\"dGhpcyBpcyBhIFNIQTI1NiB0ZXN0ISAgICAgICAgICAgIA\"", json); #if NETSTANDARD2_0 Assert.Contains("\"x5u\":\"" + JsonEncodedText.Encode("https://example.com") + "\"", json); Assert.Contains("\"x5c\":[\"MIIDQjCCAiqgAwIBAgIGATz/FuLiMA0GCSqGSIb3DQEBBQUAMGIxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDTzEPMA0GA1UEBxMGRGVudmVyMRwwGgYDVQQKExNQaW5nIElkZW50aXR5IENvcnAuMRcwFQYDVQQDEw5CcmlhbiBDYW1wYmVsbDAeFw0xMzAyMjEyMzI5MTVaFw0xODA4MTQyMjI5MTVaMGIxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDTzEPMA0GA1UEBxMGRGVudmVyMRwwGgYDVQQKExNQaW5nIElkZW50aXR5IENvcnAuMRcwFQYDVQQDEw5CcmlhbiBDYW1wYmVsbDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL64zn8/QnHYMeZ0LncoXaEde1fiLm1jHjmQsF/449IYALM9if6amFtPDy2yvz3YlRij66s5gyLCyO7ANuVRJx1NbgizcAblIgjtdf/u3WG7K\u002bIiZhtELto/A7Fck9Ws6SQvzRvOE8uSirYbgmj6He4iO8NCyvaK0jIQRMMGQwsU1quGmFgHIXPLfnpnfajr1rVTAwtgV5LEZ4Iel\u002bW1GC8ugMhyr4/p1MtcIM42EA8BzE6ZQqC7VPqPvEjZ2dbZkaBhPbiZAS3YeYBRDWm1p1OZtWamT3cEvqqPpnjL1XyW\u002boyVVkaZdklLQp2Btgt9qr21m42f4wTw\u002bXrp6rCKNb0CAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAh8zGlfSlcI0o3rYDPBB07aXNswb4ECNIKG0CETTUxmXl9KUL\u002b9gGlqCz5iWLOgWsnrcKcY0vXPG9J1r9AqBNTqNgHq2G03X09266X5CpOe1zFo\u002bOwb1zxtp3PehFdfQJ610CDLEaS9V9Rqp17hCyybEpOGVwe8fnk\u002bfbEL2Bo3UPGrpsHzUoaGpDftmWssZkhpBJKVMJyf/RuP2SmmaIzmnw9JiSlYhzo4tpzd5rFXhjRbg4zW9C\u002b2qok\u002b2\u002bqDM1iJ684gPHMIY8aLWrdgQTxkumGmTqgawR\u002bN5MDtdPTEQ0XfIBc2cJEUyMTY5MPvACWpkA6SdS4xSvdXK3IVfOWA==\"]", json); #else Assert.Contains("\"x5u\":\"" + JsonEncodedText.Encode("https://example.com", JsonSerializationBehavior.JsonEncoder) + "\"", json); Assert.Contains("\"x5c\":[\"" + JsonEncodedText.Encode("MIIDQjCCAiqgAwIBAgIGATz/FuLiMA0GCSqGSIb3DQEBBQUAMGIxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDTzEPMA0GA1UEBxMGRGVudmVyMRwwGgYDVQQKExNQaW5nIElkZW50aXR5IENvcnAuMRcwFQYDVQQDEw5CcmlhbiBDYW1wYmVsbDAeFw0xMzAyMjEyMzI5MTVaFw0xODA4MTQyMjI5MTVaMGIxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDTzEPMA0GA1UEBxMGRGVudmVyMRwwGgYDVQQKExNQaW5nIElkZW50aXR5IENvcnAuMRcwFQYDVQQDEw5CcmlhbiBDYW1wYmVsbDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL64zn8/QnHYMeZ0LncoXaEde1fiLm1jHjmQsF/449IYALM9if6amFtPDy2yvz3YlRij66s5gyLCyO7ANuVRJx1NbgizcAblIgjtdf/u3WG7K+IiZhtELto/A7Fck9Ws6SQvzRvOE8uSirYbgmj6He4iO8NCyvaK0jIQRMMGQwsU1quGmFgHIXPLfnpnfajr1rVTAwtgV5LEZ4Iel+W1GC8ugMhyr4/p1MtcIM42EA8BzE6ZQqC7VPqPvEjZ2dbZkaBhPbiZAS3YeYBRDWm1p1OZtWamT3cEvqqPpnjL1XyW+oyVVkaZdklLQp2Btgt9qr21m42f4wTw+Xrp6rCKNb0CAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAh8zGlfSlcI0o3rYDPBB07aXNswb4ECNIKG0CETTUxmXl9KUL+9gGlqCz5iWLOgWsnrcKcY0vXPG9J1r9AqBNTqNgHq2G03X09266X5CpOe1zFo+Owb1zxtp3PehFdfQJ610CDLEaS9V9Rqp17hCyybEpOGVwe8fnk+fbEL2Bo3UPGrpsHzUoaGpDftmWssZkhpBJKVMJyf/RuP2SmmaIzmnw9JiSlYhzo4tpzd5rFXhjRbg4zW9C+2qok+2+qDM1iJ684gPHMIY8aLWrdgQTxkumGmTqgawR+N5MDtdPTEQ0XfIBc2cJEUyMTY5MPvACWpkA6SdS4xSvdXK3IVfOWA==", JsonSerializationBehavior.JsonEncoder) + "\"]", json); #endif Assert.Contains("\"crv\":\"P-256\"", json); Assert.Contains("\"x\":\"" + Encoding.UTF8.GetString(Base64Url.Encode(key.X)) + "\"", json); Assert.Contains("\"y\":\"" + Encoding.UTF8.GetString(Base64Url.Encode(key.Y)) + "\"", json); Assert.Contains("\"d\":\"" + Encoding.UTF8.GetString(Base64Url.Encode(key.D)) + "\"", json); }
private static void GenerateKeys() { // The GenerateKey method creates a new crypto-random asymmetric key for elliptic curve algorithms var ecKey = ECJwk.GenerateKey(EllipticalCurve.P521, withPrivateKey: true, SignatureAlgorithm.EcdsaSha512); ecKey.Kid = "Generated-ES512"; Console.WriteLine("Asymmetric generated JWK for elliptic curve P-521, for ES512 signature algorithm:"); Console.WriteLine(ecKey); Console.WriteLine(); // The GenerateKey method creates a new crypto-random asymmetric key for RSA algorithms var rsaKey = RsaJwk.GenerateKey(2048, withPrivateKey: true, SignatureAlgorithm.RsaSsaPssSha384); rsaKey.Kid = "Generated-PS384"; Console.WriteLine("Asymmetric generated JWK of 2048 bits for RSA, for PS384 signature algorithm:"); Console.WriteLine(rsaKey); Console.WriteLine(); // The GenerateKey method creates a new crypto-random symmetric key for symmetric algorithms var symmetricKey = SymmetricJwk.GenerateKey(128, SignatureAlgorithm.HmacSha256); symmetricKey.Kid = "Generated-HS256"; Console.WriteLine("Symmetric generated JWK of 128 bits, for HS256 signature algorithm:"); Console.WriteLine(symmetricKey); Console.WriteLine(); // The GenerateKey method creates a new crypto-random aymmetric key for RSA algorithms var symmetricKey2 = SymmetricJwk.GenerateKey(256); Console.WriteLine("Symmetric generated JWK of 256 bits, without specified signature algorithm, without key identifier:"); Console.WriteLine(symmetricKey2); Console.WriteLine(); }
private static void GenerateKeys() { // The GenerateKey method creates a new crypto-random asymmetric key for elliptic curve algorithms var ecKey = ECJwk.GeneratePrivateKey(SignatureAlgorithm.ES512); Console.WriteLine("Asymmetric generated JWK for elliptic curve P-521, for ES512 signature algorithm:"); Console.WriteLine(ecKey); Console.WriteLine(); // The GenerateKey method creates a new crypto-random asymmetric key for RSA algorithms // You may specify a bigger key size. The default is the minimum size (2048 bits for RSA) var rsaKey = RsaJwk.GeneratePrivateKey(SignatureAlgorithm.PS384); Console.WriteLine("Asymmetric generated JWK of 2048 bits for RSA, for PS384 signature algorithm:"); Console.WriteLine(rsaKey); Console.WriteLine(); // The GenerateKey method creates a new crypto-random symmetric key for symmetric algorithms var symmetricKey = SymmetricJwk.GenerateKey(SignatureAlgorithm.HS256); Console.WriteLine("Symmetric generated JWK of 128 bits, for HS256 signature algorithm:"); Console.WriteLine(symmetricKey); Console.WriteLine(); // The GenerateKey method creates a new crypto-random aymmetric key for RSA algorithms var symmetricKey2 = SymmetricJwk.GenerateKey(256, computeThumbprint: false); Console.WriteLine("Symmetric generated JWK of 256 bits, without specified signature algorithm, without key identifier (the thumbprint):"); Console.WriteLine(symmetricKey2); Console.WriteLine(); }
public void TryWrapKey_WithStaticKey_Success(EncryptionAlgorithm enc, KeyManagementAlgorithm alg) { var contentEncryptionKey = ECJwk.GeneratePrivateKey(EllipticalCurve.P256); Jwk cek = TryWrapKey_Success(contentEncryptionKey, enc, alg); Assert.NotNull(cek); Assert.IsType <SymmetricJwk>(cek); }
public void FromPem_PublicKey(string pem) { var key = ECJwk.FromPem(pem); ECParameters ecParameters = key.ExportParameters(true); ECParameters expected = GetNistP256ReferenceKey(false); AssertEqual(expected, ecParameters); Assert.False(key.HasPrivateKey); }
public void GenerateKey(EllipticalCurve crv) { var key = ECJwk.GeneratePrivateKey(crv); Assert.NotNull(key); var key2 = ECJwk.GeneratePrivateKey(crv.SupportedSignatureAlgorithm); Assert.NotNull(key2); }
public void FromPem_UnexpectedKeyType_ThrowArgumentException() { string pem = @" -----BEGIN RSA PUBLIC KEY----- MEgCQQC3P1n17ovVXiS3/wKa0WqFQ8ltJT5UMZuTUyxBw8FHe4nbLS8z17modFhI 4GqOaDtQRFEeG8o2JSfhfPQrOAYVAgMBAAE= -----END RSA PUBLIC KEY-----"; Assert.Throws <InvalidOperationException>(() => ECJwk.FromPem(pem)); }
public override void Canonicalize() { var jwk = ECJwk.GenerateKey(EllipticalCurve.P256, true); var canonicalizedKey = (ECJwk)CanonicalizeKey(jwk); Assert.Null(canonicalizedKey.D); Assert.Equal(EllipticalCurve.P256.Id, canonicalizedKey.Crv.Id); Assert.NotEmpty(canonicalizedKey.X); Assert.NotEmpty(canonicalizedKey.Y); }
private Jwk TryWrapKey_Success(ECJwk keyToWrap, EncryptionAlgorithm enc, KeyManagementAlgorithm alg) { var keyEncryptionKey = ECJwk.GeneratePrivateKey(EllipticalCurve.P256); var wrapper = new EcdhKeyWrapper(keyEncryptionKey, enc, alg); var cek = WrapKey(wrapper, keyToWrap, out var header); Assert.Equal(1, header.Count); Assert.True(header.ContainsKey("epk")); return(cek); }
public override void Canonicalize() { var jwk = ECJwk.GeneratePrivateKey(SignatureAlgorithm.ES256); var canonicalizedKey = (ECJwk)CanonicalizeKey(jwk); Assert.True(canonicalizedKey.D.IsEmpty); Assert.Equal(EllipticalCurve.P256.Id, canonicalizedKey.Crv.Id); Assert.False(canonicalizedKey.X.IsEmpty); Assert.False(canonicalizedKey.Y.IsEmpty); }
public EcdsaSignatureVerifier(ECJwk key, SignatureAlgorithm algorithm) : base(algorithm) { Debug.Assert(key != null); Debug.Assert(key.KeySizeInBits == algorithm.RequiredKeySizeInBits); _sha = algorithm.Sha; _hashSize = key.Crv.HashSize; _base64HashSize = Base64Url.GetArraySizeRequiredToEncode(_hashSize); _ecdsaPool = new ObjectPool <ECDsa>(new ECDsaObjectPoolPolicy(key, algorithm)); }
// SEQUENCE // SEQUENCE // OBJECT IDENTIFIER 1.2.840.10045.2.1 // OBJECT IDENTIFIER EC curve OID // BIT STRING public key private static ECJwk ReadECPublicKey(ref AsnReader reader, int[] curveOid) { var publicKey = reader.ReadBitStringBytes(); if (publicKey.IsEmpty) { ThrowHelper.ThrowInvalidOperationException_InvalidPem(); } if (publicKey[0] != 0x04) { ThrowHelper.ThrowInvalidOperationException_InvalidPem(); } if ((publicKey.Length & 0x01) != 1) { ThrowHelper.ThrowInvalidOperationException_InvalidPem(); } int fieldWidth = publicKey.Length / 2; var x = publicKey.Slice(1, fieldWidth).ToArray(); var y = publicKey.Slice(1 + fieldWidth).ToArray(); if (reader.Read()) { ThrowHelper.ThrowInvalidOperationException_InvalidPem(); } if (IsP256(curveOid)) { return(ECJwk.FromByteArray(EllipticalCurve.P256, x: x, y: y)); } else if (IsP384(curveOid)) { return(ECJwk.FromByteArray(EllipticalCurve.P384, x: x, y: y)); } else if (IsP521(curveOid)) { return(ECJwk.FromByteArray(EllipticalCurve.P521, x: x, y: y)); } else { throw new NotSupportedException(); } }
public void WrapKey_Failure() { var keyEncryptionKey = ECJwk.GenerateKey(EllipticalCurve.P256, true); var wrapper = new EcdhKeyWrapper(keyEncryptionKey, EncryptionAlgorithm.Aes256CbcHmacSha512, KeyManagementAlgorithm.EcdhEs); var destination = new byte[0]; var header = new JwtObject(); Jwk cek = null; Assert.Throws <ArgumentNullException>(() => wrapper.WrapKey(null, null, destination)); wrapper.Dispose(); Assert.Throws <ObjectDisposedException>(() => wrapper.WrapKey(null, header, destination)); Assert.Equal(0, header.Count); Assert.Null(cek); }
public void Setup() { var key = SymmetricJwk.GenerateKey(256); var rsaKey = RsaJwk.GeneratePrivateKey(2048); var ecKey = ECJwk.GeneratePrivateKey(EllipticalCurve.P256); for (int i = 0; i < Count; i++) { key.TryGetSigner(SignatureAlgorithm.HS256, out var signer); id = i; _dictionary.Add(id, signer); _concurrentDictionary.TryAdd(id, signer); _cryptoStore.TryAdd(id, signer); _cryptoStore2.TryAdd(id, signer); } }
public EcdhKeyWrapper(ECJwk key, EncryptionAlgorithm encryptionAlgorithm, KeyManagementAlgorithm contentEncryptionAlgorithm) : base(key, encryptionAlgorithm, contentEncryptionAlgorithm) { if (contentEncryptionAlgorithm.WrappedAlgorithm is null) { _algorithmName = encryptionAlgorithm.Utf8Name; _keySizeInBytes = encryptionAlgorithm.RequiredKeySizeInBytes; } else { _algorithmName = contentEncryptionAlgorithm.Utf8Name; _keySizeInBytes = contentEncryptionAlgorithm.WrappedAlgorithm.RequiredKeySizeInBits >> 3; } _algorithmNameLength = _algorithmName.Length; _hashAlgorithm = GetHashAlgorithm(encryptionAlgorithm); }
public EcdsaSigner(ECJwk key, SignatureAlgorithm algorithm) : base(algorithm) { if (key is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if (key.KeySizeInBits < 256) { ThrowHelper.ThrowArgumentOutOfRangeException_SigningKeyTooSmall(key, 256); } _canOnlyVerify = !key.HasPrivateKey; _hashAlgorithm = algorithm.HashAlgorithm; _hashSize = key.Crv.HashSize; _base64HashSize = Base64Url.GetArraySizeRequiredToEncode(_hashSize); _ecdsaPool = new ObjectPool <ECDsa>(new ECDsaObjectPoolPolicy(key, algorithm)); }
/// <inheritsdoc /> public override SymmetricJwk WrapKey(Jwk?staticKey, JwtHeader header, Span <byte> destination) { Debug.Assert(header != null); var partyUInfo = GetPartyInfo(header, JwtHeaderParameterNames.Apu); var partyVInfo = GetPartyInfo(header, JwtHeaderParameterNames.Apv); var secretAppend = BuildSecretAppend(partyUInfo, partyVInfo); ReadOnlySpan <byte> exchangeHash; var ecKey = _key; var otherPartyKey = ecKey.CreateEcdhKey(); ECDiffieHellman ephemeralKey = (staticKey is null) ? ECDiffieHellman.Create(ecKey.Crv.CurveParameters) : ((ECJwk)staticKey).CreateEcdhKey(); try { exchangeHash = new ReadOnlySpan <byte>(ephemeralKey.DeriveKeyFromHash(otherPartyKey.PublicKey, _hashAlgorithm, _secretPreprend, secretAppend), 0, _keySizeInBytes); var epk = ECJwk.FromParameters(ephemeralKey.ExportParameters(false)); header.Add(JwtHeaderParameterNames.Epk, epk); } finally { if (staticKey is null) { ephemeralKey.Dispose(); } } SymmetricJwk contentEncryptionKey; if (Algorithm.ProduceEncryptionKey) { using var keyWrapper = new AesKeyWrapper(exchangeHash, EncryptionAlgorithm, _keyManagementAlgorithm !); contentEncryptionKey = keyWrapper.WrapKey(null, header, destination); } else { exchangeHash.CopyTo(destination); contentEncryptionKey = SymmetricJwk.FromSpan(exchangeHash, false); } return(contentEncryptionKey); }
private async Task <Jwk[]> GetKeysAsync() { var keys = new List <Jwk>(); await foreach (var keyProperties in _client.GetPropertiesOfKeysAsync()) { var kvKey = await _client.GetKeyAsync(keyProperties.Name); Jwk?key = null; if (kvKey.Value.KeyType == KeyType.Oct) { key = SymmetricJwk.FromByteArray(kvKey.Value.Key.K, false); } else if (kvKey.Value.KeyType == KeyType.Rsa || kvKey.Value.KeyType == KeyType.RsaHsm) { key = RsaJwk.FromParameters(kvKey.Value.Key.ToRSA(true).ExportParameters(true), false); } #if !NETFRAMEWORK else if (kvKey.Value.KeyType == KeyType.Ec || kvKey.Value.KeyType == KeyType.EcHsm) { ECJwk.FromParameters(ConvertToECParameters(kvKey.Value), computeThumbprint: false); } #endif if (!(key is null)) { key.Kid = JsonEncodedText.Encode(kvKey.Value.Key.Id); if (kvKey.Value.Key.KeyOps != null) { foreach (var operation in kvKey.Value.Key.KeyOps) { key.KeyOps.Add(JsonEncodedText.Encode(operation.ToString())); } } keys.Add(key); } } return(keys.ToArray()); }
public EcdhKeyWrapper(ECJwk key, EncryptionAlgorithm encryptionAlgorithm, KeyManagementAlgorithm algorithm) : base(encryptionAlgorithm, algorithm) { Debug.Assert(key.SupportKeyManagement(algorithm)); Debug.Assert(algorithm.Category == AlgorithmCategory.EllipticCurve); _key = key; if (algorithm.WrappedAlgorithm is null) { _algorithm = encryptionAlgorithm.Name; _keySizeInBytes = encryptionAlgorithm.RequiredKeySizeInBytes; } else { _algorithm = algorithm.Name; _keySizeInBytes = algorithm.WrappedAlgorithm.RequiredKeySizeInBits >> 3; _keyManagementAlgorithm = algorithm.WrappedAlgorithm; } _algorithmNameLength = _algorithm.EncodedUtf8Bytes.Length; _hashAlgorithm = GetHashAlgorithm(encryptionAlgorithm); }
protected override Jwks GetKeysFromSource() { var keys = new List <Jwk>(); foreach (var keyProperties in _client.GetPropertiesOfKeys()) { var kvKey = _client.GetKey(keyProperties.Name); Jwk?key = null; if (kvKey.Value.KeyType == KeyType.Oct) { key = SymmetricJwk.FromByteArray(kvKey.Value.Key.K, false); } else if (kvKey.Value.KeyType == KeyType.Rsa || kvKey.Value.KeyType == KeyType.RsaHsm) { key = RsaJwk.FromParameters(kvKey.Value.Key.ToRSA(true).ExportParameters(true), false); } #if !NETFRAMEWORK else if (kvKey.Value.KeyType == KeyType.Ec || kvKey.Value.KeyType == KeyType.EcHsm) { ECJwk.FromParameters(ConvertToECParameters(kvKey.Value), computeThumbprint: false); } #endif if (!(key is null)) { key.Kid = JsonEncodedText.Encode(kvKey.Value.Key.Id); if (kvKey.Value.Key.KeyOps != null) { foreach (var operation in kvKey.Value.Key.KeyOps) { key.KeyOps.Add(JsonEncodedText.Encode(operation.ToString())); } } keys.Add(key); } } return(new Jwks(_client.VaultUri.ToString(), keys)); }
private async Task <Jwk[]> GetKeysAsync() { var keys = new List <Jwk>(); var keyIdentifiers = await _client.GetKeysAsync(_vaultBaseUrl, MaxResults); foreach (var keyIdentifier in keyIdentifiers) { var kvKey = await _client.GetKeyAsync(keyIdentifier.Identifier.Identifier); Jwk?key = kvKey.Key.Kty switch { JsonWebKeyType.Octet => new SymmetricJwk(kvKey.Key.K), JsonWebKeyType.Rsa => new RsaJwk(kvKey.Key.ToRSAParameters()), JsonWebKeyType.RsaHsm => new RsaJwk(kvKey.Key.ToRSAParameters()), #if !NETFRAMEWORK JsonWebKeyType.EllipticCurve => ECJwk.FromParameters(ConvertToECParameters(kvKey.Key.ToEcParameters())), JsonWebKeyType.EllipticCurveHsm => ECJwk.FromParameters(ConvertToECParameters(kvKey.Key.ToEcParameters())), #endif _ => null }; if (!(key is null)) { key.Kid = kvKey.Key.Kid; if (kvKey.Key.KeyOps != null) { for (int i = 0; i < kvKey.Key.KeyOps.Count; i++) { key.KeyOps.Add(kvKey.Key.KeyOps[i]); } } keys.Add(key); } } return(keys.ToArray()); }
private static JweWrapper CreateDescriptor(KeyManagementAlgorithm algorithm, EncryptionAlgorithm encryptionAlgorithm) { var jwk = algorithm.Category switch { Cryptography.AlgorithmCategory.None => Jwk.None, Cryptography.AlgorithmCategory.EllipticCurve => ECJwk.GeneratePrivateKey(EllipticalCurve.P256, algorithm), Cryptography.AlgorithmCategory.Rsa => RsaJwk.GeneratePrivateKey(4096, algorithm), Cryptography.AlgorithmCategory.Aes => SymmetricJwk.GenerateKey(algorithm), Cryptography.AlgorithmCategory.AesGcm => SymmetricJwk.GenerateKey(algorithm), Cryptography.AlgorithmCategory.Hmac => SymmetricJwk.GenerateKey(algorithm), Cryptography.AlgorithmCategory.Direct => SymmetricJwk.GenerateKey(encryptionAlgorithm), Cryptography.AlgorithmCategory.Direct | Cryptography.AlgorithmCategory.EllipticCurve => ECJwk.GeneratePrivateKey(EllipticalCurve.P256), _ => throw new InvalidOperationException(algorithm.Category.ToString()) }; var descriptor = new JweDescriptor(jwk, algorithm, encryptionAlgorithm) { Payload = new JwsDescriptor(Jwk.None, SignatureAlgorithm.None) { Payload = new JwtPayload { { JwtClaimNames.Iat, EpochTime.UtcNow }, { JwtClaimNames.Exp, EpochTime.UtcNow + EpochTime.OneHour }, { JwtClaimNames.Iss, "https://idp.example.com/" }, { JwtClaimNames.Aud, "636C69656E745F6964" } } } }; var policy = new TokenValidationPolicyBuilder() .AcceptUnsecureToken("https://idp.example.com/") .WithDecryptionKey(jwk) .Build(); var writer = new JwtWriter(); return(new JweWrapper(writer.WriteToken(descriptor), algorithm, encryptionAlgorithm, policy)); } }
/// <inheritsdoc /> public override bool TryUnwrapKey(ReadOnlySpan <byte> keyBytes, Span <byte> destination, JwtHeaderDocument header, out int bytesWritten) { if (!header.TryGetHeaderParameter(JwtHeaderParameterNames.Epk.EncodedUtf8Bytes, out var epk)) { ThrowHelper.ThrowJwtDescriptorException_HeaderIsRequired(JwtHeaderParameterNames.Epk); } header.TryGetHeaderParameter(JwtHeaderParameterNames.Apu.EncodedUtf8Bytes, out JwtElement apu); header.TryGetHeaderParameter(JwtHeaderParameterNames.Apv.EncodedUtf8Bytes, out JwtElement apv); byte[] secretAppend = BuildSecretAppend(apu, apv); ReadOnlySpan <byte> exchangeHash; using (var ephemeralKey = ECDiffieHellman.Create(ECJwk.FromJwtElement(epk).ExportParameters())) { var privateKey = _key.CreateEcdhKey(); if (ephemeralKey.KeySize != privateKey.KeySize) { return(ThrowHelper.TryWriteError(out bytesWritten)); } exchangeHash = new ReadOnlySpan <byte>(privateKey.DeriveKeyFromHash(ephemeralKey.PublicKey, _hashAlgorithm, _secretPreprend, secretAppend), 0, _keySizeInBytes); } if (Algorithm.ProduceEncryptionKey) { using var keyUnwrapper = new AesKeyUnwrapper(exchangeHash, EncryptionAlgorithm, _keyManagementAlgorithm !); return(keyUnwrapper.TryUnwrapKey(keyBytes, destination, header, out bytesWritten)); } else { exchangeHash.CopyTo(destination); bytesWritten = destination.Length; return(true); } }
public void GenerateKey(EllipticalCurve crv) { var key = ECJwk.GeneratePrivateKey(crv); Assert.NotNull(key); }
public ECDsaObjectPoolPolicy(ECJwk key, SignatureAlgorithm algorithm) { _key = key; _algorithm = algorithm; _usePrivateKey = key.HasPrivateKey; }
public void Factory() { var x = Base64Url.Decode("MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4"); var y = Base64Url.Decode("4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM"); var d = Base64Url.Decode("TEkodhWr0iujjHVx7BcV0llS4w5ACGgPrcAd6ZcSR01"); // FromBase64Url var key = ECJwk.FromBase64Url(EllipticalCurve.P256, x: "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4", y: "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM", KeyManagementAlgorithm.EcdhEs, computeThumbprint: true); Assert.True(key.X.SequenceEqual(x)); Assert.True(key.Y.SequenceEqual(y)); Assert.Equal(0, key.D.Length); Assert.NotEqual(0, key.Kid.EncodedUtf8Bytes.Length); key = ECJwk.FromBase64Url(EllipticalCurve.P256, x: "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4", y: "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM", KeyManagementAlgorithm.EcdhEs, computeThumbprint: false); Assert.True(key.X.SequenceEqual(x)); Assert.True(key.Y.SequenceEqual(y)); Assert.Equal(0, key.D.Length); Assert.Equal(0, key.Kid.EncodedUtf8Bytes.Length); key = ECJwk.FromBase64Url(EllipticalCurve.P256, x: "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4", y: "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM", d: "TEkodhWr0iujjHVx7BcV0llS4w5ACGgPrcAd6ZcSR01", KeyManagementAlgorithm.EcdhEs, computeThumbprint: true); Assert.True(key.X.SequenceEqual(x)); Assert.True(key.Y.SequenceEqual(y)); Assert.True(key.D.SequenceEqual(d)); Assert.NotEqual(0, key.Kid.EncodedUtf8Bytes.Length); key = ECJwk.FromBase64Url(EllipticalCurve.P256, x: "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4", y: "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM", d: "TEkodhWr0iujjHVx7BcV0llS4w5ACGgPrcAd6ZcSR01", KeyManagementAlgorithm.EcdhEs, computeThumbprint: false); Assert.True(key.X.SequenceEqual(x)); Assert.True(key.Y.SequenceEqual(y)); Assert.True(key.D.SequenceEqual(d)); Assert.Equal(0, key.Kid.EncodedUtf8Bytes.Length); key = ECJwk.FromBase64Url(EllipticalCurve.P256, x: "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4", y: "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM", SignatureAlgorithm.ES256, computeThumbprint: true); Assert.True(key.X.SequenceEqual(x)); Assert.True(key.Y.SequenceEqual(y)); Assert.Equal(0, key.D.Length); Assert.NotEqual(0, key.Kid.EncodedUtf8Bytes.Length); key = ECJwk.FromBase64Url(EllipticalCurve.P256, x: "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4", y: "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM", SignatureAlgorithm.ES256, computeThumbprint: false); Assert.True(key.X.SequenceEqual(x)); Assert.True(key.Y.SequenceEqual(y)); Assert.Equal(0, key.D.Length); Assert.Equal(0, key.Kid.EncodedUtf8Bytes.Length); key = ECJwk.FromBase64Url(EllipticalCurve.P256, x: "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4", y: "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM", d: "TEkodhWr0iujjHVx7BcV0llS4w5ACGgPrcAd6ZcSR01", SignatureAlgorithm.ES256, computeThumbprint: true); Assert.True(key.X.SequenceEqual(x)); Assert.True(key.Y.SequenceEqual(y)); Assert.True(key.D.SequenceEqual(d)); Assert.NotEqual(0, key.Kid.EncodedUtf8Bytes.Length); key = ECJwk.FromBase64Url(EllipticalCurve.P256, x: "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4", y: "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM", d: "TEkodhWr0iujjHVx7BcV0llS4w5ACGgPrcAd6ZcSR01", SignatureAlgorithm.ES256, computeThumbprint: false); Assert.True(key.X.SequenceEqual(x)); Assert.True(key.Y.SequenceEqual(y)); Assert.True(key.D.SequenceEqual(d)); Assert.Equal(0, key.Kid.EncodedUtf8Bytes.Length); // FromByteArray key = ECJwk.FromByteArray(EllipticalCurve.P256, x: x, y: y, KeyManagementAlgorithm.EcdhEs, computeThumbprint: true); Assert.True(key.X.SequenceEqual(x)); Assert.True(key.Y.SequenceEqual(y)); Assert.Equal(0, key.D.Length); Assert.NotEqual(0, key.Kid.EncodedUtf8Bytes.Length); key = ECJwk.FromByteArray(EllipticalCurve.P256, x: x, y: y, KeyManagementAlgorithm.EcdhEs, computeThumbprint: false); Assert.True(key.X.SequenceEqual(x)); Assert.True(key.Y.SequenceEqual(y)); Assert.Equal(0, key.D.Length); Assert.Equal(0, key.Kid.EncodedUtf8Bytes.Length); key = ECJwk.FromByteArray(EllipticalCurve.P256, x: x, y: y, d: d, KeyManagementAlgorithm.EcdhEs, computeThumbprint: true); Assert.True(key.X.SequenceEqual(x)); Assert.True(key.Y.SequenceEqual(y)); Assert.True(key.D.SequenceEqual(d)); Assert.NotEqual(0, key.Kid.EncodedUtf8Bytes.Length); key = ECJwk.FromByteArray(EllipticalCurve.P256, x: x, y: y, d: d, KeyManagementAlgorithm.EcdhEs, computeThumbprint: false); Assert.True(key.X.SequenceEqual(x)); Assert.True(key.Y.SequenceEqual(y)); Assert.True(key.D.SequenceEqual(d)); Assert.Equal(0, key.Kid.EncodedUtf8Bytes.Length); key = ECJwk.FromByteArray(EllipticalCurve.P256, x: x, y: y, SignatureAlgorithm.ES256, computeThumbprint: true); Assert.True(key.X.SequenceEqual(x)); Assert.True(key.Y.SequenceEqual(y)); Assert.Equal(0, key.D.Length); Assert.NotEqual(0, key.Kid.EncodedUtf8Bytes.Length); key = ECJwk.FromByteArray(EllipticalCurve.P256, x: x, y: y, SignatureAlgorithm.ES256, computeThumbprint: false); Assert.True(key.X.SequenceEqual(x)); Assert.True(key.Y.SequenceEqual(y)); Assert.Equal(0, key.D.Length); Assert.Equal(0, key.Kid.EncodedUtf8Bytes.Length); key = ECJwk.FromByteArray(EllipticalCurve.P256, x: x, y: y, d: d, SignatureAlgorithm.ES256, computeThumbprint: true); Assert.True(key.X.SequenceEqual(x)); Assert.True(key.Y.SequenceEqual(y)); Assert.True(key.D.SequenceEqual(d)); Assert.NotEqual(0, key.Kid.EncodedUtf8Bytes.Length); key = ECJwk.FromByteArray(EllipticalCurve.P256, x: x, y: y, d: d, SignatureAlgorithm.ES256, computeThumbprint: false); Assert.True(key.X.SequenceEqual(x)); Assert.True(key.Y.SequenceEqual(y)); Assert.True(key.D.SequenceEqual(d)); Assert.Equal(0, key.Kid.EncodedUtf8Bytes.Length); }
// SEQUENCE // INTEGER 1 // OCTET STRING private key // [0] // OBJECT IDENTIFIER 1.2.840.10045.3.1.7 // [1] // BIT STRING public key public static ECJwk ReadECPrivateKey(string key) { string base64KeyData = key.Substring(PrivateECKeyPrefix.Length, key.Length - PrivateECKeyPrefix.Length - PrivateECKeySuffix.Length); byte[] keyData = Convert.FromBase64String(base64KeyData); var reader = new AsnReader(keyData); reader = reader.ReadSequence(); var version = reader.ReadInteger(); if (version.Length != 1 || version[0] != 1) { ThrowHelper.ThrowInvalidOperationException_InvalidPem(); } var privateKey = reader.ReadOctetStringBytes().ToArray(); var readerOid = reader.ReadSequence(true); var curveOid = readerOid.ReadOid(); reader = reader.ReadSequence(true); var publicKey = reader.ReadBitStringBytes(); if (publicKey.IsEmpty) { ThrowHelper.ThrowInvalidOperationException_InvalidPem(); } if (publicKey[0] != 0x04) { ThrowHelper.ThrowInvalidOperationException_InvalidPem(); } if (publicKey.Length != 2 * privateKey.Length + 1) { ThrowHelper.ThrowInvalidOperationException_InvalidPem(); } var x = publicKey.Slice(1, privateKey.Length).ToArray(); var y = publicKey.Slice(1 + privateKey.Length).ToArray(); if (reader.Read()) { ThrowHelper.ThrowInvalidOperationException_InvalidPem(); } if (Pkcs8.IsP256(curveOid)) { return(ECJwk.FromByteArray(EllipticalCurve.P256, d: privateKey, x: x, y: y)); } else if (Pkcs8.IsP384(curveOid)) { return(ECJwk.FromByteArray(EllipticalCurve.P384, d: privateKey, x: x, y: y)); } else if (Pkcs8.IsP521(curveOid)) { return(ECJwk.FromByteArray(EllipticalCurve.P521, d: privateKey, x: x, y: y)); } else { throw new NotSupportedException(); } }
// SEQUENCE // INTEGER 0 // SEQUENCE // OBJECT IDENTIFIER 1.2.840.10045.2.1 // OBJECT IDENTIFIER EC curve OID // OCTET STRING // SEQUENCE // INTEGER 1 // OCTET STRING private key // [1] // BIT STRING public key private static ECJwk ReadECPrivateKey(ref AsnReader reader, int[] curveOid) { reader = reader.ReadOctetString(); reader = reader.ReadSequence(); var version = reader.ReadInteger(); if (version.Length != 1 || version[0] != 1) { ThrowHelper.ThrowInvalidOperationException_InvalidPem(); } var privateKey = reader.ReadOctetStringBytes().ToArray(); reader = reader.ReadSequence(true); var publicKey = reader.ReadBitStringBytes(); if (publicKey.IsEmpty) { ThrowHelper.ThrowInvalidOperationException_InvalidPem(); } if (publicKey[0] != 0x04) { ThrowHelper.ThrowInvalidOperationException_InvalidPem(); } if (publicKey.Length != 2 * privateKey.Length + 1) { ThrowHelper.ThrowInvalidOperationException_InvalidPem(); } var x = publicKey.Slice(1, privateKey.Length).ToArray(); var y = publicKey.Slice(1 + privateKey.Length).ToArray(); if (reader.Read()) { ThrowHelper.ThrowInvalidOperationException_InvalidPem(); } if (IsP256(curveOid)) { return(ECJwk.FromByteArray(EllipticalCurve.P256, d: privateKey, x: x, y: y)); } else if (IsP384(curveOid)) { return(ECJwk.FromByteArray(EllipticalCurve.P384, d: privateKey, x: x, y: y)); } else if (IsP521(curveOid)) { return(ECJwk.FromByteArray(EllipticalCurve.P521, d: privateKey, x: x, y: y)); } else { throw new NotSupportedException(); } }