/// <inheritdoc />
        public ICryptoTransform CreateEncryptor(ICryptographicKey key, byte[] iv)
        {
            Requires.NotNull(key, "key");

            var ownKey = (CryptographicKey)key;
            return GetTransformForBlockMode(ownKey, iv, true);
        }
        /// <inheritdoc />
        public byte[] SignHashedData(ICryptographicKey key, byte[] data)
        {
            Requires.NotNull(key, "key");
            Requires.NotNull(data, "data");

            return ((CryptographicKey)key).SignHash(data);
        }
        public void KeyPairRoundTrip()
        {
            foreach (var algorithm in KeyAlgorithmsToTest)
            {
                Debug.WriteLine("** Algorithm: {0} **", algorithm.Key);
                var keyAlgorithm = WinRTCrypto.AsymmetricKeyAlgorithmProvider.OpenAlgorithm(algorithm.Key);
                using (ICryptographicKey key = keyAlgorithm.CreateKeyPair(algorithm.Value))
                {
                    int supportedFormats = 0;
                    foreach (CryptographicPrivateKeyBlobType format in Enum.GetValues(typeof(CryptographicPrivateKeyBlobType)))
                    {
                        try
                        {
                            byte[] keyBlob = key.Export(format);
                            using (var key2 = keyAlgorithm.ImportKeyPair(keyBlob, format))
                            {
                                byte[] key2Blob = key2.Export(format);

                                Assert.AreEqual(Convert.ToBase64String(keyBlob), Convert.ToBase64String(key2Blob));
                                Debug.WriteLine("Format {0} supported.", format);
                                Debug.WriteLine(Convert.ToBase64String(keyBlob));
                                supportedFormats++;
                            }
                        }
                        catch (NotSupportedException)
                        {
                            Debug.WriteLine("Format {0} NOT supported.", format);
                        }
                    }

                    Assert.IsTrue(supportedFormats > 0, "No supported formats.");
                }
            }
        }
    private async Task PlayAliceRoleAsync(ICryptographicKey ownSigningKey, ICryptographicKey othersSigningPublicKey, Stream channel, CancellationToken cancellationToken)
    {
        // Create ephemeral ECDH key pair, to prepare for the symmetric encryption key exchange.
        using (var ecdhKeyPair = NetFxCrypto.ECDiffieHellman.Create())
        {
            // Alice receives Bob's ECDH public key and signature.
            byte[] bobPublicDH = await ReadAsync(channel, cancellationToken);

            byte[] bobSignedDH = await ReadAsync(channel, cancellationToken);

            // Alice verifies Bob's signature to be sure it's his key.
            Assert.IsTrue(WinRTCrypto.CryptographicEngine.VerifySignature(othersSigningPublicKey, bobPublicDH, bobSignedDH));

            // Alice replies to Bob's public key by transmitting her own public key and signature.
            var ecdhPublicKey = ecdhKeyPair.PublicKey.ToByteArray();
            await WriteAsync(channel, ecdhPublicKey, cancellationToken);

            byte[] ecdhPublicKeySignature = WinRTCrypto.CryptographicEngine.Sign(ownSigningKey, ecdhPublicKey);
            await WriteAsync(channel, ecdhPublicKeySignature, cancellationToken);

            // Derive a shared secret with Bob by combining Alice's private key with Bob's public key.
            var    bobDHPK = NetFxCrypto.ECDiffieHellmanCngPublicKey.FromByteArray(bobPublicDH);
            byte[] encryptionKeyMaterial  = ecdhKeyPair.DeriveKeyMaterial(bobDHPK);
            var    symmetricEncryptionKey = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7)
                                            .CreateSymmetricKey(encryptionKeyMaterial);

            // Alice also adds a secret message.
            using (var aes = CryptoStream.WriteTo(channel, WinRTCrypto.CryptographicEngine.CreateEncryptor(symmetricEncryptionKey)))
            {
                await aes.WriteAsync(SecretMessage, 0, SecretMessage.Length, cancellationToken);
            }

            channel.Dispose();
        }
    }
        /// <inheritdoc />
        public byte[] SignHashedData(ICryptographicKey key, byte[] data)
        {
            Requires.NotNull(key, "key");
            Requires.NotNull(data, "data");

            return(((CryptographicKey)key).SignHash(data));
        }
        /// <summary>
        /// Extracts the platform-specific key from the PCL version.
        /// </summary>
        /// <param name="key">The PCL key.</param>
        /// <returns>The platform-specific key.</returns>
        private static Platform.Core.CryptographicKey ExtractPlatformKey(ICryptographicKey key)
        {
            Requires.NotNull(key, "key");
            var platformKey = ((CryptographicKey)key).Key;

            return(platformKey);
        }
        /// <inheritdoc />
        public byte[] DeriveKeyMaterial(ICryptographicKey key, IKeyDerivationParameters parameters, int desiredKeySize)
        {
            var platformKey        = ((CryptographicKey)key).Key;
            var platformParameters = ((KeyDerivationParameters)parameters).Parameters;

            return(Platform.Core.CryptographicEngine.DeriveKeyMaterial(platformKey, platformParameters, (uint)desiredKeySize).ToArray());
        }
Exemple #8
0
    public void VerifySignatureWithHashInput_NullData(ICryptographicKey key)
    {
        var signature = new byte[23];

        Assert.Throws <ArgumentNullException>(
            () => WinRTCrypto.CryptographicEngine.VerifySignatureWithHashInput(key, null, signature));
    }
        /// <inheritdoc />
        public byte[] Encrypt(ICryptographicKey key, byte[] data, byte[] iv)
        {
            Requires.NotNull(key, "key");
            Requires.NotNull(data, "data");

            var keyClass = (CryptographicKey)key;

            if (keyClass.SymmetricAlgorithmProvider != null)
            {
                bool paddingInUse = keyClass.SymmetricAlgorithmProvider.Algorithm.GetPadding() != SymmetricAlgorithmPadding.None;
                Requires.Argument(paddingInUse || this.IsValidInputSize(keyClass, data.Length), "data", "Length does not a multiple of block size and no padding is selected.");
            }

            try
            {
                return(Platform.Core.CryptographicEngine.Encrypt(
                           keyClass.Key,
                           data.ToBuffer(),
                           iv.ToBuffer()).ToArray());
            }
            catch (NotImplementedException ex)
            {
                throw new NotSupportedException(ex.Message, ex);
            }
        }
        public static string DecryptAes(byte[] data, byte[] key, byte[] rgbKey, byte[] rgbIV)
        {
            ISymmetricKeyAlgorithmProvider aes = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbc);
            ICryptographicKey symetricKey      = aes.CreateSymmetricKey(rgbKey);

            string returnValue = "";

            using (var ms = new MemoryStream(data))
            {
                // Read the first 16 bytes which is the IV.
                byte[] iv = new byte[16];
                ms.Read(iv, 0, 16);
                using (var decryptor = WinRTCrypto.CryptographicEngine.CreateDecryptor(symetricKey, iv))
                {
                    using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                    {
                        using (var sr = new StreamReader(cs))
                        {
                            returnValue = sr.ReadToEnd();
                        }
                    }
                }
            }
            return(returnValue);
        }
        /// <inheritdoc />
        public ICryptoTransform CreateDecryptor(ICryptographicKey key, byte[] iv)
        {
            Requires.NotNull(key, "key");

            var keyClass = (CryptographicKey)key;
            return keyClass.CreateDecryptor(iv);
        }
    public void PrivateKeyDataComputation()
    {
        var    algorithmName = AsymmetricAlgorithm.RsaOaepSha1;
        string base64BCrypt  = Helper.PrivateKeyFormatsAndBlobs[Tuple.Create(algorithmName, CryptographicPrivateKeyBlobType.BCryptPrivateKey)];
        string base64Pkcs1   = Helper.PrivateKeyFormatsAndBlobs[Tuple.Create(algorithmName, CryptographicPrivateKeyBlobType.Pkcs1RsaPrivateKey)];

        var algorithm = WinRTCrypto.AsymmetricKeyAlgorithmProvider.OpenAlgorithm(algorithmName);
        ICryptographicKey bcryptKey = algorithm.ImportKeyPair(Convert.FromBase64String(base64BCrypt), CryptographicPrivateKeyBlobType.BCryptPrivateKey);
        ICryptographicKey pkcs1Key  = algorithm.ImportKeyPair(Convert.FromBase64String(base64Pkcs1), CryptographicPrivateKeyBlobType.Pkcs1RsaPrivateKey);

        var bcryptParameters = bcryptKey.ExportParameters(true);
        var pkcs1Parameters  = pkcs1Key.ExportParameters(true);

        this.logger.WriteLine("PKCS1  P: {0}", WinRTCrypto.CryptographicBuffer.EncodeToHexString(pkcs1Parameters.P));
        this.logger.WriteLine("BCrypt P: {0}", WinRTCrypto.CryptographicBuffer.EncodeToHexString(bcryptParameters.P));
        this.logger.WriteLine("PKCS1  Q: {0}", WinRTCrypto.CryptographicBuffer.EncodeToHexString(pkcs1Parameters.Q));
        this.logger.WriteLine("BCrypt Q: {0}", WinRTCrypto.CryptographicBuffer.EncodeToHexString(bcryptParameters.Q));
        this.logger.WriteLine("PKCS1  D: {0}", WinRTCrypto.CryptographicBuffer.EncodeToHexString(pkcs1Parameters.D));
        this.logger.WriteLine("BCrypt D: {0}", WinRTCrypto.CryptographicBuffer.EncodeToHexString(bcryptParameters.D));
        this.logger.WriteLine("PKCS1  DP: {0}", WinRTCrypto.CryptographicBuffer.EncodeToHexString(pkcs1Parameters.DP));
        this.logger.WriteLine("BCrypt DP: {0}", WinRTCrypto.CryptographicBuffer.EncodeToHexString(bcryptParameters.DP));
        this.logger.WriteLine("PKCS1  DQ: {0}", WinRTCrypto.CryptographicBuffer.EncodeToHexString(pkcs1Parameters.DQ));
        this.logger.WriteLine("BCrypt DQ: {0}", WinRTCrypto.CryptographicBuffer.EncodeToHexString(bcryptParameters.DQ));
        this.logger.WriteLine("PKCS1  InverseQ: {0}", WinRTCrypto.CryptographicBuffer.EncodeToHexString(pkcs1Parameters.InverseQ));
        this.logger.WriteLine("BCrypt InverseQ: {0}", WinRTCrypto.CryptographicBuffer.EncodeToHexString(bcryptParameters.InverseQ));

        Assert.Equal <byte>(pkcs1Parameters.P, bcryptParameters.P);
        Assert.Equal <byte>(pkcs1Parameters.Q, bcryptParameters.Q);
        ////Assert.Equal<byte>(pkcs1Parameters.D, bcryptParameters.D); // not equal when computed ourselves, but equivalent
        Assert.Equal <byte>(pkcs1Parameters.DP, bcryptParameters.DP);
        Assert.Equal <byte>(pkcs1Parameters.DQ, bcryptParameters.DQ);
        Assert.Equal <byte>(pkcs1Parameters.InverseQ, bcryptParameters.InverseQ);
    }
    public void CreateKey()
    {
        foreach (var algorithmAndExpectedResult in this.stretchedKeyBase64)
        {
            this.logger.WriteLine("Testing algorithm: {0}", algorithmAndExpectedResult.Key);
            var algorithm         = WinRTCrypto.KeyDerivationAlgorithmProvider.OpenAlgorithm(algorithmAndExpectedResult.Key);
            ICryptographicKey key = algorithm.CreateKey(this.originalKey);
            Assert.NotNull(key);
            Assert.Equal(this.originalKey.Length * 8, key.KeySize);

            IKeyDerivationParameters parameters = WinRTCrypto.KeyDerivationParameters.BuildForPbkdf2(this.salt, this.iterations);
            Assert.Equal(this.iterations, parameters.IterationCount);
            CollectionAssertEx.AreEqual(this.salt, parameters.KdfGenericBinary);

            try
            {
                byte[] keyMaterial = WinRTCrypto.CryptographicEngine.DeriveKeyMaterial(key, parameters, 20);
                Assert.Equal(algorithmAndExpectedResult.Value, Convert.ToBase64String(keyMaterial));
            }
            catch (NotSupportedException)
            {
                this.logger.WriteLine(" - Not supported on this platform");
            }
        }
    }
Exemple #14
0
        private const AsymmetricAlgorithm RsaType = AsymmetricAlgorithm.RsaPkcs1; //or OeapSha1 and OaepSha256

        public void GenerateKeys()
        {
            ICryptographicKey key = GetAsymmetricKeyAlgorithm().CreateKeyPair(RsaKeySize);

            PrivateKey = key.Export(CryptographicPrivateKeyBlobType.Pkcs1RsaPrivateKey);
            PublicKey  = key.ExportPublicKey(CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey);
        }
Exemple #15
0
        /// <inheritdoc />
        public byte[] Sign(ICryptographicKey key, byte[] data)
        {
            Requires.NotNull(key, nameof(key));
            Requires.NotNull(data, nameof(data));

            return(((CryptographicKey)key).Sign(data));
        }
        public static string Encrypt(string originalPayload, byte[] privateKey)
        {
            string encryptedPayload = "";

            ISymmetricKeyAlgorithmProvider aes = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
            ICryptographicKey symetricKey      = aes.CreateSymmetricKey(privateKey);
            var iv = WinRTCrypto.CryptographicBuffer.GenerateRandom(aes.BlockLength);

            var input = Encoding.UTF8.GetBytes(originalPayload);

            using (var encrypter = WinRTCrypto.CryptographicEngine.CreateEncryptor(symetricKey, iv))
            {
                using (var cipherStream = new MemoryStream())
                {
                    using (var tCryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write))
                        using (var tBinaryWriter = new BinaryWriter(tCryptoStream))
                        {
                            //Prepend IV to data
                            cipherStream.Write(iv, 0, iv.Length); //Write iv to the plain stream (not tested though)
                            tBinaryWriter.Write(input);
                            tCryptoStream.FlushFinalBlock();
                        }

                    encryptedPayload = Convert.ToBase64String(cipherStream.ToArray());
                }
            }

            return(encryptedPayload);
        }
Exemple #17
0
        public async Task <string> Encrypt(string dataToBeEncrypted, ICryptographicKey key)
        {
            var plain           = Encoding.UTF8.GetBytes(dataToBeEncrypted);
            var encrypted       = WinRTCrypto.CryptographicEngine.Encrypt(key, plain);
            var encryptedString = Convert.ToBase64String(encrypted);

            return(await Task.FromResult(encryptedString));
        }
Exemple #18
0
        public async Task <string> Decrypt(string dataToBeDecrypted, ICryptographicKey key)
        {
            var encrypted       = Convert.FromBase64String(dataToBeDecrypted);
            var decrypted       = WinRTCrypto.CryptographicEngine.Decrypt(key, encrypted);
            var decryptedString = Encoding.UTF8.GetString(decrypted, 0, decrypted.Length);

            return(await Task.FromResult(decryptedString));
        }
        /// <inheritdoc />
        public bool VerifySignatureWithHashInput(ICryptographicKey key, byte[] data, byte[] signature)
        {
            Requires.NotNull(key, "key");
            Requires.NotNull(data, "data");
            Requires.NotNull(signature, "paramName");

            return ((CryptographicKey)key).VerifyHash(data, signature);
        }
Exemple #20
0
        /// <inheritdoc />
        public bool VerifySignatureWithHashInput(ICryptographicKey key, byte[] data, byte[] signature)
        {
            Requires.NotNull(key, nameof(key));
            Requires.NotNull(data, nameof(data));
            Requires.NotNull(signature, nameof(signature));

            return(((CryptographicKey)key).VerifyHash(data, signature));
        }
Exemple #21
0
    public void Sign_VerifySignatureWithHashInput(ICryptographicKey key, HashAlgorithm hashAlgorithm)
    {
        byte[] hash = WinRTCrypto.HashAlgorithmProvider.OpenAlgorithm(hashAlgorithm)
                      .HashData(this.data);
        byte[] signature = WinRTCrypto.CryptographicEngine.Sign(key, this.data);

        Assert.True(WinRTCrypto.CryptographicEngine.VerifySignatureWithHashInput(key, hash, signature));
    }
        /// <inheritdoc />
        public bool VerifySignatureWithHashInput(ICryptographicKey key, byte[] data, byte[] signature)
        {
            Requires.NotNull(key, "key");
            Requires.NotNull(data, "data");
            Requires.NotNull(signature, "paramName");

            return(((CryptographicKey)key).VerifyHash(data, signature));
        }
        /// <inheritdoc />
        public ICryptoTransform CreateDecryptor(ICryptographicKey key, byte[] iv)
        {
            Requires.NotNull(key, "key");

            var ownKey = (CryptographicKey)key;

            return(GetTransformForBlockMode(ownKey, iv, false));
        }
        /// <inheritdoc />
        public ICryptoTransform CreateDecryptor(ICryptographicKey key, byte[] iv)
        {
            Requires.NotNull(key, "key");

            var keyClass = (CryptographicKey)key;

            return(keyClass.CreateDecryptor(iv));
        }
        /// <inheritdoc />
        public bool VerifySignature(ICryptographicKey key, byte[] data, byte[] signature)
        {
            Requires.NotNull(key, "key");
            Requires.NotNull(data, "data");
            Requires.NotNull(signature, "signature");

            return ((CryptographicKey)key).VerifySignature(data, signature);
        }
        public static bool Verify(byte[] key, byte[] message, byte[] signature)
        {
            IMacAlgorithmProvider provider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithm.HmacSha256);

            ICryptographicKey hmacKey = provider.CreateKey(key);

            return(CryptographicEngine.VerifySignature(hmacKey, message, signature));
        }
        public static byte[] sha256sum(byte[] key, byte[] message)
        {
            IMacAlgorithmProvider provider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithm.HmacSha256);
            ICryptographicKey     hmacKey  = provider.CreateKey(key);

            byte [] hmac = CryptographicEngine.Sign(hmacKey, message);
            return(hmac);
        }
        /// <summary>
        /// Computes PKCS5 for the message
        /// </summary>
        /// <param name="message">plaintext</param>
        /// <returns>PKCS5 of the message</returns>
        public static byte[] aesCbcPkcs5(byte[] message, byte[] key, byte[] iv)
        {
            ISymmetricKeyAlgorithmProvider objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7); // PKCS5
            ICryptographicKey ckey = objAlg.CreateSymmetricKey(key);

            byte [] result = CryptographicEngine.Encrypt(ckey, message, iv);
            return(result);
        }
        /// <inheritdoc />
        public byte[] Decrypt(ICryptographicKey key, byte[] data, byte[] iv)
        {
            Requires.NotNull(key, "key");
            Requires.NotNull(data, "data");

            var keyClass = (CryptographicKey)key;
            return keyClass.Decrypt(data, iv);
        }
Exemple #30
0
    public void CreateSymmetricKey_ExportPublicKey()
    {
        var provider          = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
        ICryptographicKey key = provider.CreateSymmetricKey(this.keyMaterial);

        Assert.Throws <NotSupportedException>(
            () => key.ExportPublicKey());
    }
Exemple #31
0
    private void CreateSymmetricKeyHelper(SymmetricAlgorithm algorithm)
    {
        var provider          = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(algorithm);
        ICryptographicKey key = provider.CreateSymmetricKey(this.keyMaterial);

        Assert.NotNull(key);
        Assert.Equal(this.keyMaterial.Length * 8, key.KeySize);
    }
        /// <inheritdoc />
        public bool VerifySignature(ICryptographicKey key, byte[] data, byte[] signature)
        {
            Requires.NotNull(key, "key");
            Requires.NotNull(data, "data");
            Requires.NotNull(signature, "signature");

            return(((CryptographicKey)key).VerifySignature(data, signature));
        }
Exemple #33
0
        /// <inheritdoc />
        public ICryptoTransform CreateEncryptor(ICryptographicKey key, byte[]?iv)
        {
            Requires.NotNull(key, nameof(key));

            var keyClass = (CryptographicKey)key;

            return(keyClass.CreateEncryptor(iv));
        }
        /// <inheritdoc />
        public byte[] Sign(ICryptographicKey key, byte[] data)
        {
            Requires.NotNull(key, "key");
            Requires.NotNull(data, "data");

            return(Platform.Core.CryptographicEngine.Sign(
                       ExtractPlatformKey(key),
                       data.ToBuffer()).ToArray());
        }
Exemple #35
0
            internal static string Decrypt(byte[] encryptedText) //Seridonio,2016
            {
                ISymmetricKeyAlgorithmProvider aesCrypto = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
                ICryptographicKey symmtricKey            = aesCrypto.CreateSymmetricKey(_derivedKey);
                ICryptoTransform  decryptor = WinRTCrypto.CryptographicEngine.CreateDecryptor(symmtricKey);

                byte[] decryptedText = decryptor.TransformFinalBlock(encryptedText, 0, encryptedText.Length);
                return(Encoding.UTF8.GetString(decryptedText, 0, decryptedText.Length));
            }
Exemple #36
0
 public void SignHashedData_VerifySignatureWithHashInput(ICryptographicKey key, HashAlgorithm hashAlgorithm)
 {
     byte[] hash = WinRTCrypto.HashAlgorithmProvider.OpenAlgorithm(hashAlgorithm)
                   .HashData(this.data);
     byte[] signature = WinRTCrypto.CryptographicEngine.SignHashedData(key, hash);
     Assert.True(WinRTCrypto.CryptographicEngine.VerifySignatureWithHashInput(key, hash, signature));
     Assert.False(WinRTCrypto.CryptographicEngine.VerifySignatureWithHashInput(key, hash, PclTestUtilities.Tamper(signature)));
     Assert.False(WinRTCrypto.CryptographicEngine.VerifySignatureWithHashInput(key, PclTestUtilities.Tamper(this.data), signature));
 }
 static CryptographicEngineAsymmetricTests()
 {
     try
     {
         EcdsaSigningKey = WinRTCrypto.AsymmetricKeyAlgorithmProvider
             .OpenAlgorithm(AsymmetricAlgorithm.EcdsaP256Sha256)
             .CreateKeyPair(256);
     }
     catch (NotSupportedException)
     {
         // ECDSA is not supported on this platform.
     }
 }
 public CryptographicEngineTests(ITestOutputHelper logger)
 {
     this.logger = logger;
     try
     {
         this.aesKeyZerosPadding = WinRTCrypto.SymmetricKeyAlgorithmProvider
             .OpenAlgorithm(SymmetricAlgorithmName.Aes, SymmetricAlgorithmMode.Cbc, SymmetricAlgorithmPadding.Zeros)
             .CreateSymmetricKey(Convert.FromBase64String(AesKeyMaterial));
     }
     catch (NotSupportedException)
     {
     }
 }
        /// <inheritdoc />
        public byte[] Decrypt(ICryptographicKey key, byte[] data, byte[] iv)
        {
            Requires.NotNull(key, "key");
            Requires.NotNull(data, "data");

            var keyClass = (CryptographicKey)key;
            if (keyClass.SymmetricAlgorithmProvider != null)
            {
                Requires.Argument(this.IsValidInputSize(keyClass, data.Length), "data", "Length does not a multiple of block size and no padding is selected.");
            }

            return Platform.Core.CryptographicEngine.Decrypt(
                keyClass.Key,
                data.ToBuffer(),
                iv.ToBuffer()).ToArray();
        }
Exemple #40
0
        public Rsa(byte[] key, bool intermediateConvertToBase64BeforeEncryption = false, bool isPrivateKey = false)
		{                      
            try
            {                                     
                var rsa = WinRTCrypto.AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithm.RsaPkcs1);
                IntermediateConvertToBase64BeforeEncryption = intermediateConvertToBase64BeforeEncryption;
                CanDecrypt = isPrivateKey;

               
                if (isPrivateKey)
                {
                   _key = rsa.ImportKeyPair(key);
                }
                else
                {
                    _key = rsa.ImportPublicKey(key);
                }
            }
            catch (Exception ex)
            {
                string exception = ex.Message;
            }           
		}
        /// <inheritdoc />
        public byte[] Encrypt(ICryptographicKey key, byte[] data, byte[] iv)
        {
            Requires.NotNull(key, "key");
            Requires.NotNull(data, "data");

            var keyClass = (CryptographicKey)key;
            if (keyClass.SymmetricAlgorithmProvider != null)
            {
                bool paddingInUse = keyClass.SymmetricAlgorithmProvider.Algorithm.GetPadding() != SymmetricAlgorithmPadding.None;
                Requires.Argument(paddingInUse || this.IsValidInputSize(keyClass, data.Length), "data", "Length does not a multiple of block size and no padding is selected.");
            }

            try
            {
                return Platform.Core.CryptographicEngine.Encrypt(
                    keyClass.Key,
                    data.ToBuffer(),
                    iv.ToBuffer()).ToArray();
            }
            catch (NotImplementedException ex)
            {
                throw new NotSupportedException(ex.Message, ex);
            }
        }
Exemple #42
0
        /// <summary>
        /// Initializes a new instance of the <see cref="OwnEndpoint" /> class.
        /// </summary>
        /// <param name="signingKey">The signing key.</param>
        /// <param name="encryptionKey">The encryption key.</param>
        /// <param name="inboxOwnerCode">The secret that proves ownership of the inbox at the <see cref="Endpoint.MessageReceivingEndpoint" />.</param>
        public OwnEndpoint(ICryptographicKey signingKey, ICryptographicKey encryptionKey, string inboxOwnerCode = null)
            : this()
        {
            Requires.NotNull(signingKey, "signingKey");
            Requires.NotNull(encryptionKey, "encryptionKey");

            this.PublicEndpoint = new Endpoint
            {
                SigningKeyPublicMaterial = signingKey.ExportPublicKey(CryptoSettings.PublicKeyFormat),
                EncryptionKeyPublicMaterial = encryptionKey.ExportPublicKey(CryptoSettings.PublicKeyFormat),
            };

            // We could preserve the key instances, but that could make
            // our behavior a little less repeatable if we had problems
            // with key serialization.
            ////this.signingKey = signingKey;
            ////this.encryptionKey = encryptionKey;

            // Since this is a new endpoint we can choose a more modern format for the private keys.
            this.PrivateKeyFormat = CryptographicPrivateKeyBlobType.Pkcs8RawPrivateKeyInfo;
            this.SigningKeyPrivateMaterial = signingKey.Export(this.PrivateKeyFormat);
            this.EncryptionKeyPrivateMaterial = encryptionKey.Export(this.PrivateKeyFormat);
            this.InboxOwnerCode = inboxOwnerCode;
        }
        /// <inheritdoc />
        public byte[] SignHashedData(ICryptographicKey key, byte[] data)
        {
            Requires.NotNull(key, "key");
            Requires.NotNull(data, "data");

            var keyClass = (CryptographicKey)key;
            return Platform.Core.CryptographicEngine.SignHashedData(
                keyClass.Key,
                data.ToBuffer()).ToArray();
        }
        /// <inheritdoc />
        public bool VerifySignature(ICryptographicKey key, byte[] data, byte[] signature)
        {
            Requires.NotNull(key, "key");
            Requires.NotNull(data, "data");
            Requires.NotNull(signature, "signature");

            return Platform.Core.CryptographicEngine.VerifySignature(
                ExtractPlatformKey(key),
                data.ToBuffer(),
                signature.ToBuffer());
        }
 /// <inheritdoc />
 public byte[] DeriveKeyMaterial(ICryptographicKey key, IKeyDerivationParameters parameters, int desiredKeySize)
 {
     // Right now we're assuming that KdfGenericBinary is directly usable as a salt
     // in RFC2898. When our KeyDerivationParametersFactory class supports
     // more parameter types than just BuildForPbkdf2, we might need to adjust this code
     // to handle each type of parameter.
     var keyDerivation = (KeyDerivationCryptographicKey)key;
     byte[] salt = parameters.KdfGenericBinary;
     switch (keyDerivation.Algorithm)
     {
         case KeyDerivationAlgorithm.Pbkdf2Sha1:
             var deriveBytes = new Platform.Rfc2898DeriveBytes(keyDerivation.Key, salt, parameters.IterationCount);
             return deriveBytes.GetBytes(desiredKeySize);
         default:
             // TODO: consider using Platform.PasswordDeriveBytes if it can
             // support some more of these algorithms.
             throw new NotSupportedException("Only KeyDerivationAlgorithm.Pbkdf2Sha1 is supported for this platform.");
     }
 }
        /// <inheritdoc />
        public byte[] Sign(ICryptographicKey key, byte[] data)
        {
            Requires.NotNull(key, "key");
            Requires.NotNull(data, "data");

            return Platform.Core.CryptographicEngine.Sign(
                ExtractPlatformKey(key),
                data.ToBuffer()).ToArray();
        }
Exemple #47
0
        public App()
        {
            // create the key we are going to use
            var asym = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithm.RsaPkcs1);
            var hash = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithm.Sha1);

            // The root page of your application
            MainPage = new ContentPage
            {
                Content = new StackLayout
                {
                    VerticalOptions = LayoutOptions.Center,
                    Children = {
                        // create a key
                        (createKeyButton = new Button {
                            Text = "Create Key",
                            Command = new Command(() => {
                                key = asym.CreateKeyPair(512);
                                var publicKey = key.ExportPublicKey();
                                var publicKeyString = Convert.ToBase64String(publicKey);
                                
                                publicKeyLabel.Text = publicKeyString;
                            })
                        }),
                        (publicKeyLabel = new Label {
                            Text = "..."
                        }),
                        // enter plain text
                        (valueText = new Entry {
                            Text = "Hello World!"
                        }),
                        // start encryption
                        (encryptButton = new Button {
                            Text = "Encrypt",
                            Command = new Command(() => {
                                try {
                                    var plainString = valueText.Text;
                                    var plain = Encoding.UTF8.GetBytes(plainString);
                                    var encrypted = CryptographicEngine.Encrypt(key, plain);
                                    var encryptedString = Convert.ToBase64String(encrypted);

                                    encryptLabel.Text = encryptedString;
                                } catch (Exception ex) {
                                    encryptLabel.Text = "Error encrypting: " + ex.Message;
                                }
                            })
                        }),
                        (encryptLabel = new Label {
                            Text = "..."
                        }),
                        // and now decrypt
                        (decryptButton = new Button {
                            Text = "Decrypt",
                            Command = new Command(() => {
                                try {
                                    var encryptedString = encryptLabel.Text;
                                    var encrypted = Convert.FromBase64String(encryptedString);
                                    var decrypted = CryptographicEngine.Decrypt(key, encrypted);
                                    var decryptedString = Encoding.UTF8.GetString(decrypted, 0, decrypted.Length);

                                    decryptLabel.Text = decryptedString;
                                } catch (Exception ex) {
                                    decryptLabel.Text = "Error decrypting: " + ex.Message;
                                }
                            })
                        }),
                        (decryptLabel = new Label {
                            Text = "..."
                        }),
                        // and hash
                        (hashButton = new Button {
                            Text = "hash",
                            Command = new Command(() => {
                                try {
                                    var plainString = valueText.Text;
                                    var plain = Encoding.UTF8.GetBytes(plainString);
                                    var hashed = hash.HashData(plain);
                                    var hashedString = Convert.ToBase64String(hashed);

                                    hashLabel.Text = hashedString;
                                } catch (Exception ex) {
                                    hashLabel.Text = "Error hashing: " + ex.Message;
                                }
                            })
                        }),
                        (hashLabel = new Label {
                            Text = "..."
                        })
                    }
                }
            };

            // set initial data
            createKeyButton.Command.Execute(null);
            encryptButton.Command.Execute(null);
            decryptButton.Command.Execute(null);
            hashButton.Command.Execute(null);
        }
 /// <summary>
 /// Extracts the platform-specific key from the PCL version.
 /// </summary>
 /// <param name="key">The PCL key.</param>
 /// <returns>The platform-specific key.</returns>
 private static Platform.Core.CryptographicKey ExtractPlatformKey(ICryptographicKey key)
 {
     Requires.NotNull(key, "key");
     var platformKey = ((CryptographicKey)key).Key;
     return platformKey;
 }
 public void SignHashedData_NullHash(ICryptographicKey key)
 {
     Assert.Throws<ArgumentNullException>(
         () => WinRTCrypto.CryptographicEngine.SignHashedData(key, null));
 }
 public void SignAndVerifySignature(ICryptographicKey key)
 {
     try
     {
         byte[] signature = WinRTCrypto.CryptographicEngine.Sign(key, this.data);
         Assert.True(WinRTCrypto.CryptographicEngine.VerifySignature(key, this.data, signature));
         Assert.False(WinRTCrypto.CryptographicEngine.VerifySignature(key, PclTestUtilities.Tamper(this.data), signature));
         Assert.False(WinRTCrypto.CryptographicEngine.VerifySignature(key, this.data, PclTestUtilities.Tamper(signature)));
     }
     catch (NotSupportedException)
     {
         this.logger.WriteLine("Not supported by the platform.");
     }
 }
 public void VerifySignature_NullData(ICryptographicKey key)
 {
     Assert.Throws<ArgumentNullException>(
         () => WinRTCrypto.CryptographicEngine.VerifySignature(key, null, new byte[2]));
 }
 public void VerifySignatureWithHashInput_NullSignature(ICryptographicKey key)
 {
     Assert.Throws<ArgumentNullException>(
         () => WinRTCrypto.CryptographicEngine.VerifySignatureWithHashInput(key, this.data, null));
 }
    private async Task PlayAliceRoleAsync(ICryptographicKey ownSigningKey, ICryptographicKey othersSigningPublicKey, Stream channel, CancellationToken cancellationToken)
    {
        // Create ephemeral ECDH key pair, to prepare for the symmetric encryption key exchange.
        using (var ecdhKeyPair = NetFxCrypto.ECDiffieHellman.Create())
        {
            // Alice receives Bob's ECDH public key and signature.
            byte[] bobPublicDH = await ReadAsync(channel, cancellationToken);
            byte[] bobSignedDH = await ReadAsync(channel, cancellationToken);

            // Alice verifies Bob's signature to be sure it's his key.
            Assert.True(WinRTCrypto.CryptographicEngine.VerifySignature(othersSigningPublicKey, bobPublicDH, bobSignedDH));

            // Alice replies to Bob's public key by transmitting her own public key and signature.
            var ecdhPublicKey = ecdhKeyPair.PublicKey.ToByteArray();
            await WriteAsync(channel, ecdhPublicKey, cancellationToken);
            byte[] ecdhPublicKeySignature = WinRTCrypto.CryptographicEngine.Sign(ownSigningKey, ecdhPublicKey);
            await WriteAsync(channel, ecdhPublicKeySignature, cancellationToken);

            // Derive a shared secret with Bob by combining Alice's private key with Bob's public key.
            var bobDHPK = NetFxCrypto.ECDiffieHellmanCngPublicKey.FromByteArray(bobPublicDH);
            byte[] encryptionKeyMaterial = ecdhKeyPair.DeriveKeyMaterial(bobDHPK);
            var symmetricEncryptionKey = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7)
                .CreateSymmetricKey(encryptionKeyMaterial);

            // Alice also adds a secret message.
            using (var aes = CryptoStream.WriteTo(channel, WinRTCrypto.CryptographicEngine.CreateEncryptor(symmetricEncryptionKey)))
            {
                await aes.WriteAsync(SecretMessage, 0, SecretMessage.Length, cancellationToken);
            }

            channel.Dispose();
        }
    }
    private async Task PlayBobRoleAsync(ICryptographicKey ownSigningKey, ICryptographicKey othersSigningPublicKey, Stream channel, CancellationToken cancellationToken)
    {
        // Create ephemeral ECDH key pair, to prepare for the symmetric encryption key exchange.
        using (var ecdhKeyPair = NetFxCrypto.ECDiffieHellman.Create())
        {
            // Send the ephemeral ECDH public key to Alice.
            var ecdhPublicKey = ecdhKeyPair.PublicKey.ToByteArray();
            await WriteAsync(channel, ecdhPublicKey, cancellationToken);

            // Authenticate to Alice that this is really Bob's ephemeral public key.
            byte[] ecdhPublicKeySignature = WinRTCrypto.CryptographicEngine.Sign(ownSigningKey, ecdhPublicKey);
            await WriteAsync(channel, ecdhPublicKeySignature, cancellationToken);

            // Read Alice's reply. It consists of her own ephemeral public key and signature.
            byte[] alicePublicDH = await ReadAsync(channel, cancellationToken);
            byte[] aliceSignedDH = await ReadAsync(channel, cancellationToken);

            // Authenticate Alice's public key.
            Assert.True(WinRTCrypto.CryptographicEngine.VerifySignature(othersSigningPublicKey, alicePublicDH, aliceSignedDH));

            // Deserialize Alice's public key and derive the shared secret from it.
            var aliceDHPK = NetFxCrypto.ECDiffieHellmanCngPublicKey.FromByteArray(alicePublicDH);
            byte[] encryptionKeyMaterial = ecdhKeyPair.DeriveKeyMaterial(aliceDHPK);
            var encryptionKey = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7)
                .CreateSymmetricKey(encryptionKeyMaterial);

            // Bob reads Alice's secret message using the shared secret that both parties derived,
            // but never transmitted.
            using (var aes = CryptoStream.ReadFrom(channel, WinRTCrypto.CryptographicEngine.CreateDecryptor(encryptionKey)))
            {
                byte[] plaintext = await ReadAsync(aes, cancellationToken);

                // Assert that the plaintext is as it was expected to be.
                CollectionAssertEx.AreEqual(SecretMessage, plaintext);
            }

            channel.Dispose();
        }
    }
 /// <inheritdoc />
 public byte[] DeriveKeyMaterial(ICryptographicKey key, IKeyDerivationParameters parameters, int desiredKeySize)
 {
     return ((CryptographicKey)key).DeriveKeyMaterial(parameters, desiredKeySize);
 }
    public void Sign_VerifySignatureWithHashInput(ICryptographicKey key, HashAlgorithm hashAlgorithm)
    {
        try
        {
            byte[] hash = WinRTCrypto.HashAlgorithmProvider.OpenAlgorithm(hashAlgorithm)
                .HashData(this.data);
            byte[] signature = WinRTCrypto.CryptographicEngine.Sign(key, this.data);

            Assert.True(WinRTCrypto.CryptographicEngine.VerifySignatureWithHashInput(key, hash, signature));
        }
        catch (NotSupportedException)
        {
            // Not all platforms support this.
            this.logger.WriteLine("Skipped test for unsupported functionality on this platform.");
        }
    }
        /// <inheritdoc />
        public bool VerifySignatureWithHashInput(ICryptographicKey key, byte[] data, byte[] signature)
        {
            Requires.NotNull(key, "key");
            Requires.NotNull(data, "data");
            Requires.NotNull(signature, "signature");

            var keyClass = (CryptographicKey)key;
            return Platform.Core.CryptographicEngine.VerifySignatureWithHashInput(
                keyClass.Key,
                data.ToBuffer(),
                signature.ToBuffer());
        }
 public void VerifySignatureWithHashInput_NullData(ICryptographicKey key)
 {
     var signature = new byte[23];
     Assert.Throws<ArgumentNullException>(
         () => WinRTCrypto.CryptographicEngine.VerifySignatureWithHashInput(key, null, signature));
 }
 /// <inheritdoc />
 public byte[] DeriveKeyMaterial(ICryptographicKey key, IKeyDerivationParameters parameters, int desiredKeySize)
 {
     var platformKey = ((CryptographicKey)key).Key;
     var platformParameters = ((KeyDerivationParameters)parameters).Parameters;
     return Platform.Core.CryptographicEngine.DeriveKeyMaterial(platformKey, platformParameters, (uint)desiredKeySize).ToArray();
 }