Skip to content

Commit

Permalink
src: Fix weird empty line spacing.
Browse files Browse the repository at this point in the history
  • Loading branch information
samuel-lucas6 committed Aug 11, 2024
1 parent 57e7236 commit ff0570a
Show file tree
Hide file tree
Showing 19 changed files with 94 additions and 94 deletions.
16 changes: 8 additions & 8 deletions src/Kryptor/AsymmetricCryptography/AsymmetricKeys.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,11 @@ public static class AsymmetricKeys
public static (string publicKey, string privateKey) GenerateEncryptionKeyPair(Span<byte> passphrase)
{
passphrase = PassphrasePrompt.GetNewPassphrase(passphrase);

Span<byte> publicKey = stackalloc byte[X25519.PublicKeySize];
Span<byte> privateKey = stackalloc byte[X25519.PrivateKeySize];
X25519.GenerateKeyPair(publicKey, privateKey);

Span<byte> fullPublicKey = stackalloc byte[Constants.Curve25519KeyHeader.Length + publicKey.Length];
Spans.Concat(fullPublicKey, Constants.Curve25519KeyHeader, publicKey);
Span<byte> encryptedPrivateKey = PrivateKey.Encrypt(privateKey, passphrase, Constants.Curve25519KeyHeader);
Expand All @@ -41,11 +41,11 @@ public static (string publicKey, string privateKey) GenerateEncryptionKeyPair(Sp
public static (string publicKey, string privateKey) GenerateSigningKeyPair(Span<byte> passphrase)
{
passphrase = PassphrasePrompt.GetNewPassphrase(passphrase);

Span<byte> publicKey = stackalloc byte[Ed25519.PublicKeySize];
Span<byte> privateKey = stackalloc byte[Ed25519.PrivateKeySize];
Ed25519.GenerateKeyPair(publicKey, privateKey);

Span<byte> fullPublicKey = stackalloc byte[Constants.Ed25519KeyHeader.Length + publicKey.Length];
Spans.Concat(fullPublicKey, Constants.Ed25519KeyHeader, publicKey);
Span<byte> encryptedPrivateKey = PrivateKey.Encrypt(privateKey, passphrase, Constants.Ed25519KeyHeader);
Expand Down Expand Up @@ -94,12 +94,12 @@ public static string ReadKeyFileComment(string filePath, int stringKeyLength)
string comment = File.ReadAllText(filePath).TrimStart();
return comment.Remove(startIndex: 0, stringKeyLength).TrimStart();
}

public static Span<byte> GetCurve25519PublicKey(Span<byte> privateKey)
{
Span<byte> publicKey = stackalloc byte[X25519.PublicKeySize];
X25519.ComputePublicKey(publicKey, privateKey);

Span<byte> fullPublicKey = new byte[Constants.Curve25519KeyHeader.Length + publicKey.Length];
Spans.Concat(fullPublicKey, Constants.Curve25519KeyHeader, publicKey);
return fullPublicKey;
Expand All @@ -109,9 +109,9 @@ public static Span<byte> GetEd25519PublicKey(Span<byte> privateKey)
{
Span<byte> publicKey = stackalloc byte[Ed25519.PublicKeySize];
Ed25519.ComputePublicKey(publicKey, privateKey);

Span<byte> fullPublicKey = new byte[Constants.Ed25519KeyHeader.Length + publicKey.Length];
Spans.Concat(fullPublicKey, Constants.Ed25519KeyHeader, publicKey);
return fullPublicKey;
}
}
}
4 changes: 2 additions & 2 deletions src/Kryptor/AsymmetricCryptography/PrivateKey.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public static Span<byte> Decrypt(Span<byte> privateKey, Span<byte> passphrase)
Span<byte> associatedData = privateKey[..(Constants.Curve25519KeyHeader.Length + Constants.PrivateKeyVersion.Length)];
Span<byte> salt = privateKey.Slice(associatedData.Length, Argon2id.SaltSize);
Span<byte> encryptedPrivateKey = privateKey[(associatedData.Length + salt.Length)..];

Span<byte> nonce = stackalloc byte[ChaCha20.NonceSize]; nonce.Clear();
Span<byte> key = stackalloc byte[ChaCha20.KeySize];
Argon2id.DeriveKey(key, passphrase, salt, Constants.Iterations, Constants.MemorySize);
Expand All @@ -72,4 +72,4 @@ public static Span<byte> Decrypt(Span<byte> privateKey, Span<byte> passphrase)
throw new CryptographicException("Incorrect passphrase, or the private key has been tampered with.", ex);
}
}
}
}
12 changes: 6 additions & 6 deletions src/Kryptor/DigitalSignatures/DigitalSignatures.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,14 @@ public static void SignFile(string filePath, string signaturePath, string commen
Span<byte> fileBytes = GetFileBytes(filePath, prehash);
Span<byte> fileSignature = stackalloc byte[Ed25519.SignatureSize];
Ed25519.Sign(fileSignature, fileBytes, privateKey);

Span<byte> commentBytes = Encoding.UTF8.GetBytes(comment);
Span<byte> signatureFileBytes = new byte[Constants.SignatureMagicBytes.Length + Constants.SignatureVersion.Length + prehashed.Length + fileSignature.Length + commentBytes.Length];
Spans.Concat(signatureFileBytes, Constants.SignatureMagicBytes, Constants.SignatureVersion, prehashed, fileSignature, commentBytes);

Span<byte> globalSignature = stackalloc byte[Ed25519.SignatureSize];
Ed25519.Sign(globalSignature, signatureFileBytes, privateKey);

CreateSignatureFile(signaturePath, signatureFileBytes, globalSignature);
}

Expand Down Expand Up @@ -70,13 +70,13 @@ private static void CreateSignatureFile(string signaturePath, Span<byte> signatu
public static bool VerifySignature(string signaturePath, string filePath, Span<byte> publicKey, out string comment)
{
Span<byte> signatureFileBytes = File.ReadAllBytes(signaturePath);

Span<byte> globalSignature = signatureFileBytes[^Ed25519.SignatureSize..];
if (!Ed25519.Verify(globalSignature, signatureFileBytes[..^globalSignature.Length], publicKey)) {
comment = string.Empty;
return false;
}

Span<byte> prehashed = signatureFileBytes.Slice(Constants.SignatureMagicBytes.Length + Constants.SignatureVersion.Length, Constants.BoolBytesLength);
bool prehash = BitConverter.ToBoolean(prehashed);
Span<byte> fileBytes = GetFileBytes(filePath, prehash);
Expand All @@ -86,4 +86,4 @@ public static bool VerifySignature(string signaturePath, string filePath, Span<b
comment = Encoding.UTF8.GetString(commentBytes);
return Ed25519.Verify(fileSignature, fileBytes, publicKey);
}
}
}
4 changes: 2 additions & 2 deletions src/Kryptor/DigitalSignatures/FileSigning.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ private static void SignDirectoryFiles(string directoryPath, string comment, boo
}
Console.WriteLine();
}

public static void VerifyEachFile(string[] signaturePaths, string[] filePaths, Span<byte> publicKey)
{
if (filePaths == null || publicKey.Length == 0) {
Expand Down Expand Up @@ -115,4 +115,4 @@ public static void VerifyEachFile(string[] signaturePaths, string[] filePaths, S
}
}
}
}
}
6 changes: 3 additions & 3 deletions src/Kryptor/FileEncryption/DecryptFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,15 @@ public static void Decrypt(FileStream inputFile, string outputFilePath, Span<byt
int fileNameLength = Padding.GetUnpaddedLength(fileName, fileName.Length);
bool isDirectory = BitConverter.ToBoolean(header[^Constants.BoolBytesLength..]);
CryptographicOperations.ZeroMemory(header);

using (var outputFile = new FileStream(outputFilePath, FileHandling.GetFileStreamWriteOptions(inputFile.Length - Constants.FileHeadersLength)))
{
ConstantTime.Increment(nonce[..^1]);
DecryptChunks(inputFile, outputFile, plaintextLength, nonce, fileKey);
CryptographicOperations.ZeroMemory(fileKey);
}
inputFile.Dispose();

if (fileNameLength > 0) {
outputFilePath = FileHandling.RenameFile(outputFilePath, Encoding.UTF8.GetString(fileName[..fileNameLength]));
}
Expand Down Expand Up @@ -110,4 +110,4 @@ private static void DecryptChunks(Stream inputFile, Stream outputFile, long plai
}
outputFile.SetLength(plaintextLength);
}
}
}
12 changes: 6 additions & 6 deletions src/Kryptor/FileEncryption/EncryptFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,14 @@ public static void Encrypt(string inputFilePath, string outputFilePath, bool isD
lastChunkPadding = Constants.FileChunkSize;
}
long payloadLength = chunkCount * Constants.CiphertextChunkSize - (Constants.FileChunkSize - lastChunkPadding);

using var outputFile = new FileStream(outputFilePath, FileHandling.GetFileStreamWriteOptions(Constants.FileHeadersLength + payloadLength));
Span<byte> nonce = stackalloc byte[ChaCha20.NonceSize]; nonce.Clear();
Span<byte> encryptedHeader = EncryptFileHeader(inputFile.Length, Path.GetFileName(inputFilePath), isDirectory, nonce, fileKey, wrappedFileKeys);
outputFile.Write(unencryptedHeader);
outputFile.Write(wrappedFileKeys);
outputFile.Write(encryptedHeader);

ConstantTime.Increment(nonce[..^1]);
EncryptChunks(inputFile, outputFile, (int)chunkCount, (int)lastChunkPadding, nonce, fileKey);
CryptographicOperations.ZeroMemory(fileKey);
Expand Down Expand Up @@ -81,7 +81,7 @@ private static long GetRandomPaddingLength(long unpaddedLength, double proportio
double coefficient = Math.Log(Math.Pow(2, 32)) - Math.Log(random1 + random2 * Math.Pow(2, -32) + Math.Pow(2, -33));
return fixedPadding + (long)Math.Round(coefficient * proportion * effectiveSize);
}

private static Span<byte> EncryptFileHeader(long fileLength, string fileName, bool isDirectory, Span<byte> nonce, Span<byte> fileKey, Span<byte> associatedData)
{
Span<byte> plaintextLength = stackalloc byte[Constants.Int64BytesLength];
Expand All @@ -91,7 +91,7 @@ private static Span<byte> EncryptFileHeader(long fileLength, string fileName, bo
Span<byte> directory = BitConverter.GetBytes(isDirectory);
Span<byte> plaintextHeader = stackalloc byte[Constants.EncryptedHeaderLength - Poly1305.TagSize - kcChaCha20Poly1305.CommitmentSize];
Spans.Concat(plaintextHeader, plaintextLength, paddedFileName, spare, directory);

Span<byte> ciphertextHeader = new byte[Constants.EncryptedHeaderLength];
kcChaCha20Poly1305.Encrypt(ciphertextHeader, plaintextHeader, nonce, fileKey, associatedData);
CryptographicOperations.ZeroMemory(plaintextHeader);
Expand All @@ -105,7 +105,7 @@ private static Span<byte> GetPaddedFileName(string fileName)
Padding.Fill(paddedFileName);
return paddedFileName;
}

Span<byte> fileNameBytes = new byte[Encoding.UTF8.GetMaxByteCount(fileName.Length)];
int bytesEncoded = Encoding.UTF8.GetBytes(fileName, fileNameBytes);
if (bytesEncoded > paddedFileName.Length - 1) {
Expand Down Expand Up @@ -139,4 +139,4 @@ private static void EncryptChunks(Stream inputFile, Stream outputFile, int chunk
}
CryptographicOperations.ZeroMemory(plaintextChunk);
}
}
}
26 changes: 13 additions & 13 deletions src/Kryptor/GeneralPurpose/FileHandling.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ public static class FileHandling
return null;
}
}

public static string TrimTrailingSeparatorChars(string filePath) => filePath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar, Path.VolumeSeparatorChar);

public static string ReplaceFileName(string filePath, string newFileName)
{
string directoryPath = Path.GetDirectoryName(Path.GetFullPath(filePath));
Expand All @@ -48,7 +48,7 @@ public static string ReplaceFileName(string filePath, string newFileName)
}
return newPath;
}

public static FileStreamOptions GetFileStreamReadOptions(string filePath)
{
long fileLength = new FileInfo(filePath).Length;
Expand All @@ -61,7 +61,7 @@ public static FileStreamOptions GetFileStreamReadOptions(string filePath)
Options = fileLength < 10737418240 ? FileOptions.None : FileOptions.SequentialScan
};
}

private static int GetFileStreamBufferSize(long fileLength)
{
return fileLength switch
Expand All @@ -72,7 +72,7 @@ private static int GetFileStreamBufferSize(long fileLength)
>= 104857600 => 1048576
};
}

public static FileStreamOptions GetFileStreamWriteOptions(long preAllocationSize)
{
return new FileStreamOptions
Expand All @@ -85,7 +85,7 @@ public static FileStreamOptions GetFileStreamWriteOptions(long preAllocationSize
PreallocationSize = preAllocationSize
};
}

public static void OverwriteFile(string fileToDelete, string fileToCopy)
{
try
Expand All @@ -99,7 +99,7 @@ public static void OverwriteFile(string fileToDelete, string fileToCopy)
DisplayMessage.FilePathException(fileToDelete, ex.GetType().Name, "Unable to overwrite the file.");
}
}

public static void DeleteFile(string filePath)
{
try
Expand All @@ -115,7 +115,7 @@ public static void DeleteFile(string filePath)
DisplayMessage.FilePathException(filePath, ex.GetType().Name, "Unable to delete the file.");
}
}

public static string GetUniqueFilePath(string filePath)
{
if (!File.Exists(filePath)) {
Expand All @@ -140,7 +140,7 @@ public static string RemoveFileNameNumber(string filePath)
int index = filePath.LastIndexOf(" (", StringComparison.Ordinal);
return filePath[..index];
}

public static string RenameFile(string filePath, string newFileName)
{
try
Expand All @@ -160,7 +160,7 @@ public static string RenameFile(string filePath, string newFileName)
return filePath;
}
}

public static void CreateZipFile(string directoryPath, string zipFilePath)
{
DisplayMessage.InputToOutput("Zipping", directoryPath, zipFilePath);
Expand All @@ -169,7 +169,7 @@ public static void CreateZipFile(string directoryPath, string zipFilePath)
DeleteDirectory(directoryPath);
}
}

private static void DeleteDirectory(string directoryPath)
{
try
Expand Down Expand Up @@ -202,7 +202,7 @@ public static void ExtractZipFile(string zipFilePath)
DisplayMessage.FilePathException(zipFilePath, ex.GetType().Name, "Unable to extract the file.");
}
}

private static string GetUniqueDirectoryPath(string directoryPath)
{
if (!Directory.Exists(directoryPath)) {
Expand All @@ -217,4 +217,4 @@ private static string GetUniqueDirectoryPath(string directoryPath)
} while (Directory.Exists(directoryPath));
return directoryPath;
}
}
}
16 changes: 8 additions & 8 deletions src/Kryptor/GlobalVariables/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,17 +28,17 @@ public static class Constants
{
// Error handling
public const int ErrorCode = -1;

// Key derivation
public const int Iterations = 3;
public const int MemorySize = 268435456;
public static readonly byte[] Personalisation = Encoding.UTF8.GetBytes("Kryptor.Personal");

// File encryption
public const string EncryptedExtension = ".bin";
public const string ZipFileExtension = ".zip";
public const int RandomFileNameLength = 16;

public const int UnencryptedHeaderLength = X25519.PublicKeySize + Argon2id.SaltSize;
public const int MaxRecipients = 20;
public const int KeyWrapHeaderLength = ChaCha20.KeySize * MaxRecipients;
Expand All @@ -50,14 +50,14 @@ public static class Constants
public const int FileHeadersLength = UnencryptedHeaderLength + KeyWrapHeaderLength + EncryptedHeaderLength;
public const int FileChunkSize = 16384;
public const int CiphertextChunkSize = FileChunkSize + Poly1305.TagSize;

// Symmetric keys
public const string KeyfileExtension = ".key";
public const int KeyfileLength = ChaCha20.KeySize;
public const char Base64Padding = '=';
public const int SymmetricKeyLength = 48;
public static readonly byte[] SymmetricKeyHeader = { 61, 34, 191 }; // "PSK/" in Base64

// Asymmetric keys
public static readonly string DefaultKeyDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".kryptor");
public const string DefaultEncryptionKeyFileName = "encryption";
Expand All @@ -68,17 +68,17 @@ public static class Constants
public static readonly string DefaultEncryptionPrivateKeyPath = Path.Combine(DefaultKeyDirectory, DefaultEncryptionKeyFileName + PrivateKeyExtension);
public static readonly string DefaultSigningPublicKeyPath = Path.Combine(DefaultKeyDirectory, DefaultSigningKeyFileName + PublicKeyExtension);
public static readonly string DefaultSigningPrivateKeyPath = Path.Combine(DefaultKeyDirectory, DefaultSigningKeyFileName + PrivateKeyExtension);

public const int PublicKeyLength = 48;
public const int EncryptionPrivateKeyLength = 136;
public const int SigningPrivateKeyLength = 180;
public static readonly byte[] Curve25519KeyHeader = { 10, 239, 255 }; // "Cu//" in Base64
public static readonly byte[] Ed25519KeyHeader = { 17, 223, 255 }; // "Ed//" in Base64
public static readonly byte[] PrivateKeyVersion = { 2, 0 };

// File signing
public const string SignatureExtension = ".signature";
public static readonly byte[] SignatureMagicBytes = Encoding.UTF8.GetBytes("SIGNATURE");
public static readonly byte[] SignatureVersion = { 1, 0 };
public const int MaxCommentLength = 500;
}
}
4 changes: 2 additions & 2 deletions src/Kryptor/GlobalVariables/ErrorMessages.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,6 @@ public static class ErrorMessages
public const string UnableToDecryptFile = "Unable to decrypt the file.";

public static string GetFilePathError(string filePath, string errorMessage) => $"\"{Path.GetFileName(FileHandling.TrimTrailingSeparatorChars(filePath))}\" - {errorMessage}";

public static string GetKeyStringError(string keyString, string errorMessage) => $"\"{keyString}\" - {errorMessage}";
}
}
2 changes: 1 addition & 1 deletion src/Kryptor/GlobalVariables/GlobalVariables.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,4 @@ public static class Globals
public static bool EncryptFileNames { get; set; }
public static int SuccessfulCount { get; set; }
public static int TotalCount { get; set; }
}
}
Loading

0 comments on commit ff0570a

Please sign in to comment.