public static byte[] Decrypt( byte[] encryptedData, byte[] pass, byte[] salt, CryptConfigFileHelperScryptParameters scryptParameters = null) { if (encryptedData == null || pass == null || salt == null) { throw new ArgumentNullException(); } var keyIvGenerated = GenKeyAndIv(pass, salt, scryptParameters); try { return(keyIvGenerated.DecryptData(encryptedData)); } catch (EnumException <AesKeyIvPair.EDecryptDataErrCodes> enumExc) { if (enumExc.ExceptionCode == AesKeyIvPair.EDecryptDataErrCodes.WrongKey) { throw EnumException.Create(EDecryptErrCodes.WrongPassword, innerException: enumExc); } throw; } }
public T1 GetValue <T1>( byte[] pass, CryptConfigFileHelperScryptParameters scryptParameters = null ) { try { return(Encoding.UTF8.GetString(CryptConfigFileHelper.Decrypt( EncryptedData, pass, Salt, scryptParameters )).ParseJsonToType <T1>()); } catch (EnumException <CryptConfigFileHelper.EDecryptErrCodes> enumExc) { if (enumExc.ExceptionCode == CryptConfigFileHelper.EDecryptErrCodes.WrongPassword) { throw EnumException.Create( EGetValueT1ErrCodes.WrongPassword, innerException: enumExc ); } throw; } }
public byte[] DecryptData( byte[] encryptedData ) { var key = Key; Assert.NotNull(key); var iv = Iv; Assert.NotNull(iv); using (var aesAlg = new AesManaged()) { aesAlg.Key = key; aesAlg.IV = iv; ICryptoTransform decryptor = aesAlg.CreateDecryptor( aesAlg.Key, aesAlg.IV ); /**/ using (var input = new MemoryStream(encryptedData)) { using (var output = new MemoryStream( encryptedData.Length + 32) ) { using (var disposableBuffer = new TempByteArray(4096)) { var buffer = disposableBuffer.Data; try { using ( var csDecrypt = new CryptoStream( input, decryptor, CryptoStreamMode.Read ) ) { var read = csDecrypt.Read(buffer, 0, buffer.Length); while (read > 0) { output.Write(buffer, 0, read); read = csDecrypt.Read(buffer, 0, buffer.Length); } } } catch (CryptographicException cryptExc) { throw EnumException.Create( EDecryptDataErrCodes.WrongKey, innerException: cryptExc ); } } var totalLength = (int)output.Length; if (totalLength < 32) { throw EnumException.Create( EDecryptDataErrCodes.WrongEncryptedDataLength); } output.Seek(0, SeekOrigin.Begin); using ( var reader = new EndianBinaryReader( _littleConverter, output ) ) { using ( var tempDataHash = new TempByteArray( reader.ReadBytesOrThrow(32) ) ) { var data = reader.ReadBytesOrThrow(totalLength - 32); using (var mySha256 = new SHA256Managed()) { var computedDataHash = mySha256.ComputeHash(data); if ( tempDataHash.Data.SequenceEqual( computedDataHash ) ) { return(data); } } throw EnumException.Create( EDecryptDataErrCodes.WrongDecryptedDataHash ); } } } } } }