protected override void ProcessRecord() { var nonce = SecretBox.GenerateNonce(); var privateKey = PrivateKey.ToByteArrayFromBase64String(); var publicKey = PublicKey.ToByteArrayFromBase64String(); if (ParameterSetName == "File") { if (ReplaceFile.IsTrue()) OutFile = Path.GetTempFileName(); using (ICryptoTransform transform = new SodiumCryptoTransform(nonce, privateKey, publicKey, SodiumCryptoTransform.Direction.Encrypt)) using (FileStream destination = new FileStream(OutFile, FileMode.CreateNew, FileAccess.Write, FileShare.None)) using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write)) using (FileStream source = new FileStream(File, FileMode.Open, FileAccess.Read, FileShare.Read)) { source.CopyTo(cryptoStream); cryptoStream.FlushFinalBlock(); destination.Write(nonce, 0, nonce.Length); destination.Flush(); } if (ReplaceFile.IsTrue()) { System.IO.File.Delete(File); System.IO.File.Move(OutFile, File); } } else { var encryptedMessage = PublicKeyBox.Create(rawMessage, nonce, privateKey, publicKey); var results = new EncryptedMessage() { EncryptedType = "Asymetric", Message = NoCompression.IsTrue() ? encryptedMessage.ToBase64String() : encryptedMessage.Compress(), Nonce = nonce.ToBase64String(), Compressed = !NoCompression }; WriteObject(results); } }
protected override void ProcessRecord() { var key = Key.ToByteArrayFromBase64String(); if (ParameterSetName == "File") { if (ReplaceFile.IsTrue()) OutFile = Path.GetTempFileName(); using (ICryptoTransform transform = new SodiumCryptoTransform(nonce, key, SodiumCryptoTransform.Direction.Encrypt, algo)) using (FileStream destination = new FileStream(OutFile, FileMode.CreateNew, FileAccess.Write, FileShare.None)) using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write)) using (FileStream source = new FileStream(File, FileMode.Open, FileAccess.Read, FileShare.Read)) { source.CopyTo(cryptoStream); cryptoStream.FlushFinalBlock(); destination.Write(nonce, 0, nonce.Length); destination.Flush(); } if (ReplaceFile.IsTrue()) { System.IO.File.Delete(File); System.IO.File.Move(OutFile, File); } } else { byte[] encryptedMessage = null; switch (algo) { case SodiumCryptoTransform.SymmetricAlgorithm.ChaCha20: encryptedMessage = StreamEncryption.EncryptChaCha20(rawMessage, nonce, key); break; case SodiumCryptoTransform.SymmetricAlgorithm.XSalsa: encryptedMessage = StreamEncryption.Encrypt(rawMessage, nonce, key); break; case SodiumCryptoTransform.SymmetricAlgorithm.Default: default: encryptedMessage = SecretBox.Create(rawMessage, nonce, key); break; } var results = new EncryptedMessage() { EncryptedType = algo.GetDescription(), Message = NoCompression.IsTrue() ? encryptedMessage.ToBase64String() : encryptedMessage.Compress(), Nonce = nonce.ToBase64String(), Compressed = !NoCompression }; WriteObject(results); } }