如何使用Postgres加密并使用C#解密?

时间:2019-04-07 16:31:58

标签: c# postgresql encryption

我在postgres中加密密码 而且我想用C#解密,但是两种方法无法匹配 我该怎么办?

cmake -G "Visual Studio 15" .\src -o .\build

我找到了一种使用pgcrypto在postgres中加密的方法。 下面是postgres中的加密和解密。

private static byte[] TruncateHash(string key, int length)
{
    SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
    // Hash the key.
    byte[] keyBytes = System.Text.Encoding.Unicode.GetBytes(key);
    byte[] hash = sha1.ComputeHash(keyBytes);

    // Truncate or pad the hash.
    Array.Resize(ref hash, length);
    return hash;
}

public static string EncryptString(string plaintext, string Passphrase)
{
    TripleDESCryptoServiceProvider tripleDes = new TripleDESCryptoServiceProvider();
    // Initialize the crypto provider.
    tripleDes.Key = TruncateHash(Passphrase, tripleDes.KeySize / 8);
    tripleDes.IV = TruncateHash("", tripleDes.BlockSize / 8);

    // Convert the plaintext string to a byte array.
    byte[] plaintextBytes = System.Text.Encoding.Unicode.GetBytes(plaintext);

    // Create the stream.
    System.IO.MemoryStream ms = new System.IO.MemoryStream();
    // Create the encoder to write to the stream.
    CryptoStream encStream = new CryptoStream(ms, tripleDes.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);

    // Use the crypto stream to write the byte array to the stream.
    encStream.Write(plaintextBytes, 0, plaintextBytes.Length);
    encStream.FlushFinalBlock();

    // Convert the encrypted stream to a printable string.
    return Convert.ToBase64String(ms.ToArray());
}

public static string DecryptString(string encryptedtext, string Passphrase)
{
    TripleDESCryptoServiceProvider tripleDes = new TripleDESCryptoServiceProvider();
    // Initialize the crypto provider.
    tripleDes.Key = TruncateHash(Passphrase, tripleDes.KeySize / 8);
    tripleDes.IV = TruncateHash("", tripleDes.BlockSize / 8);
    // Convert the encrypted text string to a byte array.
    byte[] encryptedBytes = Convert.FromBase64String(encryptedtext);

    // Create the stream.
    System.IO.MemoryStream ms = new System.IO.MemoryStream();
    // Create the decoder to write to the stream.
    CryptoStream decStream = new CryptoStream(ms, tripleDes.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);

    // Use the crypto stream to write the byte array to the stream.
    decStream.Write(encryptedBytes, 0, encryptedBytes.Length);
    decStream.FlushFinalBlock();

    // Convert the plaintext stream to a string.
    return System.Text.Encoding.Unicode.GetString(ms.ToArray());
}

我的代码有什么问题,c#和postgres无法匹配。 我想保留c#代码并将postgres代码更改为匹配

0 个答案:

没有答案