예제 #1
0
 public static Memory <byte> EasyDecrypt(ReadOnlyMemory <byte> src, string?password = null)
 {
     if (password._IsNullOrZeroLen())
     {
         password = Consts.Strings.EasyEncryptDefaultPassword;
     }
     return(ChaChaPoly.EasyDecryptWithPassword(src, password));
 }
예제 #2
0
        protected override async Task InitMetadataImplAsync(CancellationToken cancel = default)
        {
            Memory <byte> firstSectorData = new byte[XtsAesMetaDataSize];

            // ヘッダの読み込みを試行する
            int readSize = await this.PhysicalReadAsync(0, firstSectorData, cancel);

            if (readSize == XtsAesMetaDataSize)
            {
                var metaDataParseResult = TryParseMetaData(firstSectorData);

                metaDataParseResult.ThrowIfException();

                var metaData = metaDataParseResult.Value !;

                // パスワード検査
                if (Secure.VeritySaltedPassword(metaData.SaltedPassword, this.CurrentPassword) == false)
                {
                    throw new CoresException("XtsAesRandomAccess: Incorrect password.");
                }

                // 秘密鍵解読
                var decrypted = ChaChaPoly.EasyDecryptWithPassword(metaData.MasterKeyEncryptedByPassword._GetHexBytes(), this.CurrentPassword);
                decrypted.ThrowIfException();

                // 秘密鍵サイズ検査
                if (decrypted.Value.Length != XtsAesKeySize)
                {
                    throw new CoresException("XtsAesRandomAccess: decrypted.Value.Length != XtsAesKeySize");
                }

                this.CurrentMasterKey = decrypted.Value;

                this.CurrentMetaData = metaData;
            }
            else if (readSize == 0)
            {
                // ファイルの内容が存在しない

                // マスターキーを新規作成する
                this.CurrentMasterKey = Secure.Rand(XtsAesKeySize);

                // メタデータを新規作成する
                var metaData = new XtsAesRandomAccessMetaData
                {
                    Version        = 1,
                    VirtualSize    = 0,
                    SaltedPassword = Secure.SaltPassword(this.CurrentPassword),
                    MasterKeyEncryptedByPassword = ChaChaPoly.EasyEncryptWithPassword(this.CurrentMasterKey, this.CurrentPassword)._GetHexString(),
                };

                this.CurrentMetaData = metaData;

                // メタデータを書き込みする
                await WriteMetaDataAsync(cancel);
            }
            else
            {
                // 不正 ここには来ないはず
                throw new CoresException($"XtsAesRandomAccess: Invalid readSize: {readSize}");
            }

            // XTS を作成
            this.CurrentXts        = XtsAes256.Create(this.CurrentMasterKey.ToArray());
            this.CurrentEncrypter  = this.CurrentXts.CreateEncryptor();
            this.CurrentDescrypter = this.CurrentXts.CreateDecryptor();
        }