溫馨提示×

如何在c#中實現(xiàn)numeric類型的數(shù)據(jù)加密

c#
小樊
83
2024-08-28 16:59:11
欄目: 編程語言

在C#中實現(xiàn)numeric類型的數(shù)據(jù)加密,可以使用加密算法對數(shù)字進行加密和解密

  1. 首先,安裝System.Security.Cryptography包:
dotnet add package System.Security.Cryptography
  1. 創(chuàng)建一個名為NumericEncryption的類,并添加以下代碼:
using System;
using System.Numerics;
using System.Security.Cryptography;

public class NumericEncryption
{
    private readonly RSA _rsa;

    public NumericEncryption()
    {
        _rsa = RSA.Create();
    }

    public byte[] Encrypt(BigInteger number)
    {
        var dataToEncrypt = number.ToByteArray();
        return _rsa.Encrypt(dataToEncrypt, RSAEncryptionPadding.OaepSHA256);
    }

    public BigInteger Decrypt(byte[] encryptedData)
    {
        var decryptedData = _rsa.Decrypt(encryptedData, RSAEncryptionPadding.OaepSHA256);
        return new BigInteger(decryptedData);
    }
}
  1. 使用NumericEncryption類加密和解密numeric類型的數(shù)據(jù):
using System;

class Program
{
    static void Main(string[] args)
    {
        var numericEncryption = new NumericEncryption();

        // 要加密的數(shù)字
        BigInteger number = 12345678901234567890;

        // 加密數(shù)字
        byte[] encryptedNumber = numericEncryption.Encrypt(number);
        Console.WriteLine($"Encrypted number: {Convert.ToBase64String(encryptedNumber)}");

        // 解密數(shù)字
        BigInteger decryptedNumber = numericEncryption.Decrypt(encryptedNumber);
        Console.WriteLine($"Decrypted number: {decryptedNumber}");
    }
}

這個示例使用RSA加密算法對大整數(shù)進行加密和解密。請注意,加密后的數(shù)據(jù)是二進制格式,因此在輸出時將其轉(zhuǎn)換為Base64字符串以便于閱讀。在實際應(yīng)用中,您可能需要根據(jù)需求調(diào)整加密算法和密鑰長度。

0