Пример #1
0
        private static byte[] Decrypt(NppCryptCipherParams cipher, byte[] encryptedData, string password)
        {
            if (cipher.Encryption.Cipher != "rijndael")
            {
                throw new Exception($"Cipher algorithm \"{cipher.Encryption.Cipher}\" is not supported now. " +
                                    "Only \"rijndael\" algorithm might be used in the current version");
            }

            if (cipher.Encryption.Mode != CipherMode.CBC)
            {
                throw new Exception($"Cipher algorithm mode \"{cipher.Encryption.Mode}\" is not supported now. " +
                                    $"Only \"{nameof(CipherMode.CBC)}\" mode might be used in the current version");
            }


            if (cipher.Key.Algorithm != "scrypt")
            {
                throw new Exception($"Key hashing algorithm \"{cipher.Key.Algorithm}\" is not supported now. " +
                                    "Only \"scrypt\" algorithm might be used in the current version");
            }

            if (!cipher.Key.N.HasValue)
            {
                throw new Exception($"Parameter '{nameof(cipher.Key.N)}' of key hashing algorithm is not set");
            }
            if (!cipher.Key.R.HasValue)
            {
                throw new Exception($"Parameter '{nameof(cipher.Key.R)}' of key hashing algorithm is not set");
            }
            if (!cipher.Key.P.HasValue)
            {
                throw new Exception($"Parameter '{nameof(cipher.Key.P)}' of key hashing algorithm is not set");
            }
            if (cipher.Key.Salt == null)
            {
                throw new Exception($"Parameter '{nameof(cipher.Key.Salt)}' of key hashing algorithm is not set");
            }

            var key = ScryptEncoder.CryptoScrypt(Encoding.UTF8.GetBytes(password), cipher.Key.Salt,
                                                 cipher.Key.N.Value, cipher.Key.R.Value, cipher.Key.P.Value, cipher.Encryption.KeyLength ?? 32);

            using Rijndael rijAlg = Rijndael.Create();
            rijAlg.Key            = key;
            rijAlg.IV             = cipher.Iv.Value;
            rijAlg.Mode           = cipher.Encryption.Mode;

            using var ms = new MemoryStream();
            using var cs = new CryptoStream(ms, rijAlg.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(encryptedData, 0, encryptedData.Length);
            cs.Close();
            var res = ms.ToArray();

            ms.Close();
            return(res);
        }