Beispiel #1
0
 public static int ToInt32(IBuffer buffer)
 {
     byte[] data;
     CryptographicBuffer.CopyToByteArray(buffer, out data);
     data = GetBytes(data, 4);
     return(BitConverter.ToInt32(data, 0));
 }
Beispiel #2
0
        /// <summary>
        /// This function converts IBuffer data to string by specified format
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        public static string FormatValue(IBuffer buffer, DataFormat format)
        {
            byte[] data;
            CryptographicBuffer.CopyToByteArray(buffer, out data);

            switch (format)
            {
            case DataFormat.ASCII:
                return(Encoding.ASCII.GetString(data));

            case DataFormat.UTF8:
                return(Encoding.UTF8.GetString(data));

            case DataFormat.Dec:
                return(string.Join(" ", data.Select(b => b.ToString("00"))));

            case DataFormat.Hex:
                return(BitConverter.ToString(data).Replace("-", " "));

            case DataFormat.Bin:
                var s = string.Empty;
                foreach (var b in data)
                {
                    s += Convert.ToString(b, 2).PadLeft(8, '0') + " ";
                }
                return(s);

            default:
                return(Encoding.ASCII.GetString(data));
            }
        }
        /// <summary>
        /// Decrypts a message using a symmetric algorithm.
        /// </summary>
        private static void SymmetricDecrypt(
            TcpChannelToken token,
            ArraySegment <byte> dataToDecrypt,
            bool useClientKeys)
        {
            // get the decrypting key.
            CryptographicKey decryptingKey = (useClientKeys) ? token.ClientEncryptor : token.ServerEncryptor;
            IBuffer          IV            = (useClientKeys) ? CryptographicBuffer.CreateFromByteArray(token.ClientInitializationVector) : CryptographicBuffer.CreateFromByteArray(token.ServerInitializationVector);

            if (decryptingKey == null)
            {
                throw ServiceResultException.Create(StatusCodes.BadSecurityChecksFailed, "Token missing symmetric key object.");
            }

            SymmetricKeyAlgorithmProvider AesCbcProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbc);

            if (dataToDecrypt.Count % AesCbcProvider.BlockLength != 0)
            {
                throw ServiceResultException.Create(StatusCodes.BadSecurityChecksFailed, "Input data is not an even number of encryption blocks.");
            }

            byte[] blockToDecrypt = new byte[dataToDecrypt.Count];
            Array.ConstrainedCopy(dataToDecrypt.Array, dataToDecrypt.Offset, blockToDecrypt, 0, dataToDecrypt.Count);

            IBuffer block           = CryptographicBuffer.CreateFromByteArray(blockToDecrypt);
            IBuffer encryptedBuffer = CryptographicEngine.Decrypt(decryptingKey, block, IV);

            CryptographicBuffer.CopyToByteArray(encryptedBuffer, out blockToDecrypt);

            Array.ConstrainedCopy(blockToDecrypt, 0, dataToDecrypt.Array, dataToDecrypt.Offset, dataToDecrypt.Count);
        }
Beispiel #4
0
 public static byte[] DecryptAES(byte[] source, string publicKey)
 {
     if (source == null || source.Length == 0)
     {
         throw new ArgumentNullException("source");
     }
     if (string.IsNullOrEmpty(publicKey))
     {
         throw new ArgumentNullException("publicKey");
     }
     try
     {
         var     str                       = Convert.ToBase64String(source);
         IBuffer toDecryptBuffer           = CryptographicBuffer.DecodeFromBase64String(str);
         SymmetricKeyAlgorithmProvider aes = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
         var    symetricKey                = aes.CreateSymmetricKey(GetMD5Hash(publicKey));
         var    buffDecrypted              = CryptographicEngine.Decrypt(symetricKey, toDecryptBuffer, null);
         byte[] result;
         CryptographicBuffer.CopyToByteArray(buffDecrypted, out result);
         return(result);
     }
     catch (Exception ex)
     {
         return(null);
     }
 }
        public async Task <object> GenerateLocalPasswordAsync()
        {
            //var response = await _protoService.SendAsync(new GetTonWalletPasswordSalt());
            //if (response is TonWalletPasswordSalt passwordSalt)
            //{
            //    var passwordBuffer = CryptographicBuffer.GenerateRandom(64);
            //    var saltBuffer = CryptographicBuffer.GenerateRandom(32);

            //    CryptographicBuffer.CopyToByteArray(passwordBuffer, out byte[] password);
            //    CryptographicBuffer.CopyToByteArray(saltBuffer, out byte[] salt);

            //    System.Buffer.BlockCopy(passwordSalt.Salt.ToArray(), 0, password, 32, 32);

            //    return new ByteTuple(password, salt);
            //}
            //else if (response is Error error)
            //{
            //    return new Ton.Tonlib.Api.Error(error.Code, error.Message);
            //}

            //return null;

            var passwordBuffer = CryptographicBuffer.GenerateRandom(64);
            var saltBuffer     = CryptographicBuffer.GenerateRandom(32);

            CryptographicBuffer.CopyToByteArray(passwordBuffer, out byte[] password);
            CryptographicBuffer.CopyToByteArray(saltBuffer, out byte[] salt);

            await Task.CompletedTask;

            return(new ByteTuple(password, salt));
        }
Beispiel #6
0
 /// <summary>
 /// Generate a cryptographically secure random number
 /// </summary>
 /// <param name="length">Length of the desired number in bytes</param>
 /// <returns></returns>
 public static byte[] GenerateRandomBytes(uint length)
 {
     IBuffer buffer = CryptographicBuffer.GenerateRandom(length);
     byte[] rand = new byte[length];
     CryptographicBuffer.CopyToByteArray(buffer, out rand);
     return rand;
 }
        /// <inheritdoc />
        public override void ForwardProcessDataStream(Stream inStream, Stream outStream, Dictionary <string, string> options, out long writtenBytes)
        {
            if (options == null)
            {
                throw new ArgumentException("Options dictionary was null", "options");
            }
            else if (!options.ContainsKey(paddedSizeOptionName) || !options.ContainsKey(padTypeOptionName) || !options.ContainsKey(padExceptionOptionName))
            {
                throw new ArgumentException("Options dictionary did not contain the necessary padding options", "options");
            }

            int             paddingSize;
            DataPaddingType padType;
            bool            padException;

            if (!int.TryParse(options[paddedSizeOptionName], out paddingSize) || !bool.TryParse(options[padExceptionOptionName], out padException))
            {
                throw new ArgumentException("Options dictionary contained invalid options for DataPadder", "options");
            }

            try { padType = (DataPaddingType)Enum.Parse(typeof(DataPaddingType), options[padTypeOptionName]); }
            catch (ArgumentException) { throw new ArgumentException("Options dictionary contained invalid options for DataPadder", "options"); }

            if (padException && inStream.Length > paddingSize - 4)
            {
                throw new ArgumentException("Options dictionary contained invalid options for DataPadder. Not enough data padding was allowed", "options");
            }

            paddingSize = paddingSize - 4 - (int)inStream.Length;
            if (paddingSize < 0)
            {
                paddingSize = 0;
            }

            byte[] padData;

            if (padType == DataPaddingType.Random)
            {
#if NETFX_CORE
                CryptographicBuffer.CopyToByteArray(CryptographicBuffer.GenerateRandom((uint)paddingSize), out padData);
#else
                padData = new byte[paddingSize];
                rand.GetBytes(padData);
#endif
            }
            else
            {
                padData = new byte[paddingSize];
            }

            StreamTools.Write(inStream, 0, inStream.Length, outStream, 8192, double.MaxValue, int.MaxValue);

            if (paddingSize != 0)
            {
                outStream.Write(padData, 0, padData.Length);
            }

            outStream.Write(BitConverter.GetBytes(paddingSize + 4), 0, 4);
            writtenBytes = outStream.Position;
        }
        /// <summary>
        /// Implementation of Load from storage for Windows Store.
        /// </summary>
        protected async Task <byte[]> LoadDataAsync()
        {
            try
            {
                // find the storage file
                var localFolder = ApplicationData.Current.LocalFolder;

                var storageFile = await localFolder.GetFileAsync(StorageFile);

                // read the data. It will be encrypted data
                IBuffer buffProtected = await FileIO.ReadBufferAsync(storageFile);

                DataProtectionProvider provider = new DataProtectionProvider();

                // decrypt the data
                IBuffer clearBuffer = await provider.UnprotectAsync(buffProtected);

                // convert it to byte array
                byte[] clearBytes = new byte[clearBuffer.Length];
                CryptographicBuffer.CopyToByteArray(clearBuffer, out clearBytes);

                return(clearBytes);
            }
            catch (Exception)
            {
                return(null);
            }
        }
        /// <summary>
        /// HTTP请求签名
        /// </summary>
        /// <param name="url">请求目标的URL</param>
        /// <param name="body">请求的主体数据</param>
        /// <returns></returns>
        public string SignRequest(string url, byte[] body)
        {
            Uri    u            = new Uri(url);
            string pathAndQuery = u.PathAndQuery;

            byte[] pathAndQueryBytes = Encoding.UTF8.GetBytes(pathAndQuery);

            using (MemoryStream buffer = new MemoryStream())
            {
                buffer.Write(pathAndQueryBytes, 0, pathAndQueryBytes.Length);
                buffer.WriteByte((byte)'\n');
                if (body != null && body.Length > 0)
                {
                    buffer.Write(body, 0, body.Length);
                }
#if WINDOWS_UWP
                var    hma        = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha1);
                var    skBuffer   = CryptographicBuffer.ConvertStringToBinary(mac.SecretKey, BinaryStringEncoding.Utf8);
                var    hmacKey    = hma.CreateKey(skBuffer);
                var    dataBuffer = CryptographicBuffer.CreateFromByteArray(buffer.ToArray());
                var    signBuffer = CryptographicEngine.Sign(hmacKey, dataBuffer);
                byte[] digest;
                CryptographicBuffer.CopyToByteArray(signBuffer, out digest);
#else
                HMACSHA1 hmac   = new HMACSHA1(Encoding.UTF8.GetBytes(mac.SecretKey));
                byte[]   digest = hmac.ComputeHash(buffer.ToArray());
#endif
                string digestBase64 = Base64.UrlSafeBase64Encode(digest);
                return(string.Format("{0}:{1}", mac.AccessKey, digestBase64));
            }
        }
Beispiel #10
0
        /// <summary>
        /// Creates a public and private key pair that can be used for asymmethric encryption
        /// </summary>
        /// <param name="keySize">The keysize to generate</param>
        /// <returns>The generated key size</returns>
        public static KeyPair CreateKeyPair(RSAKeySizes keySize)
        {
#if WINDOWS_UWP
            var asym = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
            var key  = asym.CreateKeyPair((uint)keySize);

            var privateKeyBuffer = key.Export(CryptographicPrivateKeyBlobType.Capi1PrivateKey);
            var publicKeyBuffer  = key.ExportPublicKey(CryptographicPublicKeyBlobType.Capi1PublicKey);

            byte[] privateKeyBytes;
            byte[] publicKeyBytes;

            CryptographicBuffer.CopyToByteArray(privateKeyBuffer, out privateKeyBytes);
            CryptographicBuffer.CopyToByteArray(publicKeyBuffer, out publicKeyBytes);

            string privateKey = Convert.ToBase64String(privateKeyBytes);
            string publicKey  = Convert.ToBase64String(publicKeyBytes);
#else
            var cspParams = new CspParameters {
                ProviderType = 1                                 /* PROV_RSA_FULL */
            };
            var rsaProvider = new RSACryptoServiceProvider((int)keySize, cspParams);

            string publicKey  = Convert.ToBase64String(rsaProvider.ExportCspBlob(false));
            string privateKey = Convert.ToBase64String(rsaProvider.ExportCspBlob(true));
#endif
            return(new KeyPair(privateKey.ToSecureString(), publicKey));
        }
Beispiel #11
0
        public static byte[] Decrypt(SecureString privateKey, byte[] data)
        {
            if (privateKey == null)
            {
                throw new ArgumentNullException(nameof(privateKey));
            }

            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }
#if WINDOWS_UWP
            var keyBuffer = CryptographicBuffer.DecodeFromBase64String(privateKey.GetString());

            var asym = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
            var key  = asym.ImportKeyPair(keyBuffer, CryptographicPrivateKeyBlobType.Capi1PrivateKey);

            var plainBuffer = CryptographicEngine.Decrypt(key, data.AsBuffer(), null);

            byte[] plainBytes;
            CryptographicBuffer.CopyToByteArray(plainBuffer, out plainBytes);

            return(plainBytes);
#else
            var cspParams = new CspParameters {
                ProviderType = 1                                 /* PROV_RSA_FULL */
            };
            var rsaProvider = new RSACryptoServiceProvider(cspParams);
            rsaProvider.ImportCspBlob(Convert.FromBase64String(privateKey.GetString()));
            return(rsaProvider.Decrypt(data, false));
#endif
        }
Beispiel #12
0
        /// <summary>
        /// Encrypts data
        /// </summary>
        /// <param name="publicKey">The public key to use to encrypt the data</param>
        /// <param name="data">The data to encrypt</param>
        /// <returns>The ecrypted data</returns>
        /// <exception cref="ArgumentNullException"><paramref name="publicKey"/> is null</exception>
        /// <exception cref="ArgumentNullException"><paramref name="data"/> is null</exception>
        public static byte[] Encrypt(string publicKey, byte[] data)
        {
            if (publicKey == null)
            {
                throw new ArgumentNullException(nameof(publicKey));
            }

            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }
#if WINDOWS_UWP
            var keyBuffer = CryptographicBuffer.DecodeFromBase64String(publicKey);

            var asym = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
            var key  = asym.ImportPublicKey(keyBuffer, CryptographicPublicKeyBlobType.Capi1PublicKey);

            var plainBuffer     = CryptographicBuffer.CreateFromByteArray(data);
            var encryptedBuffer = CryptographicEngine.Encrypt(key, plainBuffer, null);

            byte[] encryptedBytes;
            CryptographicBuffer.CopyToByteArray(encryptedBuffer, out encryptedBytes);

            return(encryptedBytes);
#else
            var cspParams = new CspParameters {
                ProviderType = 1                                 /* PROV_RSA_FULL */
            };
            var rsaProvider = new RSACryptoServiceProvider(cspParams);

            rsaProvider.ImportCspBlob(Convert.FromBase64String(publicKey));

            return(rsaProvider.Encrypt(data, false));
#endif
        }
        // if received "01", send logs via notification from HistoryData characteristic
        protected override bool WriteRequested(GattSession session, GattWriteRequest request)
        {
            byte[] receivedWrite;
            CryptographicBuffer.CopyToByteArray(request.Value, out receivedWrite);
            var receivedWriteHexString = Helpers.ToHexString(request.Value);

            QuickLockHistoryService parent = (QuickLockHistoryService)this.ParentService;

            if ((request.Value.Length != 1) || (receivedWrite[0] != 0x01))
            {
                Debug.WriteLine($"Quicklock history cmd WriteRequested, but invalid format: {receivedWriteHexString} ({request.Value.Length})");
                //do not update Value, return
                OnPropertyChanged(new PropertyChangedEventArgs("InvalidRequest"));
                return(true);
            }

            Debug.WriteLine($"Quicklock history cmd received, sending out logs");

            //    OnPropertyChanged(new PropertyChangedEventArgs("Logs"));

            // set the status characteristic and send notification
            parent.QuickLockHistoryData.SendLogs();

            return(true);
        }
Beispiel #14
0
        private void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
        {
            try
            {
                byte[]            data;
                IBuffer           buffer = args.CharacteristicValue;
                ThermometerResult Result = new ThermometerResult();

                CryptographicBuffer.CopyToByteArray(buffer, out data);
                string rawdata = "";

                //  float temperature =(float) (((data[4] & 255) * 256 + (data[3] & 255)) * 0.01);
                // decimal temperature = (decimal) ((data[4] & 255) * 256 + (data[3] & 255)) ;
                int     a = data[4] & 255;
                int     b = data[3] & 255;
                int     c = a * 256;
                int     d = b + c;
                decimal f = decimal.Round(((decimal)d / (decimal)100), 1);
                //temperature = decimal.Round((temperature / (decimal)100), 1);
                for (int i = 0; i < data.Length; i++)
                {
                    rawdata += data[i].ToString() + "-";
                }

                MainPage.TestresultModel.ThermometerData(f, data.Length > 6? data[6]:0, data[2] == 193, rawdata);
            }catch (Exception ex)
            {
                MainPage.TestresultModel.NotifyStatusMessage?.Invoke("Exception: " + ex.Message, 2);
            }
            //  double temperature = (((0x0e & 0xff) * 256 + (0x78 & 0xff)) * 0.01);
            // double t = temperature;
            // double t1 = temperature1;
        }
Beispiel #15
0
        static async Task <(int err, byte[] sig)> VerifyUser(string key_name, string contentToSign)
        {
            if (await KeyCredentialManager.IsSupportedAsync() == false)
            {
                await(new MessageDialog("KeyCredentialManager not supported")).ShowAsync();
                return(ERR_VERIFY_HELLO_NOT_SUPPORTED, null);
            }

            var key = await KeyCredentialManager.OpenAsync(key_name);

            if (key.Status != KeyCredentialStatus.Success)
            {
                return(CredentialStatusToExitCode(key.Status), null);
            }

            var buf     = CryptographicBuffer.ConvertStringToBinary(contentToSign, BinaryStringEncoding.Utf8);
            var signRes = await key.Credential.RequestSignAsync(buf);

            if (signRes.Status != KeyCredentialStatus.Success)
            {
                return(CredentialStatusToExitCode(key.Status), null);
            }

            byte[] sig;
            CryptographicBuffer.CopyToByteArray(signRes.Result, out sig);
            return(0, sig);
        }
Beispiel #16
0
        private static byte[] GetCipherKey(string passphrase, int length)
        {
            List <byte> cipherKey = new List <byte>();

            var md5 = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);

            {
                byte[] passwordBytes = Encoding.UTF8.GetBytes(passphrase);

                byte[] buffer;
                CryptographicBuffer.CopyToByteArray(md5.HashData(CryptographicBuffer.CreateFromByteArray(passwordBytes.ToArray())), out buffer);
                var hash = buffer.AsEnumerable();

                cipherKey.AddRange(hash);

                while (cipherKey.Count < length)
                {
                    hash = passwordBytes.Concat(hash);

                    CryptographicBuffer.CopyToByteArray(md5.HashData(CryptographicBuffer.CreateFromByteArray(hash.ToArray())), out buffer);
                    hash = buffer.AsEnumerable();

                    cipherKey.AddRange(hash);
                }
            }

            return(cipherKey.Take(length).ToArray());
        }
Beispiel #17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SecureString"/> class from a subarray of
        /// <see cref="char"/> objects.
        /// </summary>
        /// <param name="value">A pointer to an array of System.Char objects.</param>
        /// <param name="length">The number of elements of value to include in the new instance.</param>
        public unsafe SecureString(char *value, int length)
        {
            this.Length = length;
            this.initialisationVector = Encoding.UTF8.GetBytes(CryptoUtils.BrewPassword(42)).GetBytes(16);

            byte[] dataCopy = new byte[length];
            var    gc       = GCHandle.Alloc(dataCopy, GCHandleType.Pinned);

            for (int i = 0; i < dataCopy.Length; i++)
            {
                dataCopy[i] = (byte)*(value + i);
            }

            // We cannot use our Aes implemtation in here because we will cause a cycling
            // dependency... And that will lead to a StackOverflow

            var passPhrase  = Encoding.UTF8.GetBytes(Debug.HardwareIdentifier.GetHash(HashAlgorithms.Sha512));
            var keyMaterial = CryptographicBuffer.CreateFromByteArray(passPhrase);

            var toDecryptBuffer = CryptographicBuffer.CreateFromByteArray(dataCopy);
            var aes             = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
            var symetricKey     = aes.CreateSymmetricKey(keyMaterial);
            var buffEncrypted   = CryptographicEngine.Encrypt(symetricKey, dataCopy.AsBuffer(), initialisationVector.AsBuffer());

            CryptographicBuffer.CopyToByteArray(buffEncrypted, out data);

            gc.FillWithRandomValues(dataCopy.Length);
        }
Beispiel #18
0
        private void GetTokenResponse(object Sender, IqResultEventArgs e)
        {
            object[] P = (object[])e.State;
#if WINDOWS_UWP
            Certificate Certificate = (Certificate)P[0];
#else
            X509Certificate2 Certificate = (X509Certificate2)P[0];
#endif
            XmlElement E = e.FirstElement;

            if (e.Ok && E != null && E.LocalName == "getTokenChallenge" && E.NamespaceURI == NamespaceProvisioningToken)
            {
                int    SeqNr     = XML.Attribute(E, "seqnr", 0);
                string Challenge = E.InnerText;
                byte[] Bin       = System.Convert.FromBase64String(Challenge);

#if WINDOWS_UWP
                CryptographicKey Key = PersistedKeyProvider.OpenPublicKeyFromCertificate(Certificate,
                                                                                         Certificate.SignatureHashAlgorithmName, CryptographicPadding.RsaPkcs1V15);
                IBuffer Buffer = CryptographicBuffer.CreateFromByteArray(Bin);
                Buffer = CryptographicEngine.Decrypt(Key, Buffer, null);
                CryptographicBuffer.CopyToByteArray(Buffer, out Bin);
                string Response = System.Convert.ToBase64String(Bin);
#else
                Bin = Certificate.GetRSAPrivateKey().Decrypt(Bin, RSAEncryptionPadding.Pkcs1);
                string Response = System.Convert.ToBase64String(Bin);
#endif

                this.client.SendIqGet(this.provisioningServerAddress, "<getTokenChallengeResponse xmlns='" + NamespaceProvisioningToken + "' seqnr='" +
                                      SeqNr.ToString() + "'>" + Response + "</getTokenChallengeResponse>",
                                      this.GetTokenChallengeResponse, P);
            }
        }
Beispiel #19
0
        /// <summary>
        /// Encrypt using AES/ECB
        /// </summary>
        /// <param name="message">The message to encrypt</param>
        /// <param name="key">The key with which to encrypt</param>
        /// <returns>Encrypted data</returns>
        private static byte[] EncryptAes(byte[] message, CryptographicKey key)
        {
            int blockRoundedSize = ((message.Length + 15) / 16) * 16;
            byte[] paddedMessage = new byte[blockRoundedSize];
            Array.Copy(message, paddedMessage, message.Length);

            IBuffer encrypted;
            IBuffer iv = null;
            IBuffer data = CryptographicBuffer.CreateFromByteArray(paddedMessage);
            String algName = SymmetricAlgorithmNames.AesEcb;

            // Encrypt the data.
            try
            {
                encrypted = CryptographicEngine.Encrypt(key, data, iv);
            }
            catch (Exception)
            {
                Debug.WriteLine("An invalid key size was selected for the given algorithm.\n"); 
                return null;
            }

            byte[] encryptedMsg = new byte[encrypted.Length];
            CryptographicBuffer.CopyToByteArray(encrypted, out encryptedMsg);
            return encryptedMsg;
        }
Beispiel #20
0
        public byte[] ComputeHash(byte[] buffer, int offset, int count)
        {
#if WINDOWS_STORE
            MacAlgorithmProvider provider = MacAlgorithmProvider.OpenAlgorithm(algorithmName);

            CryptographicKey hmacKey;
            if (Key != null)
            {
                hmacKey = provider.CreateKey(CryptographicBuffer.CreateFromByteArray(Key));
            }
            else
            {
                hmacKey = provider.CreateKey(CryptographicBuffer.GenerateRandom(provider.MacLength));
            }

            IBuffer hmacValue = CryptographicEngine.Sign(hmacKey, CryptographicBuffer.CreateFromByteArray(buffer));

            byte[] result;
            CryptographicBuffer.CopyToByteArray(hmacValue, out result);

            return(result);
#else
            return(hmac.ComputeHash(buffer, offset, count));
#endif
        }
Beispiel #21
0
        public byte[] Sign(byte[] securedInput, object key)
        {
            //using (var sha = HashAlgorithm)
            //{
            //var privateKey = Ensure.Type<AsymmetricAlgorithm>(key, "RsaUsingSha alg expects key to be of AsymmetricAlgorithm type.");

            AsymmetricKeyAlgorithmProvider provider =
                AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaSignPkcs1Sha256);

            //CryptographicKey cryptographicKey = (CryptographicKey)key;
            CryptographicKey cryptographicKey = provider.ImportKeyPair(((CryptographicKey)key).Export(CryptographicPrivateKeyBlobType.BCryptPrivateKey),
                                                                       CryptographicPrivateKeyBlobType.BCryptPrivateKey);

            //provider.ImportKeyPair(null, CryptographicPrivateKeyBlobType.)

            IBuffer signedData =
                CryptographicEngine.Sign(cryptographicKey, CryptographicBuffer.CreateFromByteArray(securedInput));

            byte[] result;
            CryptographicBuffer.CopyToByteArray(signedData, out result);

            return(result);

            //var pkcs1 = new RSAPKCS1SignatureFormatter(privateKey);
            //pkcs1.SetHashAlgorithm(hashMethod);

            //return pkcs1.CreateSignature(sha.ComputeHash(securedInput));
            //}
        }
Beispiel #22
0
    public static byte[] Encrypt(string plainText, string pw, string salt = "")
    {
        IBuffer pwBuffer    = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8);
        IBuffer saltBuffer  = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf16LE);
        IBuffer plainBuffer = CryptographicBuffer.ConvertStringToBinary(plainText, BinaryStringEncoding.Utf16LE);

        // Derive key material for password size 32 bytes for AES256 algorithm
        KeyDerivationAlgorithmProvider keyDerivationProvider = Windows.Security.Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1");
        // using salt and 1000 iterations
        KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000);

        // create a key based on original key and derivation parmaters
        CryptographicKey keyOriginal  = keyDerivationProvider.CreateKey(pwBuffer);
        IBuffer          keyMaterial  = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32);
        CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer);

        // derive buffer to be used for encryption salt from derived password key
        IBuffer saltMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16);

        // display the buffers – because KeyDerivationProvider always gets cleared after each use, they are very similar unforunately
        string keyMaterialString  = CryptographicBuffer.EncodeToBase64String(keyMaterial);
        string saltMaterialString = CryptographicBuffer.EncodeToBase64String(saltMaterial);

        SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7");
        // create symmetric key from derived password key
        CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial);

        // encrypt data buffer using symmetric key and derived salt material
        IBuffer resultBuffer = CryptographicEngine.Encrypt(symmKey, plainBuffer, saltMaterial);

        byte[] result;
        CryptographicBuffer.CopyToByteArray(resultBuffer, out result);

        return(result);
    }
Beispiel #23
0
        /// <summary>
        /// WPRT的RSA私钥解密
        /// </summary>
        /// <param name="rawData"></param>
        /// <returns></returns>
        public static string PrivateDecrypt(string rawData)
        {
            try
            {
                /*将文本转换成IBuffer*/
                IBuffer bufferRawData = CryptographicBuffer.ConvertStringToBinary(rawData, BinaryStringEncoding.Utf8);

                /*加密算法提供程序*/
                AsymmetricKeyAlgorithmProvider provider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm
                                                              (AsymmetricAlgorithmNames.RsaPkcs1);

                /*导入私钥*/
                string           PRIVATE_KEY = "MIICXAIBAAKBgQCJIYvV7IEzHOm4vdgu8RWc9it09ggXCKNAMEtcQM4kXT1mQyEnbEeGVYOyJWTd2jVhpToxMQ4r9p9EKd1bMClAA/KhUjQC/l9YdS3MFAZC65V47Bx6CTad4bZo1E1D6x1rOjQe4lANxWnApwY4QPYGFxEmQD3yNyErh38VlNL2GQIDAQABAoGAFxGmpZFI1uFpTCPbx2HVQfeDrgRprf5NAFJfiyB3zVRGLPrkC+7CRY4DPqfdxRidXFTgakAXYzv05RGp5FpAxf1GBAR6HQxVcntBpNqJUo2UBP+IrXgPFDPdodAl9SWgaHKwc79pCARVdJutm86kRRsy5rjcWpR8HQCYWzk/lmUCQQDcRnenz6CAhMvztS04APlly3uhvLGIVsXkGdsmv7JltRvFmZ/1MqpvAbC6WrzFMlWeFgYz6EyBiqfH6m4CbdJbAkEAn18K40E3r9WzPlbhIAEs2SiY68iZGCmzR/0n6PR48NtFSGsSDRIR632oeftBPfN7W4+kUIehL2gt9RgnRH8bmwJBAJMYK4dQSyoHg/q2nf+sBt9HRsP2sccNyxBLg+EYWhU5H9aQhBTFRLLkOhP3y98TgcETjAjVs2E+KlSB4/yTQckCQH4axVG23CptDQyp0C7z3xnh7sa7DrC45lxzK25Aa6YhyruXxUvEXZuZ7YK/1gsAKz7y9RCnkVoitCK4vvGLJjsCQBbzsW7HwZVe5RMiRsjxX7v0Ng4NnM85tnX0GUmkpuixOpfcq3PsZo7ujcBvJ5IJvbXo4QuuIRKSmxItHI26tkI=";
                CryptographicKey privateKey  = provider.ImportKeyPair(CryptographicBuffer.DecodeFromBase64String(PRIVATE_KEY));

                //解密
                IBuffer result = CryptographicEngine.Decrypt(privateKey, bufferRawData, null);
                byte[]  res;
                CryptographicBuffer.CopyToByteArray(result, out res);
                return(Encoding.UTF8.GetString(res, 0, res.Length));
            }
            catch (Exception)
            {
                return(rawData);
            }
        }
        protected override bool WriteRequested(GattSession session, GattWriteRequest request)
        {
            byte[] receivedWrite;
            CryptographicBuffer.CopyToByteArray(request.Value, out receivedWrite);
            var receivedWriteHexString = Helpers.ToHexString(request.Value);

            QuickLockMainService parent = (QuickLockMainService)this.ParentService;

            //expected: 0066612666 (pcap), or 006661266600000000 (also correct)
            if ((request.Value.Length != 5) && (request.Value.Length != 9))
            {
                Debug.WriteLine($"Smart lock auth WriteRequested, but invalid format: {receivedWriteHexString} ({request.Value.Length})");
                //do not update Value, return
                OnPropertyChanged(new PropertyChangedEventArgs("InvalidRequest"));
                return(true);
            }

            //check just the first byte and password, ignore rest if provided
            if ((receivedWrite[0] != 0x00) || (receivedWrite[1] != password[0]) || (receivedWrite[2] != password[1]) || (receivedWrite[3] != password[2]) || (receivedWrite[4] != password[3]))
            {
                Debug.WriteLine($"Smart lock auth WriteRequested: INVALID PASSWORD: {receivedWriteHexString} ({request.Value.Length})");
                //do not update Value, return
                OnPropertyChanged(new PropertyChangedEventArgs("InvalidPin"));
                return(true);
            }

            parent.UpdateAuthenticationState(true);
            OnPropertyChanged(new PropertyChangedEventArgs("AuthenticationState"));

            return(true);
        }
Beispiel #25
0
        protected override bool WriteRequested(GattSession session, GattWriteRequest request)
        {
            byte[] receivedWrite;
            CryptographicBuffer.CopyToByteArray(request.Value, out receivedWrite);
            var receivedWriteHexString = Helpers.ToHexString(request.Value);

            if ((request.Value.Length != 6) || (receivedWrite[5] != 0xFF))
            {
                Debug.WriteLine($"Light Bulb color Write requested, INVALID INPUT: {receivedWriteHexString} ({request.Value.Length})");
                //send notification to user
                OnPropertyChanged(new PropertyChangedEventArgs("InvalidRequest"));

                //do not update Value, return
                return(true);
            }

            // ARGB request
            if (receivedWrite[0] == 0xAA)
            {
                ProcessARGB(receivedWrite);
            }

            // password protected request
            else if (receivedWrite[0] == 0xBE)
            {
                ProcessPassProtected(receivedWrite);
            }

            //send to scenario
            return(true);
        }
Beispiel #26
0
        static public async Task <bool> createUser(User user, string password)
        {
            RestController <User> userController = new RestController <User>();
            var list = await userController.getObjects(WcfConfig.getUserUrl(user.Email));

            if (list.Count != 0)
            {
                return(false);
            }

            RestController <Role>    roleController    = new RestController <Role>();
            RestController <Patient> patientController = new RestController <Patient> ();

            List <Role> roles = await roleController.getObjects(WcfConfig.getRole(RolesKind.PATIENT));

            user.Roles = roles;

            IBuffer buff = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8);
            HashAlgorithmProvider hap = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256);
            IBuffer shaBuff           = hap.HashData(buff);

            byte[] pass;
            CryptographicBuffer.CopyToByteArray(shaBuff, out pass);
            user.Pass = pass;
            await userController.insertObject(user, WcfConfig.TableUser);

            await patientController.insertObject(new Patient { Pesel = user.Pesel }, WcfConfig.TablePatient);

            return(true);
        }
        /// <summary>
        /// helper function that copies the raw data into byte array
        /// </summary>
        /// <param name="buffer">The raw input buffer</param>
        private void SetValue(IBuffer buffer)
        {
            _rawData = buffer;
            CryptographicBuffer.CopyToByteArray(_rawData, out _data);

            SetValue();
        }
Beispiel #28
0
        public static byte[] HashData(TpmAlgId algId, byte[] dataToHash)
        {
            string algName;

            switch (algId)
            {
            case TpmAlgId.Sha1:
                algName = HashAlgorithmNames.Sha1;
                break;

            case TpmAlgId.Sha256:
                algName = HashAlgorithmNames.Sha256;
                break;

            case TpmAlgId.Sha384:
                algName = HashAlgorithmNames.Sha384;
                break;

            case TpmAlgId.Sha512:
                algName = HashAlgorithmNames.Sha512;
                break;

            default:
                Globs.Throw <ArgumentException>("AlgId is not a supported hash algorithm");
                return(null);
            }
            HashAlgorithmProvider algProvider = HashAlgorithmProvider.OpenAlgorithm(algName);
            IBuffer hashedData = algProvider.HashData(CryptographicBuffer.CreateFromByteArray(dataToHash));

            byte[] digest;
            CryptographicBuffer.CopyToByteArray(hashedData, out digest);
            return(digest);
        }
        public virtual void NextBytes(byte[] bytes, int start, int len)
        {
            if (start < 0)
            {
                throw new ArgumentException("Start offset cannot be negative", "start");
            }
            if (bytes.Length < (start + len))
            {
                throw new ArgumentException("Byte array too small for requested offset and length");
            }

            if (bytes.Length == len && start == 0)
            {
                NextBytes(bytes);
            }
            else
            {
#if NETFX_CORE
                byte[] tmpBuf = null;
                var    buffer = CryptographicBuffer.GenerateRandom((uint)bytes.Length);
                CryptographicBuffer.CopyToByteArray(buffer, out tmpBuf);
#else
                byte[] tmpBuf = new byte[len];
                NextBytes(tmpBuf);
#endif
                Array.Copy(tmpBuf, 0, bytes, start, len);
            }
        }
Beispiel #30
0
        void OnValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
        {
            CryptographicBuffer.CopyToByteArray(args.CharacteristicValue, out var value);
            if (_cache == null)
            {
                _cache = value;
            }
            else
            {
                var values = new List <byte>(_cache);
                values.AddRange(value);
                _cache = values.ToArray();
            }
            if (_cache.Length < 2)
            {
                return;
            }
            var code1 = _cache[_cache.Length - 2];
            var code2 = _cache[_cache.Length - 1];

            if (code1 != 0x0D || code2 != 0x0A)
            {
                return;
            }
            var str = Encoding.ASCII.GetString(_cache).TrimEnd();

            _cache = null;

            DealWithStr(str);
        }