/// <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); }
public void AES_Encrypt_Decrypt_Test() { var password = CryptoUtils.BrewPassword(10).ToSecureString(); var testData = "Test Test Hello"; var encrypted = Aes.Encrypt(password, testData); var decrypted = Encoding.UTF8.GetString(Aes.Decrypt(password, encrypted)); Assert.AreEqual(testData, decrypted); }