/// <summary> /// Creates instance from encrypted data. /// </summary> /// <param name="encryptedData">Encrypted data to be decrypted.</param> /// <param name="password">Password to generate key to encrypt and decrypt.</param> /// <param name="salt">Salt to generate key.</param> /// <param name="iterationCount">Iteration count to generate key.</param> /// <param name="keySize">Key size in bit.</param> /// <param name="cipherMode"><see cref="CipherMode"/>.</param> /// <param name="paddingMode"><see cref="PaddingMode"/>.</param> /// <returns>PBEProtectedString instance.</returns> public static PBEProtectedString FromEncryptedData(byte[] encryptedData, byte[] password, byte[] salt, int iterationCount = 4096, int keySize = 256, CipherMode cipherMode = CipherMode.CBC, PaddingMode paddingMode = PaddingMode.PKCS7) { var ps = new PBEProtectedString(keySize, cipherMode, paddingMode); ps.EncryptedData = encryptedData; ps.Salt = salt; ps.generateKey(password, iterationCount, BLOCK_SIZE); return(ps); }
/// <summary> /// Creates instance from char array. /// </summary> /// <param name="chars">Char array to be encrypted.</param> /// <param name="password">Password to generate key to encrypt and decrypt.</param> /// <param name="saltLenght">Salt length to generate key.</param> /// <param name="iterationCount">Iteration count to generate key.</param> /// <param name="keySize">Key size in bit.</param> /// <param name="cipherMode"><see cref="CipherMode"/>.</param> /// <param name="paddingMode"><see cref="PaddingMode"/>.</param> /// <returns>PBEProtectedString instance.</returns> public static PBEProtectedString FromChars(char[] chars, byte[] password, int saltLenght = 128, int iterationCount = 4096, int keySize = 256, CipherMode cipherMode = CipherMode.CBC, PaddingMode paddingMode = PaddingMode.PKCS7) { var ps = new PBEProtectedString(keySize, cipherMode, paddingMode); if (saltLenght > 0) { ps.Salt = RAND.NextBytes(saltLenght); } ps.generateKey(password, iterationCount, BLOCK_SIZE); using (var aes = Aes.Create()) { aes.KeySize = ps.keySize; aes.BlockSize = BLOCK_SIZE; aes.Mode = ps.cipherMode; aes.Padding = ps.paddingMode; aes.Key = ps.key; aes.IV = ps.iv; using (var memory = new MemoryStream()) { using (var encryptor = aes.CreateEncryptor()) using (var stream = new CryptoStream(memory, encryptor, CryptoStreamMode.Write)) using (var writer = new StreamWriter(stream, ENCODING)) { writer.Write(chars); } ps.EncryptedData = memory.ToArray(); } } return(ps); }