CryptographyUtility Class

Provides methods for performing common cryptography operations.

Namespace

System.Net.Security

Assembly

System.Net.Primitives.dll

Remarks

The CryptographyUtility class offers static methods for encoding and decoding data using various cryptographic algorithms. It is particularly useful for handling security-related operations in network applications.

Methods

Name Description
HashData(byte[] data) Computes the SHA-256 hash of the input data.
EncryptData(byte[] data, byte[] key) Encrypts the input data using AES-256 encryption with the provided key.
DecryptData(byte[] encryptedData, byte[] key) Decrypts the input encrypted data using AES-256 decryption with the provided key.
Base64Encode(byte[] data) Encodes the input byte array into a Base64 string.
Base64Decode(string base64String) Decodes a Base64 string into a byte array.

Example Usage

The following C# example demonstrates how to use the CryptographyUtility class to hash and encrypt data.


using System;
using System.Net.Security;

public class Example {
    public static void Main(string[] args) {
        // Sample data
        byte[] originalData = { 0x01, 0x02, 0x03, 0x04, 0x05 };
        byte[] encryptionKey = GenerateRandomKey(); // In a real scenario, manage keys securely

        // Hashing
        byte[] hash = CryptographyUtility.HashData(originalData);
        Console.WriteLine($"SHA-256 Hash: {BitConverter.ToString(hash).Replace("-", "")}");

        // Encryption
        byte[] encryptedData = CryptographyUtility.EncryptData(originalData, encryptionKey);
        Console.WriteLine($"Encrypted Data (Hex): {BitConverter.ToString(encryptedData).Replace("-", "")}");

        // Decryption
        byte[] decryptedData = CryptographyUtility.DecryptData(encryptedData, encryptionKey);
        Console.WriteLine($"Decrypted Data (Hex): {BitConverter.ToString(decryptedData).Replace("-", "")}");

        // Base64 Encoding and Decoding
        string base64Encoded = CryptographyUtility.Base64Encode(originalData);
        Console.WriteLine($"Base64 Encoded: {base64Encoded}");

        byte[] base64Decoded = CryptographyUtility.Base64Decode(base64Encoded);
        Console.WriteLine($"Base64 Decoded (Hex): {BitConverter.ToString(base64Decoded).Replace("-", "")}");
    }

    private static byte[] GenerateRandomKey() {
        // In a real application, use a secure cryptographically random number generator
        return new byte[32]; // For AES-256
    }
}
            

Related Topics