IBuffer GetNonce()
        {
            // Security best practises require that an ecryption operation not
            // be called more than once with the same nonce for the same key.
            // A nonce value can be predictable, but must be unique for each
            // secure session.

            NonceBytes[0]++;
            for (int i = 0; i < NonceBytes.Length - 1; i++)
            {
                if (NonceBytes[i] == 255)
                {
                    NonceBytes[i + 1]++;
                }
            }

            return(CryptographicBuffer.CreateFromByteArray(NonceBytes));
        }
Example #2
0
        public static byte[] aesCtr(byte[] message, byte[] key, uint counter)
        {
            SymmetricKeyAlgorithmProvider objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7); // CRT
            IBuffer          buffKey             = CryptographicBuffer.CreateFromByteArray(key);
            CryptographicKey ckey = objAlg.CreateSymmetricKey(buffKey);

            byte[] ivBytes = new byte[16];
            ByteUtil.intToByteArray(ivBytes, 0, (int)counter);

            IBuffer buffPlaintext = CryptographicBuffer.CreateFromByteArray(message);
            IBuffer buffIV        = CryptographicBuffer.CreateFromByteArray(ivBytes);
            IBuffer buffEncrypt   = CryptographicEngine.Encrypt(ckey, buffPlaintext, buffIV);

            byte[] ret;
            CryptographicBuffer.CopyToByteArray(buffEncrypt, out ret);

            return(ret);
        }
Example #3
0
        public static string CalculateMD5Hash(this byte[] input)
        {
#if NETFX_CORE
            var     alg    = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            IBuffer buff   = CryptographicBuffer.CreateFromByteArray(input);
            var     hashed = alg.HashData(buff);
            var     res    = CryptographicBuffer.EncodeToHexString(hashed);
            return(res);
#else
            var hash = Cryptography.MD5.Create().ComputeHash(input);
            var sb   = new StringBuilder();
            foreach (var b in hash)
            {
                sb.Append(b.ToString("x2"));
            }
            return(sb.ToString());
#endif
        }
        public async Task <bool> EncryptAsync(string publicKey, IList <byte> dataArray, IList <byte> localPassword)
        {
            //if (await KeyCredentialManager.IsSupportedAsync())
            //{
            //    var boh = await KeyCredentialManager.RequestCreateAsync(publicKey, KeyCredentialCreationOption.ReplaceExisting);
            //    if (boh.Status == KeyCredentialStatus.Success)
            //    {
            //        var boh2 = await boh.Credential.RequestSignAsync()
            //    }
            //}
            //else
            {
                var dialog = new SettingsPasscodeInputPopup();

                var confirm = await dialog.ShowQueuedAsync();

                if (confirm != ContentDialogResult.Primary)
                {
                    return(false);
                }

                var secret   = CryptographicBuffer.ConvertStringToBinary(dialog.Passcode, BinaryStringEncoding.Utf8);
                var salt     = CryptographicBuffer.GenerateRandom(32);
                var material = PBKDF2(secret, salt);

                var data = CryptographicBuffer.CreateFromByteArray(dataArray.ToArray());

                var objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
                var key    = objAlg.CreateSymmetricKey(material);

                var encrypt    = CryptographicEngine.Encrypt(key, data, null);
                var saltString = CryptographicBuffer.EncodeToHexString(salt);
                var dataString = CryptographicBuffer.EncodeToHexString(encrypt);

                var localPasswordBuffer = CryptographicBuffer.CreateFromByteArray(localPassword.ToArray());
                var localPasswordString = CryptographicBuffer.EncodeToHexString(localPasswordBuffer);

                var vault    = new PasswordVault();
                var password = $"{saltString};{dataString};{localPasswordString};{(dialog.IsSimple ? 1 : 2)}";
                vault.Add(new PasswordCredential($"{_session}", publicKey, password));
            }

            return(true);
        }
Example #5
0
        //-------------------------------------------------------------------------------------------------
        //--- Generate a OneTime Password from a Guid
        //-------------------------------------------------------------------------------------------------
        public static async Task <int> OTPFromGuid(Guid TheGuid, bool UseNetworkTime = false)
        {
            Int64 myTimeStamp;

            byte[] mySecret;
            byte[] myHmac;
            byte[] myData;
            int    myOffset;
            int    myOneTimePassword;
            Int64  MyUnixTimestamp;

            mySecret = StringToBytes(TheGuid.ToString("N"));

#if WINDOWS_UWP
            var myCryptprovider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha1);
#else
            HMACSHA1 crypt = new HMACSHA1(mySecret);
#endif
            MyUnixTimestamp = await GetUnixTimestamp(UseNetworkTime);

            myTimeStamp = Convert.ToInt64(MyUnixTimestamp / 30);
            myData      = BitConverter.GetBytes(myTimeStamp).Reverse().ToArray();

#if WINDOWS_UWP
            var myBuffer    = CryptographicBuffer.CreateFromByteArray(myData);
            var myKeyBuffer = CryptographicBuffer.CreateFromByteArray(mySecret);

            var myKey          = myCryptprovider.CreateKey(myKeyBuffer);
            var mySignedBuffer = CryptographicEngine.Sign(myKey, myBuffer);

            CryptographicBuffer.CopyToByteArray(mySignedBuffer, out myHmac);
#else
            myHmac = new HMACSHA1(mySecret).ComputeHash(myData);
#endif
            myOffset          = myHmac.Last() & 0x0F;
            myOneTimePassword = (
                ((myHmac[myOffset + 0] & 0x7f) << 24) |
                ((myHmac[myOffset + 1] & 0xff) << 16) |
                ((myHmac[myOffset + 2] & 0xff) << 8) |
                (myHmac[myOffset + 3] & 0xff)
                ) % 1000000;

            return(myOneTimePassword);
        }
        public static CryptographicKey New([ReadOnlyArray] byte[] x, [ReadOnlyArray] byte[] y, [ReadOnlyArray] byte[] d)
        {
            if (x.Length != y.Length)
            {
                throw new ArgumentException("X, Y and Z must be same size");
            }

            if (x.Length != d.Length)
            {
                throw new ArgumentException("X and Y must be same size");
            }

            int partSize = x.Length;

            byte[] magic;
            string alg;

            if (partSize == 32)
            {
                magic = BCRYPT_ECDSA_PRIVATE_P256_MAGIC;
                alg   = AsymmetricAlgorithmNames.EcdsaP256Sha256;
            }
            else if (partSize == 48)
            {
                magic = BCRYPT_ECDSA_PRIVATE_P384_MAGIC;
                alg   = AsymmetricAlgorithmNames.EcdsaP384Sha384;
            }
            else if (partSize == 66)
            {
                magic = BCRYPT_ECDSA_PRIVATE_P521_MAGIC;
                alg   = AsymmetricAlgorithmNames.EcdsaP521Sha512;
            }
            else
            {
                throw new ArgumentException("Size of X,Y or D must equal to 32, 48 or 66 bytes");
            }

            byte[] partLength = BitConverter.GetBytes(partSize);

            byte[] blob = Arrays.Concat(magic, partLength, x, y, d);

            return(AsymmetricKeyAlgorithmProvider.OpenAlgorithm(alg)
                   .ImportKeyPair(CryptographicBuffer.CreateFromByteArray(blob), CryptographicPrivateKeyBlobType.BCryptPrivateKey));
        }
Example #7
0
        public static byte[] decrypt(byte[] input, byte[] key)
        {
            /*
             * byte[] iv = new byte[IV_LENGTH];
             */
            byte[] encryptedData = new byte[input.Length - IV_LENGTH];
            // Buffer.BlockCopy(input, 0, iv, 0, iv.Length);
            Buffer.BlockCopy(input, IV_LENGTH, encryptedData, 0, encryptedData.Length);

            var encryptedBuffer = CryptographicBuffer.CreateFromByteArray(encryptedData);
            var aes             = SymmetricKeyAlgorithmProvider.OpenAlgorithm(ENC_ALG);
            var symmetricKey    = aes.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(key));
            // var ivBuffer = CryptographicBuffer.CreateFromByteArray(iv);
            var decryptedBuffer = CryptographicEngine.Decrypt(symmetricKey, encryptedBuffer, null);

            byte[] outputBuffer = new byte[decryptedBuffer.Length];
            CryptographicBuffer.CopyToByteArray(decryptedBuffer, out outputBuffer);
            return(outputBuffer);
        }
        public Part[] Encrypt([ReadOnlyArray] byte[] aad, [ReadOnlyArray] byte[] plainText, [ReadOnlyArray] byte[] cek)
        {
            Ensure.BitSize(cek, keySizeBits, string.Format("AesCbcHmacEncryptor expected key of size {0} bits, but was given {1} bits", keySizeBits, cek.Length * 8));

            byte[] hmacKey = Arrays.FirstHalf(cek);
            byte[] aesKey  = Arrays.SecondHalf(cek);

            IBuffer iv = CryptographicBuffer.GenerateRandom(16);

            SymmetricKeyAlgorithmProvider alg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);

            CryptographicKey key = alg.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(aesKey));

            byte[] cipherText = Buffer.ToBytes(CryptographicEngine.Encrypt(key, CryptographicBuffer.CreateFromByteArray(plainText), iv));

            byte[] authTag = ComputeAuthTag(aad, Buffer.ToBytes(iv), cipherText, hmacKey);

            return(new[] { new Part(Buffer.ToBytes(iv)), new Part(cipherText), new Part(authTag) });
        }
Example #9
0
        public byte[] DecryptSsh1(BigInteger e, BigInteger n, BigInteger encryptedChallenge, byte[] sessionId)
        {
            var decryptKey = GetKey(e, n);

            if (decryptKey == null)
            {
                return(null);
            }

            RsaCipher cipher = new RsaCipher((RsaKey)decryptKey.Key.Key);

            byte[] decryptedChallenge = cipher.Decrypt(encryptedChallenge.ToByteArray().Reverse().ToArray());

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

            byte[] response;
            CryptographicBuffer.CopyToByteArray(md5.HashData(CryptographicBuffer.CreateFromByteArray(decryptedChallenge.Concat(sessionId).ToArray())), out response);
            return(response);
        }
Example #10
0
        private async void sendChallenge(byte[] data)
        {
            IBuffer    buffer = CryptographicBuffer.CreateFromByteArray(data);
            DataReader reader = DataReader.FromBuffer(buffer);
            DataWriter writer = new DataWriter();

            // read packet type
            byte packetType = reader.ReadByte();

            m_logger.WriteLine("Packet type: " + packetType);

            // read pseudonym
            byte   len       = reader.ReadByte();
            string pseudonym = reader.ReadString(len);

            m_logger.WriteLine("Server pseudonym: " + pseudonym);

            byte[] sharedKey = m_member.computeSharedKeyClient(pseudonym, HandshakeParty.SERVER_ROLE);
            m_logger.WriteLine("Computed shared key: " + BitConverter.ToString(sharedKey));

            // set packet type and write pseudonym
            writer.WriteByte((byte)PACKET_TYPE.PKT_TYPE_CHLNG);
            writer.WriteByte((byte)m_member.getPseudonym().Length);
            writer.WriteString(m_member.getPseudonym());

            // prepare challenge
            byte[] encChallenge = m_member.getChallenge(sharedKey, out m_challenge);
            m_logger.WriteLine("Sending challenge " + m_challenge.ToString() + " to other party");

            // send challenge length
            len = (byte)encChallenge.Length;
            writer.WriteByte(len);

            // send challenge
            writer.WriteBytes(encChallenge);
            byte[] adData = getWriterData(writer);
            startPublisher(adData);

            await System.Threading.Tasks.Task.Delay(TimeSpan.FromSeconds(3));

            // wait for response
            startScanning(handleResponse);
        }
Example #11
0
        public static string GetZeroDigestForAlgorithm(string algorithm, int initialValue = 0)
        {
            uint digestSize = GetDigestSizeForAlgorithm(algorithm);

            byte[] zeroDigest = new byte[digestSize];
            Array.Clear(zeroDigest, 0, (int)digestSize);

            var buffer = CryptographicBuffer.CreateFromByteArray(zeroDigest);
            var ret    = CryptographicBuffer.EncodeToHexString(buffer);

            if (initialValue != 0)
            {
                string initialString = String.Format("{0:x}", initialValue);
                int    start         = ret.Length - initialString.Length;
                ret = ret.Remove(start, initialString.Length).Insert(start, initialString);
            }

            return(ret);
        }
        public static String CreateHMAC(String encrypted, String keyBytes)
        {
            String strAlgName = SampleConfiguration.MacAlg;
            MacAlgorithmProvider objMacProv = MacAlgorithmProvider.OpenAlgorithm(strAlgName);

            IBuffer buffKeyMaterial = CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(keyBytes));
            IBuffer bufMsg          = CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(encrypted));

            CryptographicKey hmacKey  = objMacProv.CreateKey(buffKeyMaterial);
            IBuffer          buffHMAC = CryptographicEngine.Sign(hmacKey, bufMsg);

            // Verify that the HMAC length is correct for the selected algorithm
            if (buffHMAC.Length != objMacProv.MacLength)
            {
                throw new Exception("Error computing digest");
            }

            return(CryptographicBuffer.EncodeToBase64String(buffHMAC));
        }
Example #13
0
        //-------------------------------------------------------------------------------------------------
        //--- Private constructor to initialise the internal variables
        //-------------------------------------------------------------------------------------------------

        private StringEncryptor()
        {
            myRandomGenerator = new Random();
            myEncoder         = new UTF8Encoding();
            myKeyArray        = Convert.FromBase64String("Do+Not+Forget+to+Change+this+Now");

#if WINDOWS_UWP
            myCryptoAlgorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7");
            keymaterial       = CryptographicBuffer.CreateFromByteArray(myKeyArray);
            key = myCryptoAlgorithm.CreateSymmetricKey(keymaterial);
#else
            myCryptoAlgorithm         = new AesCryptoServiceProvider();
            myCryptoAlgorithm.Mode    = CipherMode.CBC;
            myCryptoAlgorithm.Padding = PaddingMode.PKCS7;

            myCryptoAlgorithm.KeySize   = 256;
            myCryptoAlgorithm.BlockSize = 128;
#endif
        }
Example #14
0
        private static string DecryptPassword(CryptoPassword cp)
        {
            // Restore Buffer for IV.
            var bufferIV = CryptographicBuffer.CreateFromByteArray(cp.IV);

            // Restore Buffer for Encrypted Password.
            var bufferEncryptedPassword = CryptographicBuffer.CreateFromByteArray(cp.EncryptedPassword);

            // Restore Buffer for Key.
            var bufferKeyMaterial = CryptographicBuffer.CreateFromByteArray(cp.KeyMaterial);

            // Rebuild key.
            var key = CreateSymmetricKey(bufferKeyMaterial);

            // Get buffer for decrypted Password.
            var bufferDecrypt = CryptographicEngine.Decrypt(key, bufferEncryptedPassword, bufferIV);

            return(CryptographicBuffer.ConvertBinaryToString(_encoding, bufferDecrypt));
        }
        internal static string ComputeHmac256(byte[] key, string message)
        {
#if RT
            MacAlgorithmProvider macAlgorithmProvider = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA256");
            IBuffer          keyMaterial   = CryptographicBuffer.CreateFromByteArray(key);
            CryptographicKey hmacKey       = macAlgorithmProvider.CreateKey(keyMaterial);
            IBuffer          messageBuffer = CryptographicBuffer.ConvertStringToBinary(message, BinaryStringEncoding.Utf8);
            IBuffer          signedMessage = CryptographicEngine.Sign(hmacKey, messageBuffer);
            return(CryptographicBuffer.EncodeToBase64String(signedMessage));
#elif COMMON
            return(null);
#else
            using (HashAlgorithm hashAlgorithm = new HMACSHA256(key))
            {
                byte[] messageBuffer = Encoding.UTF8.GetBytes(message);
                return(Convert.ToBase64String(hashAlgorithm.ComputeHash(messageBuffer)));
            }
#endif
        }
Example #16
0
        /// <summary>
        /// /////////////////////////////////////////////////////////////////////////////////////////////
        /// </summary>
        /// <param name="sender"></param>

        ////////////////////////////////////////////////////////////////////////////////////////////

        private async void btnCharacteristicWriteData1_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(CharacteristicWriteValue.Text))
            {
                byte[] bw = { 0 };


                bw[0] = (byte)Convert.ToInt32(CharacteristicWriteValue.Text);;

                IBuffer writeBuffer = CryptographicBuffer.CreateFromByteArray(bw);

                var writeSuccessful = await WriteBufferToSelectedCharacteristicAsync(writeBuffer);
            }
            else
            {
                strDevName = "No data to write to device";
                printToLog(strDevName);
            }
        }
Example #17
0
        /// <summary>
        /// Hash message using SHA1
        /// </summary>
        /// <param name="data">The data to hash</param>
        /// <returns>Byte array containing SHA1 hash</returns>
        private static byte[] ToSHA1Bytes(byte[] data)
        {
            IBuffer messageBuffer = CryptographicBuffer.CreateFromByteArray(data);

            // Create a HashAlgorithmProvider object that opens SHA1.
            HashAlgorithmProvider algProv = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1);

            // Hash the message
            IBuffer hashedBuffer = algProv.HashData(messageBuffer);

            // Verify that the hash length equals the length specified for the algorithm.
            if (hashedBuffer.Length != algProv.HashLength)
            {
                throw new Exception("There was an error creating the hash");
            }
            byte[] hashed = new byte[hashedBuffer.Length];
            CryptographicBuffer.CopyToByteArray(hashedBuffer, out hashed);
            return(hashed);
        }
        public void TestDeriveSharedSecret()
        {
            BigInteger         pX        = BigInteger.Parse("68319caad24e6909cd8b3962d7d0077f4cc9dc348b96da80e9b45de70e6ba30e", NumberStyles.HexNumber);
            BigInteger         pY        = BigInteger.Parse("00d82256dcb4153cb26b9ffc3846660b348767e06422c996b0f1646c8f1aee0051", NumberStyles.HexNumber);
            EllipticCurvePoint publicKey = new EllipticCurvePoint(pX, pY);

            BigInteger privateKey = BigInteger.Parse("00885d74025021979e140f419966b2119dc4a19f89bae719c14f97bdb594c3e2f5", NumberStyles.HexNumber);

            var provider = new EllipticCurveCryptoProvider(EllipticCurveNames.Secp256R1);
            EllipticCurvePoint sharedSecret = provider.DeriveSharedSecret(privateKey, publicKey);

            IBuffer info = CryptographicBuffer.CreateFromByteArray(new byte[] { 0x01 });
            IBuffer salt = null;
            var     outputKeyMaterial = provider.DerivteKeyWithHkdf(sharedSecret, salt, info);

            var strKeyHex = CryptographicBuffer.EncodeToHexString(outputKeyMaterial);

            Assert.AreEqual("a6cf3a73f624e73bef4f9760156b039bc2004133207c1186685aa72c2cbdf752".ToUpper(), strKeyHex.ToUpper());
        }
Example #19
0
        public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
        {
            if (inputBuffer == null)
            {
                throw new ArgumentNullException("inputBuffer");
            }

            if (inputOffset < 0 || inputOffset > inputBuffer.Length)
            {
                throw new ArgumentOutOfRangeException("inputOffset");
            }

            if (inputCount < 0 || inputOffset > inputBuffer.Length - inputCount)
            {
                throw new ArgumentOutOfRangeException("inputCount");
            }

            if (outputBuffer == null)
            {
                throw new ArgumentNullException("outputBuffer");
            }

            if (outputOffset < 0 || outputOffset > outputBuffer.Length - algorithm.BlockLength)
            {
                throw new ArgumentOutOfRangeException("outputOffset");
            }

            IBuffer encrypted, data;

            byte[] input, output;

            input = new byte[inputCount];
            Array.Copy(inputBuffer, inputOffset, input, 0, inputCount);
            data = CryptographicBuffer.CreateFromByteArray(input);

            encrypted = CryptographicEngine.Encrypt(key, data, iv);

            CryptographicBuffer.CopyToByteArray(encrypted, out output);

            Array.Copy(output, 0, outputBuffer, outputOffset, output.Length);

            return(output.Length);
        }
        public byte[] ComputeHash(Stream stream)
        {
            int bytesRead    = 0;
            var cryptoBuffer = CryptographicBuffer.CreateFromByteArray(new byte[AWSSDKUtils.DefaultBufferSize]);

            byte[] buffer = new byte[AWSSDKUtils.DefaultBufferSize];
            while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
            {
                if (bytesRead != cryptoBuffer.Length)
                {
                    cryptoBuffer = CryptographicBuffer.CreateFromByteArray(new byte[bytesRead]);
                }

                buffer.CopyTo(0, cryptoBuffer, 0, bytesRead);
                _hash.Append(cryptoBuffer);
            }

            return(_hash.GetValueAndReset().ToArray());
        }
Example #21
0
        private static CryptographicKey GenerateKey()
        {
            HashAlgorithmProvider         algorithm         = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha512);
            CryptographicHash             cryptographicHash = algorithm.CreateHash();
            SymmetricKeyAlgorithmProvider provider          = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);

            byte[] hash = new byte[32];
            cryptographicHash.Append(CryptographicBuffer.CreateFromByteArray(Encoding.UTF8.GetBytes("Pa$$w0rd")));

            byte[] temp;
            CryptographicBuffer.CopyToByteArray(cryptographicHash.GetValueAndReset(), out temp);

            Array.Copy(temp, 0, hash, 0, 16);
            Array.Copy(temp, 0, hash, 15, 16);

            CryptographicKey key = provider.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash));

            return(key);
        }
        public string GenerateSteamGuardCodeForTime(long time)
        {
            if (string.IsNullOrEmpty(this.SharedSecret))
            {
                return("");
            }

            IBuffer sharedSecretArray = CryptographicBuffer.DecodeFromBase64String(this.SharedSecret);
            var     timeArray         = new byte[8];

            time /= 30L;

            for (var i = 8; i > 0; i--)
            {
                timeArray[i - 1] = (byte)time;
                time           >>= 8;
            }
            IBuffer data = CryptographicBuffer.CreateFromByteArray(timeArray);

            MacAlgorithmProvider hmacsha1 = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1");
            CryptographicKey     hmacKey  = hmacsha1.CreateKey(sharedSecretArray);

            byte[] hashedData = CryptographicEngine.Sign(hmacKey, data).ToArray();
            var    codeArray  = new byte[5];

            try
            {
                var b         = (byte)(hashedData[19] & 0xF);
                int codePoint = (hashedData[b] & 0x7F) << 24 | (hashedData[b + 1] & 0xFF) << 16 | (hashedData[b + 2] & 0xFF) << 8 | (hashedData[b + 3] & 0xFF);

                for (var i = 0; i < 5; ++i)
                {
                    codeArray[i] = SteamGuardCodeTranslations[codePoint % SteamGuardCodeTranslations.Length];
                    codePoint   /= SteamGuardCodeTranslations.Length;
                }
            }
            catch (Exception)
            {
                return(null); //Change later, catch-alls are bad!
            }
            return(Encoding.UTF8.GetString(codeArray, 0, codeArray.Length));
        }
Example #23
0
File: Utils.cs Project: Fart03/lau
        // Note: ivec - big-endian, but BigInterger.ctor and BigInteger.ToByteArray return little-endian
        public static byte[] AES_ctr128_encrypt(byte[] input, IBuffer key, ref byte[] ivec, ref byte[] ecount_buf, ref uint num)
        {
            uint n;
            var  output = new byte[input.Length];

            n = num;

            var provider     = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcb);
            var keySymmetric = provider.CreateSymmetricKey(key);

            for (uint i = 0; i < input.Length; i++)
            {
                if (n == 0)
                {
                    var ivecBuffer   = CryptographicBuffer.CreateFromByteArray(ivec);
                    var ecountBuffer = CryptographicEngine.Encrypt(keySymmetric, ivecBuffer, null);

                    CryptographicBuffer.CopyToByteArray(ecountBuffer, out ecount_buf);
                    Array.Reverse(ivec);
                    var bi = new System.Numerics.BigInteger(TLUtils.Combine(ivec, new byte[] { 0x00 }));
                    bi = (bi + 1);
                    var biArray = bi.ToByteArray();
                    var b       = new byte[16];
                    //for (var j = 0; j < biArray.Length && j < b.Length; j++)
                    //{
                    //    b[j] = biArray[j];
                    //}

                    System.Buffer.BlockCopy(biArray, 0, b, 0, Math.Min(biArray.Length, b.Length));

                    //System.Diagnostics.Debug.WriteLine(bi);
                    Array.Reverse(b);
                    ivec = b;
                }

                output[i] = (byte)(input[i] ^ ecount_buf[n]);
                n         = (n + 1) % 16;
            }

            num = n;
            return(output);
        }
Example #24
0
        private void WriteSignedData(Stream stream, SmtpMessage message, Byte[] body, Byte[] boundary)
        {
            var    mg = message;
            Stream mm = stream;

            ThrowExceptionIfValueIsNull(mg.From.CryptographicKeyInfo.Base64Content, "Can't sign message unless the From property contains a privateKey.");

            mm.Write(ByteData.ContentTypeMultipartSignedProtocolApplicationXpkcs7Signature);
            mm.WriteByte(34); // "
            mm.Write(boundary);
            mm.WriteByte(34); // "
            mm.Write(ByteData.NewLine);
            mm.Write(ByteData.NewLine);

            mm.Write(ByteData.NewLine);
            mm.Write(boundary);
            mm.Write(ByteData.NewLine);
            mm.Write(body);
            mm.Write(ByteData.NewLine);
            mm.Write(boundary);
            mm.Write(ByteData.NewLine);
            mm.Write(ByteData.ContentTypeApplicationXpkcs7Signature);
            mm.Write(ByteData.NewLine);
            mm.Write(ByteData.ContentTransferEncodingIsBase64);
            mm.Write(ByteData.NewLine);
            mm.Write(ByteData.ContentDispositionAttachmentFileNameIsSmimeP7s);

            mm.Write(ByteData.NewLine);
            mm.Write(ByteData.NewLine);
            var signatureBuffer = Cryptography.ToSignMessage(CryptographicBuffer.CreateFromByteArray(body), mg.From.CryptographicKeyInfo);

            Byte[] signature;
            CryptographicBuffer.CopyToByteArray(signatureBuffer, out signature);
            Base64Converter converter = new Base64Converter(body.Length);

            mm.Write(converter.Encode(signature));
            mm.Write(ByteData.NewLine);
            mm.Write(ByteData.NewLine);
            mm.Write(boundary);
            mm.Write(Encoding.UTF8.GetBytes("--"));
            mm.Write(ByteData.NewLine);
        }
Example #25
0
        /// <summary>
        /// Obtiene los datos cifrados con DES
        /// </summary>
        /// <param name="data">Datos a cifrar</param>
        /// <param name="keyString">clave con la que cifrar</param>
        /// <returns></returns>
        public static byte[] getDES(byte[] data, string keyString)
        {
            //creamos el proveedor de cifrado
            SymmetricKeyAlgorithmProvider symmetricKeyAlgorithmProvider =
                SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.DesEcb);

            // Declaramos el encoding
            BinaryStringEncoding encoding = BinaryStringEncoding.Utf8;
            // Creamos un buffer con el contenido de la clave
            IBuffer buffkey = CryptographicBuffer.ConvertStringToBinary(keyString, encoding);

            //creamos la clave
            CryptographicKey cryptographicKey =
                symmetricKeyAlgorithmProvider.CreateSymmetricKey(buffkey);

            // Creamos un buffer con el contenido a cifrar
            IBuffer dataBuffer = CryptographicBuffer.CreateFromByteArray(data);
            IBuffer dataToSign = dataBuffer;

            if ((data.Length % 8) > 0)
            {
                int    diff = (int)(data.Length % 8);
                byte[] buff = new byte[dataBuffer.Length + (8 - diff)];
                for (int i = 0; i < buff.Length; i++)
                {
                    buff[i] = 0;
                }
                Array.Copy(data, buff, data.Length);
                dataToSign = CryptographicBuffer.CreateFromByteArray(buff);
            }
            //ciframos
            IBuffer cipherTextBuffered = CryptographicEngine.Encrypt(cryptographicKey, dataToSign, null);

            //Se prepara el contenedor del mensaje cifrado
            byte[] cipherText = new byte[cipherTextBuffered.Length];

            //Se copia el contenido
            CryptographicBuffer.CopyToByteArray(cipherTextBuffered, out cipherText);

            //se devuelve el contenido cifrado.
            return(cipherText);
        }
Example #26
0
        public static string GetAnonymousLoginKey()
        {
            byte[] radomBytes16 = GenerateRandomByte(16);
            byte[] radomByte4   = GenerateRandomByte(4);
            int    time         = (int)(DateTime.Now - new DateTime(1970, 1, 1)).TotalSeconds;

            byte[] timeBytes  = BitConverter.GetBytes(time);
            byte[] timeBytes1 = timeBytes.Concat(radomByte4).ToArray();
            byte[] timeBytes2 = timeBytes1.Concat(Param).ToArray();

            byte[] arrayOfByte = AESHandle(timeBytes2, radomBytes16);

            byte[] arrayOfByte1 = radomBytes16.Concat(arrayOfByte).ToArray();
            byte[] arrayOfByte2 = MD5Handle(arrayOfByte1);
            byte[] arrayOfByte3 = arrayOfByte2.Concat(radomBytes16).ToArray();
            byte[] arrayOfByte4 = arrayOfByte3.Concat(arrayOfByte).ToArray();
            string rst          = CryptographicBuffer.EncodeToBase64String(CryptographicBuffer.CreateFromByteArray(arrayOfByte4));

            return(rst);
        }
Example #27
0
        /// <summary>
        /// Hashes the given <paramref name="data"/> with the given <paramref name="algName"/> and returns it.
        /// <para/>
        /// Source: https://docs.microsoft.com/en-us/uwp/api/windows.security.cryptography.core.hashalgorithmprovider
        /// </summary>
        /// <param name="data">The data that should get hashed.</param>
        /// <param name="algName">The <see cref="HashAlgorithmNames"/> name that should get used for hashing.</param>
        /// <returns></returns>
        private static byte[] hash(byte[] data, string algName)
        {
            // Convert the message string to binary data.
            IBuffer buffUtf8Msg = CryptographicBuffer.CreateFromByteArray(data);

            // Create a HashAlgorithmProvider object.
            HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(algName);

            // Hash the message.
            IBuffer buffHash = objAlgProv.HashData(buffUtf8Msg);

            // Verify that the hash length equals the length specified for the algorithm.
            if (buffHash.Length != objAlgProv.HashLength)
            {
                throw new InvalidOperationException("There was an error creating the hash");
            }

            // Return the encoded string
            return(buffHash.ToArray());
        }
Example #28
0
        public static byte[] aesCbcPkcs5(byte[] message, byte[] key, byte[] iv)
        {
            SymmetricKeyAlgorithmProvider objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
            IBuffer          buffKey             = CryptographicBuffer.CreateFromByteArray(key);
            CryptographicKey ckey = objAlg.CreateSymmetricKey(buffKey);

            if (message.Length % objAlg.BlockLength != 0)
            {
                throw new Exception("Invalid ciphertext length");
            }


            IBuffer buffPlaintext = CryptographicBuffer.CreateFromByteArray(message);
            IBuffer buffIV        = CryptographicBuffer.CreateFromByteArray(iv);
            IBuffer buffEncrypt   = CryptographicEngine.Decrypt(ckey, buffPlaintext, buffIV);

            byte[] ret;
            CryptographicBuffer.CopyToByteArray(buffEncrypt, out ret);
            return(ret);
        }
Example #29
0
        /// <summary>
        /// Calculates MD5 hash
        /// </summary>
        /// <param name="data">Input array of bytes</param>
        /// <param name="numBytes">Number of bytes in array to use</param>
        /// <returns>byte[32] MD5 hash</returns>
        public static byte[] MD5(byte[] data, int numBytes)
        {
            Debug.Assert(numBytes <= data.Length);

            byte[] result;

#if NETFX_CORE
            HashAlgorithmProvider alg  = Windows.Security.Cryptography.Core.HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            CryptographicHash     hash = alg.CreateHash();
            IBuffer buffer             = CryptographicBuffer.CreateFromByteArray(data);
            hash.Append(buffer);
            IBuffer hashBuff = hash.GetValueAndReset();
            result = hashBuff.ToArray();
#else
            MD5 md5 = System.Security.Cryptography.MD5.Create();
            result = md5.ComputeHash(data);
#endif

            return(result);
        }   // end of MD5()
Example #30
0
        public static string Decrypt(byte[] encryptedData, string pw, string salt)
        {
            IBuffer pwBuffer     = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8);
            IBuffer saltBuffer   = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf16LE);
            IBuffer cipherBuffer = CryptographicBuffer.CreateFromByteArray(encryptedData);
            KeyDerivationAlgorithmProvider keyDerivationProvider = Windows.Security.Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_ SHA1");
            KeyDerivationParameters        pbkdf2Parms           = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000);
            CryptographicKey keyOriginal              = keyDerivationProvider.CreateKey(pwBuffer);
            IBuffer          keyMaterial              = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32);
            CryptographicKey derivedPwKey             = keyDerivationProvider.CreateKey(pwBuffer);
            IBuffer          saltMaterial             = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16);
            string           keyMaterialString        = CryptographicBuffer.EncodeToBase64String(keyMaterial);
            string           saltMaterialString       = CryptographicBuffer.EncodeToBase64String(saltMaterial);
            SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7");
            CryptographicKey symmKey      = symProvider.CreateSymmetricKey(keyMaterial);
            IBuffer          resultBuffer = CryptographicEngine.Decrypt(symmKey, cipherBuffer, saltMaterial);
            string           result       = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, resultBuffer);

            return(result);
        }