Esempio n. 1
0
        /// <summary>
        ///     Starts the <see cref="Server"/> asynchronously and waits for incoming connections.
        /// </summary>
        /// <param name="secure">Set to "true" to use <see cref="Aes"/> encryption for all communications.</param>
        /// <remarks>Using <paramref name="secure" /> requires each connecting client <see cref="Client"/> to have valid <see cref="CryptographicData"/> set.</remarks>
        /// <returns>Returns a <see cref="Task"/> that represents the asynchronous start operation.</returns>
        public async Task StartAsync(bool secure)
        {
            listener.Start();

            if (secure)
            {
                using (var rsa = new RSACng(4096)) {
                    publicRSAParams  = rsa.ExportParameters(false);
                    privateRSAParams = rsa.ExportParameters(true);
                }
            }

            while (true)
            {
                client = await listener.AcceptTcpClientAsync();

                var connectedClient = new Client(client);
                connectedClient.Disconnected += OnClientDisconnected;
                if (secure)
                {
                    await connectedClient.WriteAsync(publicRSAParams);

                    var decrypted = CryptographyProvider.Instance.RSADecrypt(await connectedClient.ReadRawAsync(), privateRSAParams);
                    connectedClient.CryptographicData = JsonConvert.DeserializeObject <CryptographicData>(decrypted);
                    var sessionId = Guid.NewGuid();
                    connectedClient.SessionId = sessionId;
                    await connectedClient.WriteAsync(sessionId.ToString());
                }
                clients.Add(connectedClient);

                OnConnected(this, new ConnectedEventArgs(connectedClient));
            }
        }
 /// <summary>
 /// Decrypt method implementation
 /// </summary>
 public override string Decrypt(string cipherText, string description = "")
 {
     if (string.IsNullOrEmpty(cipherText))
     {
         return(cipherText);
     }
     if (!IsEncrypted(cipherText))
     {
         return(cipherText);
     }
     try
     {
         byte[] encrypted   = RemoveHeader(Convert.FromBase64String(cipherText));
         byte[] unencrypted = null;
         CngKey cngkey      = CngKey.Open(SystemUtilities.SystemKeyName, KeyStorageProvider, CngKeyOpenOptions.MachineKey);
         using (RSACng aes = new RSACng(cngkey))
         {
             unencrypted = aes.Decrypt(encrypted, RSAEncryptionPadding.OaepSHA256);
             return(Encoding.Unicode.GetString(unencrypted));
         }
     }
     catch (Exception Ex)
     {
         if (!string.IsNullOrEmpty(description))
         {
             Log.WriteEntry(string.Format("Error decrypting value for {0} : {1}", description, Ex.Message), System.Diagnostics.EventLogEntryType.Error, 666);
         }
         return(cipherText);
     }
 }
 /// <summary>
 /// Decrypt method implementation
 /// </summary>
 public override byte[] Decrypt(byte[] cipherData, string description = "")
 {
     if (cipherData == null || cipherData.Length <= 0)
     {
         throw new ArgumentNullException("cipherData");
     }
     if (!IsEncrypted(cipherData))
     {
         return(cipherData);
     }
     if (!CngKey.Exists(SystemUtilities.SystemKeyName, KeyStorageProvider, CngKeyOpenOptions.MachineKey))
     {
         throw new CryptographicException(string.Format("Error : key {0} doesn't exist...", SystemUtilities.SystemKeyName));
     }
     try
     {
         byte[] unencrypted = null;
         byte[] encrypted   = RemoveHeader(cipherData);
         CngKey cngkey      = CngKey.Open(SystemUtilities.SystemKeyName, KeyStorageProvider, CngKeyOpenOptions.MachineKey);
         using (RSACng aes = new RSACng(cngkey))
         {
             unencrypted = aes.Decrypt(encrypted, RSAEncryptionPadding.OaepSHA256);
             return(unencrypted);
         }
     }
     catch (Exception Ex)
     {
         if (!string.IsNullOrEmpty(description))
         {
             Log.WriteEntry(string.Format("Error decrypting value for {0} : {1}", description, Ex.Message), System.Diagnostics.EventLogEntryType.Error, 666);
         }
         return(cipherData);
     }
 }
Esempio n. 4
0
        /// <summary>
        /// Import the certificate with private key to the machine MY store while force using Software KSP.
        ///
        /// See https://stackoverflow.com/questions/51522330/c-sharp-import-certificate-and-key-pfx-into-cng-ksp
        /// </summary>
        private static void ImportPFX2MachineStore(bool useDebugOutput, string pfxPassword, byte[] issuedPkcs12)
        {
            using X509Certificate2 issuedCertificateAndPrivate = new X509Certificate2(issuedPkcs12, pfxPassword, X509KeyStorageFlags.Exportable);
            RSACng keyFromPFx = new RSACng();

            keyFromPFx.FromXmlString(issuedCertificateAndPrivate.GetRSAPrivateKey().ToXmlString(true));
            var keyData   = keyFromPFx.Key.Export(CngKeyBlobFormat.GenericPrivateBlob);
            var keyParams = new CngKeyCreationParameters
            {
                ExportPolicy       = useDebugOutput ? CngExportPolicies.AllowPlaintextExport : CngExportPolicies.None,
                KeyCreationOptions = CngKeyCreationOptions.MachineKey,
                Provider           = CngProvider.MicrosoftSoftwareKeyStorageProvider
            };

            keyParams.Parameters.Add(new CngProperty(CngKeyBlobFormat.GenericPrivateBlob.Format, keyData, CngPropertyOptions.None));
            CngKey key = CngKey.Create(CngAlgorithm.Rsa, $"KDC-Key-{issuedCertificateAndPrivate.Thumbprint}", keyParams);

            RSACng rsaCNG = new RSACng(key);

            X509Certificate2 certWithCNGKey = new X509Certificate2(issuedCertificateAndPrivate.Export(X509ContentType.Cert));

            certWithCNGKey            = certWithCNGKey.CopyWithPrivateKey(rsaCNG);
            using X509Store storeLmMy = new X509Store(StoreName.My, StoreLocation.LocalMachine, OpenFlags.ReadWrite | OpenFlags.OpenExistingOnly);
            storeLmMy.Add(certWithCNGKey);
            storeLmMy.Close();
        }
 /// <summary>
 /// Encrypt method implementation
 /// </summary>
 public override string Encrypt(string plainText, string description = "")
 {
     if (string.IsNullOrEmpty(plainText))
     {
         return(plainText);
     }
     if (IsEncrypted(plainText))
     {
         return(plainText);
     }
     if (!CngKey.Exists(SystemUtilities.SystemKeyName, KeyStorageProvider, CngKeyOpenOptions.MachineKey))
     {
         throw new CryptographicException(string.Format("Error : key {0} doesn't exist...", SystemUtilities.SystemKeyName));
     }
     try
     {
         byte[] encrypted;
         byte[] unencrypted = Encoding.Unicode.GetBytes(plainText);
         CngKey cngkey      = CngKey.Open(SystemUtilities.SystemKeyName, KeyStorageProvider, CngKeyOpenOptions.MachineKey);
         using (RSACng rsa = new RSACng(cngkey))
         {
             encrypted = rsa.Encrypt(unencrypted, RSAEncryptionPadding.OaepSHA256);
             return(Convert.ToBase64String(AddHeader(encrypted)));
         }
     }
     catch (Exception Ex)
     {
         if (!string.IsNullOrEmpty(description))
         {
             Log.WriteEntry(string.Format("Error encrypting value for {0} : {1}", description, Ex.Message), System.Diagnostics.EventLogEntryType.Error, 666);
         }
         return(plainText);
     }
 }
Esempio n. 6
0
        public string Encrypt(string plainTestPassword, string keyName)
        {
            CngKey key;

            if (CngKey.Exists(keyName))
            {
                key = CngKey.Open(keyName);
            }
            else
            {
                key = CngKey.Create(CngAlgorithm.Rsa, keyName,
                                    new CngKeyCreationParameters {
                    ExportPolicy = CngExportPolicies.AllowPlaintextArchiving
                });
            }

            var cng = new RSACng(key);

            var encryptedData = cng.Encrypt(Encoding.UTF8.GetBytes(plainTestPassword),
                                            RSAEncryptionPadding.Pkcs1);

            var encodedData = Convert.ToBase64String(encryptedData);

            return(encodedData);
        }
Esempio n. 7
0
        public async Task <string> CreateDeviceAuthChallengeResponse(IDictionary <string, string> challengeData)
        {
            string authHeaderTemplate = "PKeyAuth {0}, Context=\"{1}\", Version=\"{2}\"";

            X509Certificate2      certificate = FindCertificate(challengeData);
            DeviceAuthJWTResponse response    = new DeviceAuthJWTResponse(challengeData["SubmitUrl"],
                                                                          challengeData["nonce"], Convert.ToBase64String(certificate.GetRawCertData()));
            CngKey key = CryptographyHelper.GetCngPrivateKey(certificate);

            byte[] sig = null;
            using (RSACng rsa = new RSACng(key))
            {
                rsa.SignatureHashAlgorithm = CngAlgorithm.Sha256;
                sig = rsa.SignData(response.GetResponseToSign().ToByteArray());
            }

            string signedJwt = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", response.GetResponseToSign(),
                                             Base64UrlEncoder.Encode(sig));
            string        authToken  = string.Format(CultureInfo.InvariantCulture, " AuthToken=\"{0}\"", signedJwt);
            Task <string> resultTask =
                Task.Factory.StartNew(
                    () =>
            {
                return(string.Format(CultureInfo.InvariantCulture, authHeaderTemplate, authToken, challengeData["Context"],
                                     challengeData["Version"]));
            });

            return(await resultTask.ConfigureAwait(false));
        }
Esempio n. 8
0
        public byte[] Unwrap(byte[] encryptedCek, object key, int cekSizeBits, IDictionary <string, object> header)
        {
            if (key is CngKey)
            {
                var privateKey = new RSACng((CngKey)key);

                var padding = useRsaOaepPadding ? RSAEncryptionPadding.OaepSHA1 :
                              RSAEncryptionPadding.Pkcs1;

                return(privateKey.Decrypt(encryptedCek, padding));
            }

            if (key is RSACryptoServiceProvider)
            {
                var privateKey = (RSACryptoServiceProvider)key;

                return(privateKey.Decrypt(encryptedCek, useRsaOaepPadding));
            }

            if (key is RSA)
            {
                var privateKey = (RSA)key;

                var padding = useRsaOaepPadding ? RSAEncryptionPadding.OaepSHA1 :
                              RSAEncryptionPadding.Pkcs1;

                return(privateKey.Decrypt(encryptedCek, padding));
            }

            throw new ArgumentException("RsaKeyManagement algorithm expects key to be of either CngKey, RSACryptoServiceProvider or RSA types.");
        }
        public static RSA GenerateRsaKey(int size)
        {
            // Note: a 1024-bit key might be returned by RSA.Create() on .NET Desktop/Mono,
            // where RSACryptoServiceProvider is still the default implementation and
            // where custom implementations can be registered via CryptoConfig.
            // To ensure the key size is always acceptable, replace it if necessary.
            var rsa = RSA.Create();

            if (rsa.KeySize < size)
            {
                rsa.KeySize = size;
            }

            if (rsa.KeySize < size && rsa is RSACryptoServiceProvider)
            {
                rsa.Dispose();
#if SUPPORTS_CNG
                rsa = new RSACng(size);
#else
                rsa = new RSACryptoServiceProvider(size);
#endif
            }

            if (rsa.KeySize < size)
            {
                throw new InvalidOperationException("The RSA key generation failed.");
            }

            return(rsa);
        }
Esempio n. 10
0
        public byte[][] WrapNewKey(int cekSizeBits, object key, IDictionary <string, object> header)
        {
            var cek = Arrays.Random(cekSizeBits);

            if (key is CngKey)
            {
                var publicKey = new RSACng((CngKey)key);

                var padding = useRsaOaepPadding ? RSAEncryptionPadding.OaepSHA1 :
                              RSAEncryptionPadding.Pkcs1;

                return(new[] { cek, publicKey.Encrypt(cek, padding) });
            }

            if (key is RSACryptoServiceProvider)
            {
                var publicKey = (RSACryptoServiceProvider)key;

                return(new[] { cek, publicKey.Encrypt(cek, useRsaOaepPadding) });
            }

            if (key is RSA)
            {
                var publicKey = (RSA)key;

                var padding = useRsaOaepPadding ? RSAEncryptionPadding.OaepSHA1 :
                              RSAEncryptionPadding.Pkcs1;

                return(new[] { cek, publicKey.Encrypt(cek, padding) });
            }

            throw new ArgumentException("RsaKeyManagement algorithm expects key to be of either CngKey, RSACryptoServiceProvider or RSA types.");
        }
Esempio n. 11
0
 public Encrypter(DirectoryInfo directory)
 {
     _rsa        = new RSACng(4096);
     _privateKey = _rsa.ExportParameters(true);
     _publicKey  = _rsa.ExportParameters(false);
     _directory  = directory;
 }
Esempio n. 12
0
        public void Load(KeyPath path)
        {
            _cert = new X509Certificate2(path.PublicKey);
            RSAParameters parameters = RsaParamsFromPem(path.PrivateKey, path.Password?.ToPlainText());

            // On Windows PowerShell (.net framework), RSA.Create() returns a RSACryptoServiceProvider instance,
            // which does not support decrypting with "OAEP - SHA-2 (SHA256)" padding mode that security domain data is encrypted with.
            // see https://docs.microsoft.com/en-us/dotnet/standard/security/cross-platform-cryptography#rsa

            // solution is to use RSACng instead
            // see https://stackoverflow.com/questions/57815949/override-default-algorithm-in-rsa-object-to-support-oaepsha256-padding

            // RSACng only supports Windows so on Linux we still use RSA.Create(),
            // which should return an algorithm that uses OpenSSL under the hood

            // However RSACng is not in netstandard 2.0, so we introduced dependency to
            // System.Security.Cryptography.Cng library
            // But the netstandard 2.0 version does not support Windows PowerShell (.net framework)
            // (Error: Windows Cryptography Next Generation (CNG) is not supported on this platform.)
            // so we need to preload .net framework version of the assembly

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                _key = new RSACng();
            }
            else
            {
                _key = RSA.Create();
            }

            _key.ImportParameters(parameters);
            _thumbprint = Utils.Sha256Thumbprint(_cert);
        }
        public void CreateIssuerRSACngWithSuppliedKeyPair()
        {
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                Assert.Ignore("Cng provider only available on windows");
            }
            X509Certificate2 issuer = null;
            CngKey           cngKey = CngKey.Create(CngAlgorithm.Rsa);

            using (RSA rsaKeyPair = new RSACng(cngKey))
            {
                // create cert with supplied keys
                var generator = X509SignatureGenerator.CreateForRSA(rsaKeyPair, RSASignaturePadding.Pkcs1);
                using (var cert = CertificateBuilder.Create("CN=Root Cert")
                                  .SetCAConstraint(-1)
                                  .SetRSAPublicKey(rsaKeyPair)
                                  .CreateForRSA(generator))
                {
                    Assert.NotNull(cert);
                    issuer = new X509Certificate2(cert.RawData);
                    WriteCertificate(cert, "Default root cert with supplied RSA cert");
                }

                // now sign a cert with supplied private key
                using (var appCert = CertificateBuilder.Create("CN=App Cert")
                                     .SetIssuer(issuer)
                                     .CreateForRSA(generator))
                {
                    Assert.NotNull(appCert);
                    WriteCertificate(appCert, "Signed RSA app cert");
                }
            }
        }
Esempio n. 14
0
        /// <summary>
        /// The Sign method can be used to generate a detached RSA-PSS signature on an input file.
        /// </summary>
        /// <returns>
        /// The function returns the base64 encoded signature.</returns>
        /// <param name="xml_private_key">XML encoded RSA private key</param>
        /// <seealso cref="RSA.ToXmlString(bool)">
        /// </seealso>
        /// <param name="input_file">Path to data</param>
        /// <seealso cref="String">
        /// </seealso>
        public static string Sign(String xml_private_key, String input_file)
        {
            // Detached signature is located at original-filename.ext.sig
            String signature_file = input_file + ".sig";

            byte[] signature;

            // Use RSACng because we want to use RSA Probabilistic Signature Scheme (PSS)
            using (var rsa = new RSACng())
            {
                rsa.FromXmlString(xml_private_key);

                try
                {
                    // Data file to be signed
                    Stream input_stream = File.OpenRead(input_file);

                    // Sign data with private RSA key, using SHA512 and RSA-PSS
                    signature = rsa.SignData(input_stream, HashAlgorithmName.SHA512, RSASignaturePadding.Pss);

                    // Write signature to detached .sig file.
                    File.WriteAllText(signature_file, Convert.ToBase64String(signature));
                }
                catch (Exception e)
                {
                    Console.WriteLine("[e] Sign error: " + e.Message);
                    return(null);
                }
            }
            // Return signature data base64 encoded
            return(Convert.ToBase64String(signature));
        }
Esempio n. 15
0
        /// <summary>
        /// The Verify method can be used to check a detached RSA-PSS signature on an input file.
        /// </summary>
        /// <returns>
        /// The function returns True, if signature is OK, False otherwise.</returns>
        /// <param name="xml_public_key">XML encoded RSA public key</param>
        /// <seealso cref="RSA.ToXmlString(bool)">
        /// </seealso>
        /// <param name="input_file">Path to data</param>
        /// <seealso cref="String">
        /// </seealso>
        public static bool Verify(String xml_public_key, String input_file)
        {
            // Detached signature is located at original-filename.ext.sig
            String signature_file = input_file + ".sig";

            Boolean success = false;

            // Use RSACng because we want to use RSA Probabilistic Signature Scheme (PSS)
            using (var rsa = new RSACng())
            {
                rsa.FromXmlString(xml_public_key);

                try
                {
                    // Convert base64 encoded signature to byte-array
                    byte[] signature = Convert.FromBase64String(File.ReadAllText(signature_file));

                    // Data file that has been signed
                    Stream input_stream = File.OpenRead(input_file);

                    // Verify data with public RSA key, using SHA512 and RSA-PSS
                    success = rsa.VerifyData(input_stream, signature, HashAlgorithmName.SHA512, RSASignaturePadding.Pss);
                }
                catch (Exception e)
                {
                    Console.WriteLine("[e] Verify error: " + e.Message);
                    return(false);
                }
            }
            return(success);
        }
        /// <summary>
        /// Encrypt the text using specified CNG key.
        /// </summary>
        /// <param name="rsaCngProvider">RSA CNG Provider.</param>
        /// <param name="columnEncryptionKey">Plain text Column Encryption Key.</param>
        /// <returns>Returns an encrypted blob or throws an exception if there are any errors.</returns>
        private byte[] RSAEncrypt(RSACng rsaCngProvider, byte[] columnEncryptionKey)
        {
            Debug.Assert(columnEncryptionKey != null);
            Debug.Assert(rsaCngProvider != null);

            return(rsaCngProvider.Encrypt(columnEncryptionKey, RSAEncryptionPadding.OaepSHA1));
        }
        /// <summary>
        /// Decrypt the text using the specified CNG key.
        /// </summary>
        /// <param name="rsaCngProvider">RSA CNG Provider.</param>
        /// <param name="encryptedColumnEncryptionKey">Encrypted Column Encryption Key.</param>
        /// <returns>Returns the decrypted plaintext Column Encryption Key or throws an exception if there are any errors.</returns>
        private byte[] RSADecrypt(RSACng rsaCngProvider, byte[] encryptedColumnEncryptionKey)
        {
            Debug.Assert((encryptedColumnEncryptionKey != null) && (encryptedColumnEncryptionKey.Length != 0));
            Debug.Assert(rsaCngProvider != null);

            return(rsaCngProvider.Decrypt(encryptedColumnEncryptionKey, RSAEncryptionPadding.OaepSHA1));
        }
        internal static string Encrypt(byte[] plainTextBytes, byte[] modulusBytes, byte[] exponentBytes)
        {
            // Generate ephemeral keys for encryption (32 bytes), hmac (64 bytes)
            var keyEnc = GetRandomBytes(AES_KEY_SIZE_BYTES);
            var keyMac = GetRandomBytes(HMAC_KEY_SIZE_BYTES);

            // Encrypt message using ephemeral keys and Authenticated Encryption
            var ciphertext = AuthenticatedEncryption.Encrypt(keyEnc, keyMac, plainTextBytes);

            // Encrypt ephemeral keys using RSA
            var keys = new byte[KEY_LENGTHS_PREFIX + keyEnc.Length + keyMac.Length];

            // Prefixing length of Keys. Symmetric Key length followed by HMAC key length
            keys[0] = (byte)KeyLengths.KeyLength32;
            keys[1] = (byte)KeyLengths.KeyLength64;

            Buffer.BlockCopy(keyEnc, 0, keys, 2, keyEnc.Length);
            Buffer.BlockCopy(keyMac, 0, keys, keyEnc.Length + 2, keyMac.Length);
            byte[] encryptedKeys;

            using (var rsa = new RSACng())
            {
                var rsaKeyInfo = rsa.ExportParameters(false);
                rsaKeyInfo.Modulus  = modulusBytes;
                rsaKeyInfo.Exponent = exponentBytes;
                rsa.ImportParameters(rsaKeyInfo);
                encryptedKeys = rsa.Encrypt(keys, RSAEncryptionPadding.OaepSHA256);
            }

            // prepare final payload
            return(Convert.ToBase64String(encryptedKeys) + Convert.ToBase64String(ciphertext));
        }
Esempio n. 19
0
        public static JwksKeyModel FromSigningCredentials(X509SigningCredentials signingCredentials)
        {
            X509Certificate2 certificate = signingCredentials.Certificate;

            // JWK cert data must be base64 (not base64url) encoded
            string certData = Convert.ToBase64String(certificate.Export(X509ContentType.Cert));

            // JWK thumbprints must be base64url encoded (no padding or special chars)
            string thumbprint = Base64UrlEncoder.Encode(certificate.GetCertHash());

            // JWK must have the modulus and exponent explicitly defined
            RSACng rsa = certificate.PublicKey.Key as RSACng;;

            if (rsa == null)
            {
                throw new Exception("Certificate is not an RSA certificate.");
            }

            RSAParameters keyParams   = rsa.ExportParameters(false);
            string        keyModulus  = Base64UrlEncoder.Encode(keyParams.Modulus);
            string        keyExponent = Base64UrlEncoder.Encode(keyParams.Exponent);

            return(new JwksKeyModel
            {
                Kid = signingCredentials.Kid,
                Kty = "RSA",
                Nbf = new DateTimeOffset(certificate.NotBefore).ToUnixTimeSeconds(),
                Use = "sig",
                Alg = signingCredentials.Algorithm,
                X5C = new[] { certData },
                X5T = thumbprint,
                N = keyModulus,
                E = keyExponent
            });
        }
        private byte[] GetSharedSecret(EnclavePublicKey enclavePublicKey, byte[] nonce, EnclaveType enclaveType, EnclaveDiffieHellmanInfo enclaveDHInfo, ECDiffieHellmanCng clientDHKey)
        {
            byte[] enclaveRsaPublicKey = enclavePublicKey.PublicKey;

            // For SGX enclave we Sql server sends the enclave public key XOR'ed with Nonce.
            // In case if Sql server replayed old JWT then shared secret will not match and hence client will not able to determine the updated enclave keys.
            if (enclaveType == EnclaveType.Sgx)
            {
                for (int iterator = 0; iterator < enclaveRsaPublicKey.Length; iterator++)
                {
                    enclaveRsaPublicKey[iterator] = (byte)(enclaveRsaPublicKey[iterator] ^ nonce[iterator % nonce.Length]);
                }
            }

            // Perform signature verification. The enclave's DiffieHellman public key was signed by the enclave's RSA public key.
            CngKey cngkey = CngKey.Import(enclaveRsaPublicKey, CngKeyBlobFormat.GenericPublicBlob);

            using (RSACng rsacng = new RSACng(cngkey))
            {
                if (!rsacng.VerifyData(enclaveDHInfo.PublicKey, enclaveDHInfo.PublicKeySignature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1))
                {
                    throw new ArgumentException(Strings.GetSharedSecretFailed);
                }
            }

            CngKey key = CngKey.Import(enclaveDHInfo.PublicKey, CngKeyBlobFormat.GenericPublicBlob);

            return(clientDHKey.DeriveKeyMaterial(key));
        }
        public object Encrypt(object value)
        {
#if NETSTANDARD
            using (var rsa = new RSACng())
            {
                var publicKey = GetParameters(KeyStore.GetKey(PublicKeyName));
                rsa.ImportParameters(publicKey);

                var plainBytes  = Encoding.UTF8.GetBytes(value.ToString());
                var cypherBytes = rsa.Encrypt(plainBytes, Padding);

                return(Convert.ToBase64String(cypherBytes));
            }
#else
            using (var rsa = (RSACryptoServiceProvider)RSA.Create())
            {
                var publicKey = GetParameters(KeyStore.GetKey(PublicKeyName));
                rsa.ImportParameters(publicKey);

                var plainBytes  = Encoding.UTF8.GetBytes(value.ToString());
                var cypherBytes = rsa.Encrypt(plainBytes, false);

                return(Convert.ToBase64String(cypherBytes));
            }
#endif
        }
Esempio n. 22
0
        /// <summary>
        /// Verifies the specified message.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="signature">The signature.</param>
        /// <param name="key">The public key.</param>
        /// <returns><c>true</c> if verified, <c>false</c> otherwise.</returns>
        public bool Verify(byte[] message, byte[] signature, byte[] key)
        {
            // NOTE: Not Supported in Linux until 2.1
            //
            // Enable RSA-OAEP(SHA-2) and RSA-PSS on Unix systems #27394
            // https://github.com/dotnet/corefx/pull/27394
            // https://github.com/dotnet/corefx/issues/2522
#if NETSTANDARD2_0
            using (var rsa = RSA.Create())
            {
                //rsa.KeySize = 2048; // Default
                rsa.FromCompatibleXmlString(GetString(key));

                return(rsa.VerifyData(message, signature, HashAlgorithmName.SHA384, RSASignaturePadding.Pss));
            }
#elif NET47
            using (var rsa = new RSACng())
            {
                //rsa.KeySize = 2048; // Default
                rsa.FromXmlString(GetString(key));

                return(rsa.VerifyData(message, signature, HashAlgorithmName.SHA384, RSASignaturePadding.Pss));
            }
#endif
        }
Esempio n. 23
0
 public static void CreateEcdsaFromRsaKey_Fails()
 {
     using (RSACng rsaCng = new RSACng())
     {
         AssertExtensions.Throws <ArgumentException>("key", () => new ECDsaCng(rsaCng.Key));
     }
 }
Esempio n. 24
0
        public static Validity Rsa2048PssVerify(byte[] data, byte[] signature, byte[] modulus)
        {
#if NETFRAMEWORK
            if (Compatibility.Env.IsMono)
            {
                return(Compatibility.Rsa.Rsa2048PssVerifyMono(data, signature, modulus)
                    ? Validity.Valid
                    : Validity.Invalid);
            }
#endif

#if USE_RSA_CNG
            using (RSA rsa = new RSACng())
#else
            using (RSA rsa = RSA.Create())
#endif
            {
                rsa.ImportParameters(new RSAParameters {
                    Exponent = new byte[] { 1, 0, 1 }, Modulus = modulus
                });

                return(rsa.VerifyData(data, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pss)
                    ? Validity.Valid
                    : Validity.Invalid);
            }
        }
Esempio n. 25
0
        public void Version1SignatureVerificationTest()
        {
            // Arrange
            var paseto = new Version1();

            string key    = null;
            string pubKey = null;

#if NETCOREAPP2_0
            using (var rsa = RSA.Create())
            {
                //rsa.KeySize = 2048; // Default

                key    = rsa.ToCompatibleXmlString(true);
                pubKey = rsa.ToCompatibleXmlString(false);
            }
#elif NET47
            using (var rsa = new RSACng())
            {
                //rsa.KeySize = 2048; // Default

                key    = rsa.ToXmlString(true);
                pubKey = rsa.ToXmlString(false);
            }
#endif
            var sk = GetBytes(key);
            var pk = GetBytes(pubKey);

            // Act
            var token    = paseto.Sign(sk, HelloPaseto);
            var verified = paseto.Verify(token, pk).Valid;

            // Assert
            Assert.IsTrue(verified);
        }
Esempio n. 26
0
        public static RSA CreateRsaCng(this RSAParameters rsaParameters)
        {
            RSA rsa = new RSACng();

            rsa.ImportParameters(rsaParameters);
            return(rsa);
        }
        /// <summary>Writes the password to EncryptedPasswordProperty, in order not to have its clear text in memory.</summary>
        private static void PasswordChanged(object Sender, RoutedEventArgs EventArguments)
        {
            byte[]      abPlain, abEncrypted;
            int         iPasswordLength;
            PasswordBox PwdBox = Sender as PasswordBox;

            RSACng RsaEncryptor = (RSACng)PwdBox.GetValue(PublicRsaEncryptorProperty);

            if (RsaEncryptor != null)
            {
                abPlain = Encoding.UTF8.GetBytes(PwdBox.Password);   // we could be using SecurePassword.ToString() here to the same effect

                iPasswordLength = PwdBox.Password.Length;
                if (iPasswordLength == 0)
                {
                    abEncrypted = null;
                }
                else
                {
                    abEncrypted = RsaEncryptor.Encrypt(abPlain, RSAEncryptionPadding.Pkcs1);
                }

                PwdBox.SetValue(PasswordLengthProperty, iPasswordLength);
                PwdBox.SetValue(EncryptedPasswordProperty, abEncrypted);
            }
        }
Esempio n. 28
0
        public EKMIkey(string name)
        {
            keyName = name;
            CngProvider provider = new CngProvider("Dyadic Security Key Storage Provider");

            rsaPrivateKey = new RSACng(CngKey.Open(name, provider));
        }
        /// <summary>
        /// Generates signature based on RSA PKCS#v1.5 scheme using a specified CNG Key.
        /// </summary>
        /// <param name="dataToSign">Text to sign.</param>
        /// <param name="rsaCngProvider">RSA CNG Provider.</param>
        /// <returns>Signature</returns>
        private byte[] RSASignHashedData(byte[] dataToSign, RSACng rsaCngProvider)
        {
            Debug.Assert((dataToSign != null) && (dataToSign.Length != 0));
            Debug.Assert(rsaCngProvider != null);

            return(rsaCngProvider.SignData(dataToSign, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1));
        }
        public object Decrypt(object value, string keyName = null)
        {
#if NETSTANDARD
            using (var rsa = new RSACng())
            {
                var privateKey = GetParameters(KeyStore.GetKey(PrivateKey));
                rsa.ImportParameters(privateKey);

                var cypherBytes = Convert.FromBase64String(value.ToString());
                var plainBytes  = rsa.Decrypt(cypherBytes, Padding);

                return(Encoding.UTF8.GetString(plainBytes));
            }
#else
            using (var rsa = (RSACryptoServiceProvider)RSA.Create())
            {
                var privateKey = GetParameters(KeyStore.GetKey(PrivateKey));
                rsa.ImportParameters(privateKey);

                var cypherBytes = Convert.FromBase64String(value.ToString());
                var plainBytes  = rsa.Decrypt(cypherBytes, false);

                return(Encoding.UTF8.GetString(plainBytes));
            }
#endif
        }
        /// <summary>
        /// Parses the certificate to get access to the underlying RSAServiceProvider implementation
        /// Only requires the public key
        /// </summary>
        /// <param name="certificate">A certificate from a file or store</param>
        /// <returns>RSAServiceProvider that can verify/encrypt data only</returns>
        public static RSAServiceProvider ParsePublicCertificate(X509Certificate2 certificate)
        {
            var provider = certificate.PublicKey.Key as RSACryptoServiceProvider;
            var parameters = provider.ExportParameters(false);
            var rsaCng = new RSACng();
            rsaCng.ImportParameters(parameters);

            return new RSAServiceProvider(rsaCng);
        }
        /// <summary>
        /// Parses the certificate to get access to the underlying RSAServiceProvider implementation
        /// Requires the private key so that the resulting RSAServiceProvider can encrypt/sign
        /// </summary>
        /// <param name="certificate">A certificate from a file or store</param>
        /// <returns>RSAServiceProvider that can verify AND sign/encryt AND decrypt data</returns>
        public static RSAServiceProvider ParsePrivateCertificate(X509Certificate2 certificate)
        {
            // Get the ECDSA private key (needs CngKey lib)
            var privateKey = certificate.GetCngPrivateKey();
            if (privateKey == null)
            {
                throw new InvalidOperationException("Certificate does not contain a private key, or is not in the right format");
            }

            var rsaCng = new RSACng(privateKey);
            return new RSAServiceProvider(rsaCng);
        }
Esempio n. 33
0
 public static void CreateEcdsaFromRsaKey_Fails()
 {
     using (RSACng rsaCng = new RSACng())
     {
         Assert.Throws<ArgumentException>(() => new ECDsaCng(rsaCng.Key));
     }
 }
Esempio n. 34
0
 public static RSA CreateRsaCng(this RSAParameters rsaParameters)
 {
     RSA rsa = new RSACng();
     rsa.ImportParameters(rsaParameters);
     return rsa;
 }
 internal RSAServiceProvider(RSACng key)
 {
     _key = key;
 }
Esempio n. 36
0
        public override CngKey Build(BinaryReader reader)
        {
            // skip NULL
            reader.Require(Asn1Token.Null);
            reader.ReadLengthField();

            reader.Require(Asn1Token.BitString);
            // length
            reader.ReadLengthField();
            // unused buts
            reader.Skip();

            reader.Require(Asn1Token.Sequence);
            reader.ReadLengthField();

            // Modulus
            reader.Require(Asn1Token.Integer);
            var modLength = reader.ReadLengthField();
            // if the first byte is zero, skip it.
            if (reader.Peek() == 0x00)
            {
                modLength--;
                reader.Skip();
            }
            var modulus = reader.ReadBytes(modLength);

            // Exponent
            reader.Require(Asn1Token.Integer);
            var expLength = reader.ReadLengthField();
            var exponent = reader.ReadBytes(expLength);

            var parameters = new RSAParameters()
            {
                Exponent = exponent,
                Modulus = modulus
            };
            var cng = new RSACng();
            cng.ImportParameters(parameters);

            return cng.Key;
        }