Exemple #1
0
        public CipherSuite(ProtocolVersion version)
        {
            ProtocolVersion = version;
            CipherSuiteID = 0x0000;
            CipherSuiteName = "TLS_NULL_WITH_NULL_NULL";

            _keyExchangeAlgorithm = new KeyExchangeAlgorithmNull();
            _signatureAlgorithm = new SignatureAlgorithmNull();
            _pseudoRandomFunction = null;
            _bulkCipherAlgorithm = new BulkCipherAlgorithmNull();
            _macAlgorithm = new MACAlgorithmNull();
        }
        public CngKey GetPublicKey(SignatureAlgorithm alg, string iid, string kid)
        {
            byte[] x, y;

            if (iid == "1" && kid == "18")
            {
                x = Convert.FromBase64String("UabuaxndEdYE5Nr4fC5ETFcYe7YgyFn4fWqe1R/GB9w=");
                y = Convert.FromBase64String("k/NCBB5W8ZuBqvxZ+GHkI3fS1QflEezF9EriGUVpsAk=");
                return CreatePublicKey(x, y);
            }
            if (iid == _signingIid && kid == _signingKid)
            {
                x = Convert.FromBase64String("YtoaCnZ4QoXQFdfA0ofeVZYLHnTYUo0Q/mV8VPOI3k0=");
                y = Convert.FromBase64String("Gq1o9SAQJ1VpCVelLOC+TuoJH1dFWXiQX7rwmjzoilw=");
                return CreatePublicKey(x, y);
            }

            return null;
        }
        protected HashAlgorithm GetSignatureHashAlgorithm(SignatureAlgorithm signatureAlgorithm, byte hashAlgorithmType)
        {
            if (!signatureAlgorithm.SupportsHashAlgorithmType(hashAlgorithmType)) {
                throw new AlertException(AlertDescription.IllegalParameter,
                                         "Illegal hash algorithm type");
            }

            HashAlgorithm hashAlgorithm;
            switch (hashAlgorithmType) {
            case 1:
                hashAlgorithm = new MD5CryptoServiceProvider();
                break;
            case 2:
                hashAlgorithm = new SHA1CryptoServiceProvider();
                break;
            case 4:
                hashAlgorithm = new SHA256Managed();
                break;
            case 5:
                hashAlgorithm = new SHA384Managed();
                break;
            case 6:
                hashAlgorithm = new SHA512Managed();
                break;
            default:
                throw new AlertException(AlertDescription.InternalError,
                                         "Unsupported hash algorithm type: " + hashAlgorithmType);
            }

            return hashAlgorithm;
        }
Exemple #4
0
        public async Task <int> Run(VerifyOptions options, string httpMessage)
        {
            ISignatureAlgorithm signatureAlgorithmForVerification;

            if (string.IsNullOrEmpty(options.KeyType) || options.KeyType.Equals("RSA", StringComparison.OrdinalIgnoreCase))
            {
                RSAParameters rsaPublicKey;
                using (var stream = File.OpenRead(options.PublicKey)) {
                    using (var reader = new PemReader(stream)) {
                        rsaPublicKey = reader.ReadRsaKey();
                    }
                }
                signatureAlgorithmForVerification = RSASignatureAlgorithm.CreateForVerification(HashAlgorithmName.SHA512, rsaPublicKey);
            }
            else if (options.KeyType.Equals("P256", StringComparison.OrdinalIgnoreCase) || options.KeyType.Equals("ECDSA", StringComparison.OrdinalIgnoreCase))
            {
                ECParameters ecPublicKey;
                using (var stream = File.OpenRead(options.PublicKey)) {
                    using (var reader = new StreamReader(stream)) {
                        var fileContents = reader.ReadToEnd();
                        var lines        = fileContents.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
                        lines = lines.Skip(1).Take(lines.Length - 2).ToArray();
                        var pem      = string.Join("", lines);
                        var ecdsa    = ECDsa.Create();
                        var derArray = Convert.FromBase64String(pem);
                        ecdsa.ImportSubjectPublicKeyInfo(derArray, out _);
                        ecPublicKey = ecdsa.ExportParameters(false);
                    }
                }
                signatureAlgorithmForVerification = ECDsaSignatureAlgorithm.CreateForVerification(HashAlgorithmName.SHA512, ecPublicKey);
            }
            else if (options.KeyType.Equals("HMAC", StringComparison.OrdinalIgnoreCase))
            {
                signatureAlgorithmForVerification = SignatureAlgorithm.CreateForVerification(options.PublicKey, HashAlgorithmName.SHA512);
            }
            else
            {
                throw new NotSupportedException("The specified key type is not supported.");
            }

            var serviceProvider = new ServiceCollection()
                                  .AddHttpMessageSignatureVerification(provider => {
                var clientStore = new InMemoryClientStore();
                clientStore.Register(new Client(
                                         new KeyId("test"),
                                         "ConformanceClient",
                                         signatureAlgorithmForVerification,
                                         TimeSpan.FromSeconds(30),
                                         TimeSpan.FromMinutes(1)));
                return(clientStore);
            })
                                  .BuildServiceProvider();

            var verifier = serviceProvider.GetRequiredService <IRequestSignatureVerifier>();

            var clientRequest   = HttpRequestMessageParser.Parse(httpMessage);
            var requestToVerify = await clientRequest.ToServerSideHttpRequest();

            var verificationResult = await verifier.VerifySignature(requestToVerify, new SignedRequestAuthenticationOptions {
                OnSignatureParsed = (request, signature) => {
                    if (!string.IsNullOrEmpty(options.Algorithm))
                    {
                        signature.Algorithm = options.Algorithm;
                    }

                    return(Task.CompletedTask);
                }
            });

            return(verificationResult is RequestSignatureVerificationResultSuccess
                ? 0
                : 1);
        }
 public JwsWrapper(byte[] token, SignatureAlgorithm algorithm, TokenValidationPolicy policy)
 {
     _token     = token;
     _algorithm = algorithm;
     Policy     = policy;
 }
Exemple #6
0
 public Task <VerifyResult> VerifyAsync(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, CancellationToken cancellationToken = default) => throw new CryptographicException(CRYPT_E_NO_PROVIDER);
        public static async Task <string> Run(SignOptions options)
        {
            var serviceProvider = new ServiceCollection()
                                  .AddHttpMessageSigning()
                                  .BuildServiceProvider();
            var requestSignerFactory = serviceProvider.GetRequiredService <IRequestSignerFactory>();

            ISignatureAlgorithm signatureAlgorithm;

            if (string.IsNullOrEmpty(options.KeyType) || options.KeyType.Equals("RSA", StringComparison.OrdinalIgnoreCase))
            {
                signatureAlgorithm = RSASignatureAlgorithm.CreateForSigning(HashAlgorithmName.SHA512, KeyReader.ReadRSA(options.PrivateKey));
            }
            else if (options.KeyType.Equals("P256", StringComparison.OrdinalIgnoreCase) || options.KeyType.Equals("ECDSA", StringComparison.OrdinalIgnoreCase))
            {
                signatureAlgorithm = ECDsaSignatureAlgorithm.CreateForSigning(HashAlgorithmName.SHA512, KeyReader.ReadECDsaPrivate(options.PrivateKey));
            }
            else if (options.KeyType.Equals("HMAC", StringComparison.OrdinalIgnoreCase))
            {
                signatureAlgorithm = SignatureAlgorithm.CreateForSigning(options.PrivateKey, HashAlgorithmName.SHA512);
            }
            else
            {
                throw new NotSupportedException("The specified key type is not supported.");
            }

            if (!string.IsNullOrEmpty(options.Algorithm) &&
                !options.Algorithm.StartsWith("rsa", StringComparison.OrdinalIgnoreCase) &&
                !options.Algorithm.StartsWith("hmac", StringComparison.OrdinalIgnoreCase) &&
                !options.Algorithm.StartsWith("ecdsa", StringComparison.OrdinalIgnoreCase))
            {
                signatureAlgorithm = new CustomSignatureAlgorithm(options.Algorithm);
            }

            var signingSettings = new SigningSettings {
                SignatureAlgorithm  = signatureAlgorithm,
                EnableNonce         = false,
                DigestHashAlgorithm = HashAlgorithmName.SHA256,
                AutomaticallyAddRecommendedHeaders = false,
                Headers = options.Headers
                          ?.Split(new[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries)
                          .Select(h => new HeaderName(h))
                          .ToArray()
            };
            var signer = requestSignerFactory.Create(
                new KeyId("test"),
                signingSettings);

            var created = DateTimeOffset.UtcNow;

            if (!string.IsNullOrEmpty(options.Created))
            {
                var createdUnix = int.Parse(options.Created);
                created = DateTimeOffset.FromUnixTimeSeconds(createdUnix);
            }

            var expires = signingSettings.Expires;

            if (!string.IsNullOrEmpty(options.Expires))
            {
                var expiresUnix     = int.Parse(options.Expires);
                var expiresAbsolute = DateTimeOffset.FromUnixTimeSeconds(expiresUnix);
                expires = expiresAbsolute - created;
            }

            await signer.Sign(options.Message, created, expires);

            var serializedMessage = HttpMessageSerializer.Serialize(options.Message);

            return(serializedMessage);
        }
 private ParamReadonlyStruct(long id, string name, int requiredKeySizeInBytes, SignatureAlgorithm hashAlgorithm, int requiredKeyWrappedSizeInBytes, EncryptionType encryptionType)
 {
     _id  = id;
     Name = name;
     RequiredKeySizeInBytes        = requiredKeySizeInBytes;
     SignatureAlgorithm            = hashAlgorithm;
     RequiredKeyWrappedSizeInBytes = requiredKeyWrappedSizeInBytes;
     Category = encryptionType;
 }
Exemple #9
0
 public SignatureAndHashAlgorithm(HashAlgorithm hash,
   SignatureAlgorithm signature) {
   this.hash = hash;
   this.signature = signature;
 }
Exemple #10
0
		internal static byte[] CreatePublicKey(SignatureAlgorithm sigAlg, AssemblyHashAlgorithm hashAlg, byte[] modulus, byte[] publicExponent) {
			if (sigAlg != SignatureAlgorithm.CALG_RSA_SIGN)
				throw new ArgumentException("Signature algorithm must be RSA");
			var outStream = new MemoryStream();
			var writer = new BinaryWriter(outStream);
			writer.Write((uint)sigAlg);		// SigAlgID
			writer.Write((uint)hashAlg);	// HashAlgID
			writer.Write(0x14 + modulus.Length);// cbPublicKey
			writer.Write((byte)6);			// bType (public key)
			writer.Write((byte)2);			// bVersion
			writer.Write((ushort)0);		// reserved
			writer.Write((uint)sigAlg);		// aiKeyAlg
			writer.Write(RSA1_SIG);			// magic (RSA1)
			writer.Write(modulus.Length * 8);	// bitlen
			writer.WriteReverse(publicExponent);// pubexp
			writer.WriteReverse(modulus);	// modulus
			return outStream.ToArray();
		}
Exemple #11
0
		void Initialize(BinaryReader reader) {
			try {
				// Read PublicKeyBlob
				signatureAlgorithm = (SignatureAlgorithm)reader.ReadUInt32();
				hashAlgorithm = (AssemblyHashAlgorithm)reader.ReadUInt32();
				int pkLen = reader.ReadInt32();

				// Read PUBLICKEYSTRUC
				if (reader.ReadByte() != 6)
					throw new InvalidKeyException("Not a public key");
				if (reader.ReadByte() != 2)
					throw new InvalidKeyException("Invalid version");
				reader.ReadUInt16();	// reserved
				if ((SignatureAlgorithm)reader.ReadUInt32() != SignatureAlgorithm.CALG_RSA_SIGN)
					throw new InvalidKeyException("Not RSA sign");

				// Read RSAPUBKEY
				if (reader.ReadUInt32() != RSA1_SIG)	// magic = RSA1
					throw new InvalidKeyException("Invalid RSA1 magic");
				uint bitLength = reader.ReadUInt32();
				publicExponent = reader.ReadBytesReverse(4);

				modulus = reader.ReadBytesReverse((int)(bitLength / 8));
			}
			catch (IOException ex) {
				throw new InvalidKeyException("Invalid public key", ex);
			}
		}
Exemple #12
0
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="modulus">Modulus</param>
		/// <param name="publicExponent">Public exponent</param>
		/// <param name="hashAlgorithm">Hash algorithm</param>
		/// <param name="signatureAlgorithm">Signature algorithm</param>
		public StrongNamePublicKey(byte[] modulus, byte[] publicExponent, AssemblyHashAlgorithm hashAlgorithm, SignatureAlgorithm signatureAlgorithm) {
			this.signatureAlgorithm = signatureAlgorithm;
			this.hashAlgorithm = hashAlgorithm;
			this.modulus = modulus;
			this.publicExponent = publicExponent;
		}
        /// <summary>
        /// Parses the raw data in the record into the appropriate structures using the keyexhange and signature algorithms
        /// provided.
        /// </summary>
        /// <param name="algo"></param>
        /// <param name="sig"></param>
        public void ParseRawData(KeyExchangeAlgorithm algo, SignatureAlgorithm sig)
        {
            KeyExchangeAlgorithm = algo;
            SignatureAlgorithm = sig;
            int nAt = 0;
            // Parse our RawData block into the structures below
            if (KeyExchangeAlgorithm == TLS.KeyExchangeAlgorithm.rsa)
            {

                RSAModulusLength = ByteHelper.ReadUshortBigEndian(RawData, nAt); nAt += 2;
                rsa_modulus = ByteHelper.ReadByteArray(RawData, nAt, RSAModulusLength); nAt += RSAModulusLength;

                RSAExponentLength = ByteHelper.ReadUshortBigEndian(RawData, nAt); nAt += 2;
                rsa_exponent = ByteHelper.ReadByteArray(RawData, nAt, RSAExponentLength); nAt += RSAExponentLength;
            }
            else if (KeyExchangeAlgorithm == TLS.KeyExchangeAlgorithm.rsa)
            {
                dh_p_length = ByteHelper.ReadUshortBigEndian(RawData, nAt); nAt += 2;
                dh_p = ByteHelper.ReadByteArray(RawData, nAt, dh_p_length); nAt += dh_p_length;

                dh_g_length = ByteHelper.ReadUshortBigEndian(RawData, nAt); nAt += 2;
                dh_g = ByteHelper.ReadByteArray(RawData, nAt, dh_g_length); nAt += dh_g_length;

                dh_Ys_length = ByteHelper.ReadUshortBigEndian(RawData, nAt); nAt += 2;
                dh_Ys = ByteHelper.ReadByteArray(RawData, nAt, dh_Ys_length); nAt += dh_Ys_length;

            }
            if ((SignatureAlgorithm == TLS.SignatureAlgorithm.dsa) || (SignatureAlgorithm == TLS.SignatureAlgorithm.rsa))
            {
                HashDigitalSignatureLength = ByteHelper.ReadUshortBigEndian(RawData, nAt); nAt += 2;
                DigitalSignatureOfHash = ByteHelper.ReadByteArray(RawData, nAt, HashDigitalSignatureLength); nAt += HashDigitalSignatureLength;
            }
        }
Exemple #14
0
        private async Task <KeyVaultKey> CreateTestKeyWithKeyMaterial(SignatureAlgorithm algorithm)
        {
            string keyName = Recording.GenerateId();

            JsonWebKey keyMaterial = null;

            switch (algorithm.ToString())
            {
            case SignatureAlgorithm.PS256Value:
            case SignatureAlgorithm.PS384Value:
            case SignatureAlgorithm.PS512Value:
            case SignatureAlgorithm.RS256Value:
            case SignatureAlgorithm.RS384Value:
            case SignatureAlgorithm.RS512Value:
                using (RSA rsa = RSA.Create())
                {
                    RSAParameters rsaParameters = new RSAParameters
                    {
                        D = new byte[] { 0x8a, 0x5a, 0x7f, 0x16, 0x29, 0x95, 0x8b, 0x84, 0xeb, 0x8c, 0xba, 0x93, 0xad, 0xbf, 0x40, 0xa2,
                                         0xcc, 0xb9, 0xe9, 0xf8, 0xaa, 0x42, 0x78, 0x24, 0x5d, 0xdf, 0x99, 0xa1, 0x51, 0xd5, 0x1b, 0xaa,
                                         0xfe, 0x0a, 0xa2, 0x82, 0x49, 0xd3, 0x19, 0x9c, 0xfd, 0x48, 0x92, 0xcc, 0x44, 0x98, 0xaf, 0xbf,
                                         0x09, 0xf9, 0x4f, 0xff, 0xcc, 0x49, 0x75, 0x71, 0x27, 0xe1, 0xd8, 0xe2, 0xf2, 0xb7, 0x75, 0x5f,
                                         0x5b, 0x75, 0x75, 0xff, 0x9f, 0xaa, 0x0d, 0xb5, 0x9a, 0x49, 0xff, 0x0b, 0x85, 0xb7, 0x05, 0xb6,
                                         0x8b, 0xfb, 0x1c, 0x7b, 0x2b, 0xf8, 0xf7, 0x9d, 0xad, 0x4b, 0xe7, 0x30, 0x89, 0x13, 0x9d, 0x2b,
                                         0x7f, 0x40, 0x34, 0x3d, 0x8e, 0x38, 0x43, 0x84, 0x19, 0x67, 0xae, 0xab, 0x65, 0xa3, 0xfd, 0x01,
                                         0xcd, 0x2d, 0x5c, 0x87, 0x9f, 0xb7, 0x07, 0x98, 0x82, 0x74, 0x13, 0x69, 0xd1, 0xba, 0x6c, 0xea,
                                         0xf9, 0x54, 0x59, 0xa1, 0x3d, 0x8a, 0xaf, 0x4c, 0xa6, 0x22, 0xde, 0x2a, 0xe3, 0xc1, 0x68, 0x4e,
                                         0xc4, 0x5f, 0x49, 0xe6, 0x78, 0xb6, 0x7c, 0xa7, 0x90, 0xeb, 0xa2, 0x78, 0x93, 0xb4, 0xbb, 0xd2,
                                         0x59, 0x13, 0xe9, 0x20, 0xf5, 0x1a, 0xe5, 0x27, 0x27, 0x6c, 0x98, 0x9e, 0x20, 0x73, 0xc6, 0x61,
                                         0x4f, 0x01, 0x10, 0xf7, 0xb7, 0xe8, 0x17, 0x5f, 0x0e, 0x6b, 0x2b, 0x02, 0xf5, 0xe7, 0x4e, 0x16,
                                         0xcb, 0xd7, 0x6d, 0xb3, 0x80, 0x17, 0xac, 0xad, 0x5c, 0x48, 0x16, 0xf1, 0x2a, 0xf2, 0xde, 0x14,
                                         0xb4, 0x1b, 0x1a, 0x52, 0x11, 0x75, 0x05, 0xd8, 0x2e, 0x37, 0xe3, 0x31, 0xa5, 0x81, 0xa3, 0x29,
                                         0x20, 0xae, 0x6f, 0x52, 0xf6, 0xe4, 0xd1, 0xc2, 0x73, 0x3f, 0x2e, 0x56, 0x8a, 0xa1, 0xc3, 0x0c,
                                         0x4c, 0x1d, 0xb4, 0x77, 0xb9, 0x2a, 0xd4, 0x88, 0xc1, 0xb3, 0x3e, 0x2b, 0xd1, 0x98, 0x49, 0x8d },

                        DP = new byte[] { 0x05, 0x0c, 0x0c, 0xe9, 0x95, 0x77, 0x4d, 0x0f, 0x1e, 0x4a, 0x95, 0xbf, 0xcb, 0x0e, 0x03, 0x89,
                                          0x6f, 0xe6, 0x56, 0x54, 0xb6, 0x5a, 0x19, 0xdd, 0x7e, 0xde, 0x06, 0xce, 0xdc, 0x1b, 0x76, 0xa1,
                                          0xaa, 0x02, 0xa6, 0x77, 0x52, 0xa4, 0xbf, 0x4b, 0x18, 0x9a, 0x91, 0xc5, 0x86, 0x4a, 0xa2, 0x5f,
                                          0xcc, 0x2c, 0x3e, 0x18, 0x75, 0x75, 0xb3, 0xb4, 0x85, 0xbd, 0x6a, 0x75, 0x01, 0x88, 0xd7, 0xb6,
                                          0x63, 0xb8, 0x4e, 0xed, 0x69, 0x53, 0xb2, 0xb3, 0x80, 0xf3, 0x24, 0x4c, 0x18, 0x21, 0x18, 0xf5,
                                          0xd0, 0xea, 0xf3, 0x53, 0x49, 0x74, 0x5a, 0xc5, 0x07, 0xe6, 0xbc, 0xe0, 0x48, 0x6b, 0xa0, 0xcf,
                                          0x0e, 0x27, 0x80, 0xde, 0x3e, 0x65, 0x30, 0x1e, 0x8a, 0xcb, 0x7b, 0x55, 0xb1, 0xd4, 0x3e, 0xe8,
                                          0x3d, 0xb0, 0xf1, 0x2a, 0x5d, 0x63, 0x33, 0x05, 0x04, 0xc0, 0x52, 0x4d, 0x68, 0xff, 0x28, 0xf9, },

                        DQ = new byte[] { 0xcc, 0xf9, 0x20, 0x49, 0xfd, 0x71, 0x7b, 0x95, 0xb4, 0x6e, 0xb6, 0xdb, 0x3f, 0x99, 0x5c, 0x2a,
                                          0xf1, 0xf7, 0x17, 0x35, 0x29, 0xc7, 0x2a, 0x87, 0x6b, 0x0c, 0x8b, 0xad, 0x35, 0x00, 0xff, 0xa2,
                                          0xd8, 0x22, 0x75, 0x35, 0x3e, 0x6d, 0xd9, 0x3d, 0x39, 0x1d, 0x06, 0x65, 0x26, 0x08, 0x19, 0xb0,
                                          0xe7, 0xd7, 0x6d, 0xd0, 0xec, 0xc4, 0xe7, 0xcb, 0x2a, 0xe4, 0x2d, 0x78, 0x09, 0x9e, 0x5d, 0x86,
                                          0x8c, 0x85, 0x27, 0xb7, 0x4f, 0xed, 0x22, 0xe3, 0xe5, 0x7a, 0x0a, 0xc0, 0xe0, 0x6d, 0xe7, 0x6a,
                                          0x5c, 0x8c, 0xb6, 0x6a, 0x79, 0x72, 0x6d, 0x12, 0xa4, 0x65, 0x5b, 0xa0, 0xa9, 0xcb, 0x8d, 0x2b,
                                          0xeb, 0x1b, 0x81, 0x84, 0x26, 0xf7, 0x00, 0x49, 0x25, 0x4a, 0xc9, 0xda, 0x43, 0x60, 0x15, 0x47,
                                          0x65, 0x94, 0xe3, 0xb9, 0x0b, 0x00, 0xcb, 0x07, 0x3f, 0x5d, 0xdf, 0x19, 0x4b, 0x0f, 0x84, 0x17, },

                        Exponent = new byte[] { 0x01, 0x00, 0x01, },

                        InverseQ = new byte[] { 0xc2, 0xb4, 0x1c, 0x29, 0x19, 0x9e, 0x24, 0xe3, 0x38, 0xe0, 0x9b, 0x25, 0x12, 0x25, 0x5b, 0x5f,
                                                0xdb, 0x45, 0x72, 0xe8, 0xbe, 0x25, 0x4e, 0xc7, 0x0d, 0x15, 0x05, 0x18, 0xa8, 0x47, 0xf7, 0x87,
                                                0xa4, 0xa5, 0x02, 0xa5, 0xa0, 0x00, 0xd9, 0x98, 0xf2, 0xf4, 0x33, 0x64, 0x80, 0x30, 0xb9, 0x6c,
                                                0xcc, 0x83, 0xc0, 0x7a, 0xf3, 0x32, 0xfd, 0x60, 0x91, 0x02, 0x61, 0x9e, 0x79, 0x68, 0xcd, 0x84,
                                                0x6c, 0x39, 0x1e, 0x47, 0xb1, 0x13, 0xf9, 0xea, 0x2b, 0xc9, 0x65, 0xd5, 0x1d, 0x8a, 0x47, 0xf4,
                                                0xa3, 0xf2, 0x01, 0x50, 0x0a, 0xad, 0x72, 0xcd, 0xe3, 0x19, 0x67, 0x3e, 0x15, 0x8d, 0x40, 0x7c,
                                                0x8f, 0x30, 0xa0, 0xc9, 0x3b, 0xf9, 0x96, 0xba, 0x58, 0xae, 0xd6, 0xc8, 0x26, 0xa6, 0xa2, 0xa8,
                                                0x0f, 0x96, 0x2b, 0x28, 0xf8, 0x39, 0x11, 0xa1, 0xf0, 0x6a, 0xc5, 0xdd, 0x99, 0x5b, 0x18, 0x1a, },

                        Modulus = new byte[] { 0xc7, 0x61, 0xab, 0x5f, 0xc0, 0x4c, 0x50, 0xdf, 0x3a, 0x21, 0x87, 0x41, 0x6b, 0x42, 0x3d, 0xbd,
                                               0xd7, 0x81, 0xe5, 0xed, 0xc0, 0x59, 0xe6, 0xa0, 0xd0, 0xcc, 0x7e, 0xd7, 0xbe, 0x0f, 0xcd, 0xd5,
                                               0x3d, 0x23, 0x08, 0xa2, 0x81, 0x94, 0xc8, 0x60, 0xd0, 0xfc, 0xe8, 0xf6, 0xdf, 0x22, 0xe8, 0xa1,
                                               0xae, 0x4c, 0xab, 0x78, 0xe6, 0x7d, 0x65, 0x1c, 0x20, 0x1a, 0x7b, 0xf2, 0xd9, 0x10, 0xa2, 0x85,
                                               0x28, 0x81, 0xc0, 0x1d, 0x4d, 0xc6, 0xf0, 0x4f, 0x36, 0xe0, 0x83, 0x14, 0x4c, 0x30, 0x5c, 0xef,
                                               0x9c, 0x93, 0x26, 0x7f, 0xf4, 0x67, 0x93, 0x47, 0xe8, 0x3b, 0x27, 0x91, 0xfb, 0xe9, 0xfd, 0xbb,
                                               0x67, 0x9a, 0xa6, 0x0f, 0x84, 0x47, 0xae, 0x55, 0x55, 0x38, 0x32, 0x68, 0xfc, 0x97, 0x42, 0xc1,
                                               0x77, 0x4e, 0x7c, 0x8e, 0xc2, 0x24, 0xe9, 0x9c, 0x29, 0x12, 0xf6, 0xce, 0x90, 0xa3, 0x77, 0x05,
                                               0xaa, 0xc7, 0x63, 0x62, 0x3b, 0x38, 0xf6, 0xee, 0x77, 0x46, 0x0b, 0xed, 0xca, 0xca, 0x6e, 0x6e,
                                               0x08, 0xd1, 0x5e, 0xa9, 0xd1, 0x86, 0xea, 0xdf, 0xcc, 0x7c, 0x17, 0x9c, 0xf2, 0xae, 0x4c, 0x02,
                                               0xe8, 0x47, 0xcf, 0x95, 0xf0, 0x7c, 0x2f, 0x6f, 0x9b, 0x97, 0x87, 0xe7, 0x98, 0xf4, 0x07, 0x4d,
                                               0xd5, 0x2d, 0xf3, 0x5e, 0x91, 0x52, 0x57, 0x99, 0xbd, 0x54, 0xb5, 0x04, 0xef, 0xc8, 0x14, 0x0b,
                                               0xe0, 0xb3, 0x0b, 0x72, 0xb8, 0x43, 0x0e, 0x1f, 0x13, 0x79, 0xa1, 0x88, 0xc9, 0x96, 0x39, 0x68,
                                               0xcb, 0x16, 0x2c, 0xfd, 0xa4, 0x5f, 0x3a, 0x0d, 0x31, 0xd8, 0xc1, 0x12, 0x02, 0xf7, 0x3b, 0x6c,
                                               0xa1, 0x30, 0xad, 0x6d, 0xa4, 0xcf, 0x42, 0xe2, 0xb6, 0x5c, 0xdc, 0x33, 0xf5, 0x17, 0xda, 0x3a,
                                               0x66, 0xdf, 0xdf, 0x6a, 0x04, 0x51, 0x84, 0x8b, 0x3d, 0x8b, 0x7b, 0x9f, 0x7a, 0xd7, 0xdf, 0xad, },

                        P = new byte[] { 0xca, 0x2e, 0x9f, 0xdd, 0x52, 0x22, 0x31, 0xd3, 0x75, 0x50, 0x1f, 0xab, 0x00, 0x48, 0x62, 0xcf,
                                         0x17, 0x1f, 0xa5, 0x17, 0xe4, 0x46, 0x22, 0xfc, 0xfc, 0x2b, 0x73, 0x4e, 0xb2, 0x1f, 0xb9, 0x72,
                                         0xa4, 0xaa, 0x52, 0xee, 0x05, 0xa4, 0xeb, 0x51, 0xfa, 0xa0, 0x9b, 0x3d, 0xf9, 0xc4, 0x04, 0x22,
                                         0xd2, 0xf0, 0xb4, 0xff, 0xee, 0x2f, 0xc0, 0x81, 0x2a, 0x3d, 0x5e, 0xe4, 0x75, 0x55, 0xf2, 0x1c,
                                         0x13, 0xd3, 0x59, 0x26, 0x38, 0x81, 0x91, 0xb6, 0xb6, 0x8e, 0x47, 0x3c, 0x27, 0x9e, 0x87, 0x07,
                                         0x2d, 0xcf, 0xd7, 0xaa, 0x5f, 0x15, 0x50, 0xf5, 0xc7, 0x01, 0x5f, 0x9c, 0xae, 0x9d, 0xec, 0x63,
                                         0xfc, 0x04, 0xda, 0xb7, 0xe7, 0x80, 0x14, 0x9c, 0xef, 0x6a, 0xbd, 0x36, 0x02, 0xce, 0xaa, 0xf3,
                                         0x93, 0x46, 0x8c, 0xb9, 0x0b, 0x82, 0xe1, 0x5d, 0x39, 0xcb, 0x46, 0x5f, 0xa7, 0xd5, 0xbe, 0xef, },

                        Q = new byte[] { 0xfc, 0x74, 0x33, 0xc3, 0x32, 0x64, 0x9f, 0x78, 0xe7, 0xfd, 0x79, 0xc0, 0xb0, 0x60, 0x1f, 0x94,
                                         0xc3, 0x3d, 0xd9, 0xfc, 0x02, 0xf7, 0x16, 0x2d, 0x47, 0x88, 0xfc, 0xf4, 0x13, 0xa3, 0xbf, 0x25,
                                         0x80, 0x3c, 0x1b, 0x1d, 0x12, 0x43, 0x5c, 0xce, 0x22, 0xa4, 0x01, 0x7e, 0x04, 0x7a, 0xf3, 0x11,
                                         0x66, 0x36, 0x49, 0x3c, 0x3b, 0x6f, 0x49, 0x69, 0x74, 0xd5, 0x35, 0x23, 0x90, 0x47, 0xb3, 0x15,
                                         0xe7, 0xa5, 0x26, 0x48, 0x9d, 0xb5, 0x38, 0xa0, 0x44, 0x58, 0x63, 0xb2, 0xdd, 0x94, 0xaf, 0x2e,
                                         0x42, 0x08, 0x25, 0x19, 0x4a, 0x7b, 0xe5, 0x72, 0xbe, 0xd5, 0xa3, 0x92, 0x0b, 0xba, 0xf7, 0x5f,
                                         0x0b, 0x18, 0xa6, 0x62, 0x19, 0x6d, 0x53, 0xc1, 0x8a, 0x86, 0x19, 0x43, 0x53, 0xa4, 0x3a, 0x53,
                                         0x94, 0xd9, 0x99, 0x8b, 0x3a, 0xe4, 0x1e, 0xc5, 0x86, 0x15, 0x89, 0x53, 0xb5, 0x3d, 0x8b, 0x23, },
                    };

                    rsa.ImportParameters(rsaParameters);

                    keyMaterial = new JsonWebKey(rsa, includePrivateParameters: true);
                }

                break;

            case SignatureAlgorithm.ES256Value:
            case SignatureAlgorithm.ES256KValue:
            case SignatureAlgorithm.ES384Value:
            case SignatureAlgorithm.ES512Value:
#if NET461
                Assert.Ignore("Creating JsonWebKey with ECDsa is not supported on net461.");
#else
                KeyCurveName curveName = algorithm.GetEcKeyCurveName();
                ECCurve      curve     = ECCurve.CreateFromOid(curveName.Oid);

                using (ECDsa ecdsa = ECDsa.Create())
                {
                    try
                    {
                        ecdsa.GenerateKey(curve);
                        keyMaterial = new JsonWebKey(ecdsa, includePrivateParameters: true);
                    }
                    catch (NotSupportedException)
                    {
                        Assert.Inconclusive("This platform does not support OID {0}", curveName.Oid);
                    }
                }
#endif

                break;

            default:
                throw new ArgumentException("Invalid Algorithm", nameof(algorithm));
            }

            KeyVaultKey key = await Client.ImportKeyAsync(keyName, keyMaterial);

            keyMaterial.Id = key.Key.Id;
            key.Key        = keyMaterial;

            return(key);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="Cryptography.SignResult"/> for mocking purposes.
 /// </summary>
 /// <param name="keyId">Sets the <see cref="SignResult.KeyId"/> property.</param>
 /// <param name="signature">Sets the <see cref="SignResult.Signature"/> property.</param>
 /// <param name="algorithm">Sets the <see cref="SignResult.Algorithm"/> property.</param>
 /// <returns>A new instance of the <see cref="Cryptography.SignResult"/> for mocking purposes.</returns>
 public static SignResult SignResult(string keyId = default, byte[] signature = default, SignatureAlgorithm algorithm = default) => new SignResult
 {
     KeyId     = keyId,
     Signature = signature,
     Algorithm = algorithm,
 };
Exemple #16
0
        void genVerboseString(StringBuilder SB)
        {
            String n = Environment.NewLine;

            SB.Append($"X509 Certificate Revocation List:{n}");
            SB.Append($"Version: {Version}{n}");
            SB.Append($"Issuer: {n}");
            String[] tokens = Issuer.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            for (Int32 index = 0; index < tokens.Length; index++)
            {
                tokens[index] = "    " + tokens[index].Trim();
            }
            SB.Append(String.Join(n, tokens) + n);
            SB.Append($"This Update: {ThisUpdate}{n}");
            if (NextUpdate == null)
            {
                SB.Append($"Next Update: Infinity{n}");
            }
            else
            {
                SB.Append($"Next Update: {NextUpdate}{n}");
            }
            if (RevokedCertificates == null)
            {
                SB.Append($"CRL Entries: 0{n}");
            }
            else
            {
                SB.Append($"CRL Entries: {RevokedCertificates.Count}{n}");
                foreach (X509CRLEntry revcert in RevokedCertificates)
                {
                    SB.Append($"    Serial Number: {revcert.SerialNumber}{n}");
                    SB.Append($"    Revocation Date: {revcert.RevocationDate}{n}");
                    if (revcert.ReasonCode != 0)
                    {
                        SB.Append($"    Revocation Reason: {revcert.ReasonMessage} ({revcert.ReasonCode}){n}");
                    }
                    SB.Append(n);
                }
            }
            if (Extensions == null)
            {
                SB.Append($"CRL Extensions: 0{n}");
            }
            else
            {
                SB.Append($"CRL Extensions: {Extensions.Count}{n}");
                foreach (X509Extension ext in Extensions)
                {
                    SB.Append($"  OID={ext.Oid.Format(true)}");
                    SB.Append($"Critical={ext.Critical}, Length={ext.RawData.Length} ({ext.RawData.Length:x2}):{n}");
                    SB.Append($"    {ext.Format(true).Replace(n, $"{n}    ").TrimEnd()}{n}{n}");
                }
            }
            SB.Append("Signature Algorithm:" + n);
            SB.Append($"    Algorithm ObjectId: {SignatureAlgorithm.Format(true)}{n}");
            SB.Append($"Signature: Unused bits={sigUnused}{n}    ");
            String tempString = AsnFormatter.BinaryToString(signature, EncodingType.HexAddress);

            SB.Append($"{tempString.Replace(n, $"{n}    ").TrimEnd()}{n}");
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="Cryptography.VerifyResult"/> for mocking purposes.
 /// </summary>
 /// <param name="keyId">Sets the <see cref="VerifyResult.KeyId"/> property.</param>
 /// <param name="isValid">Sets the <see cref="VerifyResult.IsValid"/> property.</param>
 /// <param name="algorithm">Sets the <see cref="VerifyResult.Algorithm"/> property.</param>
 /// <returns>A new instance of the <see cref="Cryptography.VerifyResult"/> for mocking purposes.</returns>
 public static VerifyResult VerifyResult(string keyId = default, bool isValid = default, SignatureAlgorithm algorithm = default) => new VerifyResult
 {
     KeyId     = keyId,
     IsValid   = isValid,
     Algorithm = algorithm,
 };
Exemple #18
0
 public byte[] Sign()
 {
     // no input because Write has already updated the hash
     return(SignatureAlgorithm.Sign(new byte[0], HashAlgorithm));
 }
        public CompositionTests()
        {
            _rsa = new RSACryptoServiceProvider();
            var services = new ServiceCollection();

            services
            .AddHttpMessageSigning("unit-test-app", settings => { settings.SignatureAlgorithm = SignatureAlgorithm.CreateForSigning("s3cr3t"); })
            .AddHMACHttpMessageSigning("unit-test-app-hmac", "s3cr3t")
            .AddRSAHttpMessageSigning("unit-test-app-rsa", _rsa);
            _provider = services.BuildServiceProvider();
        }
Exemple #20
0
        public static void SignWithSpanWrongSize(SignatureAlgorithm a)
        {
            using var k = new Key(a);

            Assert.Throws <ArgumentException>("signature", () => a.Sign(k, ReadOnlySpan <byte> .Empty, Span <byte> .Empty));
        }
 /// <summary>Add configuration from the OIDC configuration, including issuer validation and signature requirement.</summary>
 public static TokenValidationPolicyBuilder AddOpenIdConfiguration(this TokenValidationPolicyBuilder builder, string metadataAddress, SignatureAlgorithm algorithm)
 {
     return(builder.RequireMetadataConfiguration(metadataAddress, algorithm));
 }
Exemple #22
0
 public SignResult Sign(SignatureAlgorithm algorithm, byte[] digest, CancellationToken cancellationToken = default) => throw new CryptographicException(CRYPT_E_NO_PROVIDER);
        /// <summary>
        /// Creates a new <see cref="CommonFrameHeader"/> from given <paramref name="buffer"/>.
        /// </summary>
        /// <param name="configurationFrame">IEC 61850-90-5 <see cref="ConfigurationFrame"/> if already parsed.</param>
        /// <param name="useETRConfiguration">Determines if system should find associated ETR file using MSVID with same name for configuration.</param>
        /// <param name="guessConfiguration">Determines if system should try to guess at a possible configuration given payload size.</param>
        /// <param name="parseRedundantASDUs">Determines if system should expose redundantly parsed ASDUs.</param>
        /// <param name="ignoreSignatureValidationFailures">Determines if system should ignore checksum signature validation errors.</param>
        /// <param name="ignoreSampleSizeValidationFailures">Determines if system should ignore sample size validation errors.</param>
        /// <param name="angleFormat">Allows customization of the angle parsing format.</param>
        /// <param name="buffer">Buffer that contains data to parse.</param>
        /// <param name="startIndex">Start index into buffer where valid data begins.</param>
        /// <param name="length">Maximum length of valid data from offset.</param>
        // ReSharper disable once UnusedParameter.Local
        public CommonFrameHeader(ConfigurationFrame configurationFrame, bool useETRConfiguration, bool guessConfiguration, bool parseRedundantASDUs, bool ignoreSignatureValidationFailures, bool ignoreSampleSizeValidationFailures, AngleFormat angleFormat, byte[] buffer, int startIndex, int length)
        {
            const byte VersionNumberMask = (byte)IEC61850_90_5.FrameType.VersionNumberMask;

            // Cache behavioral connection parameters
            m_useETRConfiguration = useETRConfiguration;
            m_guessConfiguration  = guessConfiguration;
            m_parseRedundantASDUs = parseRedundantASDUs;
            m_ignoreSignatureValidationFailures  = ignoreSignatureValidationFailures;
            m_ignoreSampleSizeValidationFailures = ignoreSampleSizeValidationFailures;
            m_angleFormat = angleFormat;

            // Ignore the time base from configuration frame if available.  The timebase is not adjustable for 61850.
            m_timebase = Common.Timebase;

            // See if frame is for a common IEEE C37.118 frame (e.g., for configuration or command)
            if (buffer[startIndex] == PhasorProtocols.Common.SyncByte)
            {
                // Strip out frame type and version information...
                m_frameType = (FrameType)(buffer[startIndex + 1] & ~VersionNumberMask);
                m_version   = (byte)(buffer[startIndex + 1] & VersionNumberMask);

                m_frameLength = BigEndian.ToUInt16(buffer, startIndex + 2);
                m_idCode      = BigEndian.ToUInt16(buffer, startIndex + 4);

                uint secondOfCentury  = BigEndian.ToUInt32(buffer, startIndex + 6);
                uint fractionOfSecond = BigEndian.ToUInt32(buffer, startIndex + 10);

                // Without timebase, the best timestamp you can get is down to the whole second
                m_timestamp = new UnixTimeTag((decimal)secondOfCentury).ToDateTime().Ticks;

                // "Actual fractional seconds" are obtained by taking fractionOfSecond and dividing by timebase.
                // Since we are converting to ticks, we need to multiply by Ticks.PerSecond.
                // We do the multiplication first so that the whole operation can be done using integer arithmetic.
                // m_timebase / 2L is added before dividing by timebase in order to round the result.
                long ticksBeyondSecond = (fractionOfSecond & ~Common.TimeQualityFlagsMask) * Ticks.PerSecond;
                m_timestamp += (ticksBeyondSecond + m_timebase / 2L) / m_timebase;

                if (configurationFrame is not null)
                {
                    // Hang on to configured frame rate and ticks per frame
                    m_framesPerSecond = configurationFrame.FrameRate;
                    m_ticksPerFrame   = Ticks.PerSecond / (double)m_framesPerSecond;
                }

                m_timeQualityFlags = fractionOfSecond & Common.TimeQualityFlagsMask;
            }
            else if (buffer[startIndex + 1] == Common.CltpTag)
            {
                // Make sure there is enough data to parse session header from frame
                if (length > Common.SessionHeaderSize)
                {
                    // Manually assign frame type - this is an IEC 61850-90-5 data frame
                    m_frameType = IEC61850_90_5.FrameType.DataFrame;

                    // Calculate CLTP tag length
                    int cltpTagLength = buffer[startIndex] + 1;

                    // Initialize buffer parsing index starting past connectionless transport protocol header
                    int index = startIndex + cltpTagLength;

                    // Start calculating total frame length
                    int frameLength = cltpTagLength;

                    // Get session type (Goose, sampled values, etc.)
                    SessionType sessionType = (SessionType)buffer[index++];

                    // Make sure session type is sampled values
                    if (sessionType == SessionType.SampledValues)
                    {
                        byte headerSize = buffer[index];

                        // Make sure header size is standard
                        if (headerSize == Common.SessionHeaderSize)
                        {
                            // Skip common header tag
                            index += 3;

                            // Get SPDU length
                            SpduLength = BigEndian.ToUInt32(buffer, index);
                            index     += 4;

                            // Add SPDU length to total frame length (updated as of 10/3/2012 to accommodate extra 6 bytes)
                            frameLength += (int)SpduLength + 8;

                            // Make sure full frame of data is available - cannot calculate full frame length needed for check sum
                            // without the entire frame since signature algorithm calculation length varies by type and size
                            if (length > SpduLength + 13)
                            {
                                // Get SPDU packet number
                                m_packetNumber = BigEndian.ToUInt32(buffer, index);

                                // Get security algorithm type
                                m_securityAlgorithm = (SecurityAlgorithm)buffer[index + 12];

                                // Get signature algorithm type
                                m_signatureAlgorithm = (SignatureAlgorithm)buffer[index + 13];

                                // Get current key ID
                                m_keyID = BigEndian.ToUInt32(buffer, index + 14);

                                // Add signature calculation result length to total frame length
                                switch (m_signatureAlgorithm)
                                {
                                case SignatureAlgorithm.None:
                                    break;

                                case SignatureAlgorithm.Sha80:
                                    frameLength += 11;
                                    break;

                                case SignatureAlgorithm.Sha128:
                                case SignatureAlgorithm.Aes128:
                                    frameLength += 17;
                                    break;

                                case SignatureAlgorithm.Sha256:
                                    frameLength += 33;
                                    break;

                                case SignatureAlgorithm.Aes64:
                                    frameLength += 9;
                                    break;

                                default:
                                    throw new InvalidOperationException($"Invalid IEC 61850-90-5 signature algorithm detected: 0x{buffer[index].ToString("X").PadLeft(2, '0')}");
                                }

                                // Check signature algorithm packet checksum here, this step is skipped in data frame parsing due to non-standard location...
                                if (m_signatureAlgorithm != SignatureAlgorithm.None)
                                {
                                    int packetIndex = startIndex + cltpTagLength;
                                    int hmacIndex   = (int)(packetIndex + SpduLength + 2);

                                    // Check for signature tag
                                    if (buffer[hmacIndex++] == 0x85)
                                    {
                                        // KeyID is technically a lookup into derived rotating keys, but all these are using dummy key for now
                                        HMAC hmac   = m_signatureAlgorithm <= SignatureAlgorithm.Sha256 ? new ShaHmac(Common.DummyKey) : (HMAC) new AesHmac(Common.DummyKey);
                                        int  result = 0;

                                        switch (m_signatureAlgorithm)
                                        {
                                        case SignatureAlgorithm.None:
                                            break;

                                        case SignatureAlgorithm.Aes64:
                                            m_sourceHash     = buffer.BlockCopy(hmacIndex, 8);
                                            m_calculatedHash = hmac.ComputeHash(buffer, packetIndex, (int)SpduLength).BlockCopy(0, 8);
                                            result           = m_sourceHash.CompareTo(0, m_calculatedHash, 0, 8);
                                            break;

                                        case SignatureAlgorithm.Sha80:
                                            m_sourceHash     = buffer.BlockCopy(hmacIndex, 10);
                                            m_calculatedHash = hmac.ComputeHash(buffer, packetIndex, (int)SpduLength).BlockCopy(0, 10);
                                            result           = m_sourceHash.CompareTo(0, m_calculatedHash, 0, 10);
                                            break;

                                        case SignatureAlgorithm.Sha128:
                                        case SignatureAlgorithm.Aes128:
                                            m_sourceHash     = buffer.BlockCopy(hmacIndex, 16);
                                            m_calculatedHash = hmac.ComputeHash(buffer, packetIndex, (int)SpduLength).BlockCopy(0, 16);
                                            result           = m_sourceHash.CompareTo(0, m_calculatedHash, 0, 16);
                                            break;

                                        case SignatureAlgorithm.Sha256:
                                            m_sourceHash     = buffer.BlockCopy(hmacIndex, 32);
                                            m_calculatedHash = hmac.ComputeHash(buffer, packetIndex, (int)SpduLength).BlockCopy(0, 32);
                                            result           = m_sourceHash.CompareTo(0, m_calculatedHash, 0, 32);
                                            break;

                                        default:
                                            throw new NotSupportedException($"IEC 61850-90-5 signature algorithm \"{m_signatureAlgorithm}\" is not currently supported: ");
                                        }

                                        if (result != 0 && !m_ignoreSignatureValidationFailures)
                                        {
                                            throw new CrcException("Invalid binary image detected - IEC 61850-90-5 check sum does not match.");
                                        }
                                    }
                                    else
                                    {
                                        throw new CrcException("Invalid binary image detected - expected IEC 61850-90-5 check sum does not exist.");
                                    }
                                }

                                // Get payload length
                                index       += 18;
                                m_dataLength = (ushort)BigEndian.ToUInt32(buffer, index);
                                index       += 4;

                                // Confirm payload type tag is sampled values
                                if (buffer[index] != 0x82)
                                {
                                    throw new InvalidOperationException($"Encountered a payload that is not tagged 0x82 for sampled values: 0x{buffer[index].ToString("X").PadLeft(2, '0')}");
                                }

                                index++;

                                // Get simulated bit value
                                m_simulatedData = buffer[index++] != 0;

                                // Get application ID
                                m_applicationID = BigEndian.ToUInt16(buffer, index);
                                index          += 2;

                                // Get ASDU payload size
                                m_payloadSize = BigEndian.ToUInt16(buffer, index);
                                index        += 2;

                                // Validate sampled value PDU tag exists and skip past it
                                buffer.ValidateTag(SampledValueTag.SvPdu, ref index);

                                // Parse number of ASDUs tag
                                m_asduCount = buffer.ParseByteTag(SampledValueTag.AsduCount, ref index);

                                if (m_asduCount == 0)
                                {
                                    throw new InvalidOperationException("Total number of ADSUs must be greater than zero.");
                                }

                                // Validate sequence of ASDU tag exists and skip past it
                                buffer.ValidateTag(SampledValueTag.SequenceOfAsdu, ref index);

                                // Set header length
                                m_headerLength = (ushort)(index - startIndex);

                                // Set calculated frame length
                                m_frameLength = (ushort)frameLength;
                            }
                        }
                        else
                        {
                            throw new InvalidOperationException($"Bad data stream, encountered an invalid session header size: {headerSize}");
                        }
                    }
                    else
                    {
                        throw new InvalidOperationException($"This library can only parse IEC 61850-90-5 sampled value sessions, type \"{sessionType}\" is not supported.");
                    }
                }
            }
            else
            {
                throw new InvalidOperationException($"Bad data stream, expected sync byte 0xAA or 0x01 as first byte in IEC 61850-90-5 frame, got 0x{buffer[startIndex].ToString("X").PadLeft(2, '0')}");
            }
        }
Exemple #24
0
 public override void IsSupportedSignature_Success(Jwk key, SignatureAlgorithm alg)
 {
     base.IsSupportedSignature_Success(key, alg);
 }
Exemple #25
0
        public static void SignWithSpanSuccess(SignatureAlgorithm a)
        {
            using var k = new Key(a);

            a.Sign(k, ReadOnlySpan <byte> .Empty, new byte[a.SignatureSize]);
        }
 public virtual void Dispose()
 {
     SignatureAlgorithm?.Dispose();
 }
Exemple #27
0
 public static void VerifyWithNullKey(SignatureAlgorithm a)
 {
     Assert.Throws <ArgumentNullException>("publicKey", () => a.Verify(null !, ReadOnlySpan <byte> .Empty, ReadOnlySpan <byte> .Empty));
 }
Exemple #28
0
 public override Signer CreateSigner_Failed(Jwk key, SignatureAlgorithm alg)
 {
     return(base.CreateSigner_Failed(key, alg));
 }
Exemple #29
0
        public static void VerifyWithWrongKey(SignatureAlgorithm a)
        {
            using var k = new Key(KeyAgreementAlgorithm.X25519);

            Assert.Throws <ArgumentException>("publicKey", () => a.Verify(k.PublicKey, ReadOnlySpan <byte> .Empty, ReadOnlySpan <byte> .Empty));
        }
Exemple #30
0
 public virtual void IsSupportedSignature_Success(Jwk key, SignatureAlgorithm alg)
 {
     Assert.True(key.SupportSignature(alg));
 }
Exemple #31
0
        public static void VerifyWithWrongSize(SignatureAlgorithm a)
        {
            using var k = new Key(a);

            Assert.False(a.Verify(k.PublicKey, ReadOnlySpan <byte> .Empty, ReadOnlySpan <byte> .Empty));
        }
Exemple #32
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="modulus">Modulus</param>
 /// <param name="publicExponent">Public exponent</param>
 /// <param name="hashAlgorithm">Hash algorithm</param>
 /// <param name="signatureAlgorithm">Signature algorithm</param>
 public StrongNamePublicKey(byte[] modulus, byte[] publicExponent, AssemblyHashAlgorithm hashAlgorithm, SignatureAlgorithm signatureAlgorithm)
 {
     this.signatureAlgorithm = signatureAlgorithm;
     this.hashAlgorithm      = hashAlgorithm;
     this.modulus            = modulus;
     this.publicExponent     = publicExponent;
 }
Exemple #33
0
 public static void Properties(SignatureAlgorithm a)
 {
     Assert.True(a.PublicKeySize > 0);
     Assert.True(a.PrivateKeySize > 0);
     Assert.True(a.SignatureSize > 0);
 }
 public InsecureAlgorithmError(SignatureAlgorithm value) => m_value = value;
Exemple #35
0
 public static void SignWithSpanWithNullKey(SignatureAlgorithm a)
 {
     Assert.Throws <ArgumentNullException>("key", () => a.Sign(null !, ReadOnlySpan <byte> .Empty, Span <byte> .Empty));
 }
Exemple #36
0
        public static Generator GenPki(string cn, string org, string orgun, string city, string state, string country,
                                       SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.SHA256,
                                       RsaKeyLength rsaKeyLength             = RsaKeyLength.Length2048Bits)
        {
            Generator generator = new Generator();


            // Determines Signature Algorithm
            string signatureAlgorithmStr;

            switch (signatureAlgorithm)
            {
            case SignatureAlgorithm.SHA1:
                signatureAlgorithmStr = PkcsObjectIdentifiers.Sha1WithRsaEncryption.Id;
                break;

            case SignatureAlgorithm.SHA256:
                signatureAlgorithmStr = PkcsObjectIdentifiers.Sha256WithRsaEncryption.Id;
                break;

            case SignatureAlgorithm.SHA512:
                signatureAlgorithmStr = PkcsObjectIdentifiers.Sha512WithRsaEncryption.Id;
                break;

            default:
                signatureAlgorithmStr = PkcsObjectIdentifiers.Sha256WithRsaEncryption.Id;
                break;
            }

            // Cert Info


            IDictionary attrs = new Hashtable();

            attrs.Add(X509Name.CN, cn);
            attrs.Add(X509Name.O, org);
            attrs.Add(X509Name.OU, orgun);
            attrs.Add(X509Name.L, city);
            attrs.Add(X509Name.ST, state);
            attrs.Add(X509Name.C, country);

            X509Name subject = new X509Name(new ArrayList(attrs.Keys), attrs);


            //Key Generator
            //ECKeyPairGenerator ecKeyPairGenerator = new ECKeyPairGenerator();
            //ecKeyPairGenerator.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), (int)rsaKeyLength));
            //AsymmetricCipherKeyPair pair = ecKeyPairGenerator.GenerateKeyPair();

            X9ECParameters     curve              = ECNamedCurveTable.GetByName("secp256k1");
            ECDomainParameters ecParam            = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H, curve.GetSeed());
            ECKeyPairGenerator ecKeyPairGenerator = new ECKeyPairGenerator();

            ecKeyPairGenerator.Init(new ECKeyGenerationParameters(ecParam, new SecureRandom()));
            AsymmetricCipherKeyPair pair = ecKeyPairGenerator.GenerateKeyPair();

            //RsaKeyPairGenerator rsaKeyPairGenerator = new RsaKeyPairGenerator();
            //rsaKeyPairGenerator.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), (int)rsaKeyLength));
            //AsymmetricCipherKeyPair pair = rsaKeyPairGenerator.GenerateKeyPair();

            //CSR Generator

            //Asn1SignatureFactory signatureFactory = new Asn1SignatureFactory(signatureAlgorithmStr, pair.Private);
            Asn1SignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHECDSA", pair.Private);

            Pkcs10CertificationRequest csr = new Pkcs10CertificationRequest(signatureFactory, subject, pair.Public, null, pair.Private);



            /***************************
            ****************************
            **Convert to PEM and Output*
            ****************************
            ***************************/

            //Private Key

            StringBuilder privateKeyStrBuilder = new StringBuilder();
            PemWriter     privateKeyPemWriter  = new PemWriter(new StringWriter(privateKeyStrBuilder));

            privateKeyPemWriter.WriteObject(pair.Private);
            privateKeyPemWriter.Writer.Flush();

            pkey = privateKeyStrBuilder.ToString();

            //Public Key

            StringBuilder publicKeyStrBuilder = new StringBuilder();
            PemWriter     publicKeyPemWriter  = new PemWriter(new StringWriter(publicKeyStrBuilder));

            publicKeyPemWriter.WriteObject(pair.Private);
            publicKeyPemWriter.Writer.Flush();

            generator.PublicKey = publicKeyStrBuilder.ToString();


            //CSR

            StringBuilder csrStrBuilder = new StringBuilder();
            PemWriter     csrPemWriter  = new PemWriter(new StringWriter(csrStrBuilder));

            csrPemWriter.WriteObject(csr);
            csrPemWriter.Writer.Flush();

            csR = csrStrBuilder.ToString();

            return(generator);
        }
Exemple #37
0
        public static void SignWithSpanWithWrongKey(SignatureAlgorithm a)
        {
            using var k = new Key(KeyAgreementAlgorithm.X25519);

            Assert.Throws <ArgumentException>("key", () => a.Sign(k, ReadOnlySpan <byte> .Empty, Span <byte> .Empty));
        }
Exemple #38
0
 public bool Verify(byte[] signature)
 {
     // no input because Write has already updated the hash
     return(SignatureAlgorithm.Verify(new byte[0], signature, HashAlgorithm));
 }
 public IssuerSignatureHeader(SignatureAlgorithm algoritm, string issuerIdentidier, string keyIdentifier)
 {
     alg = algoritm;
     iid = issuerIdentidier;
     kid = keyIdentifier;
 }