简体   繁体   中英

C# encryption/decryption

I am trying to create a simple system that encrypts strings, converts the encrypted byte array to a string and stores it in the database. Later on, the values can be retrieved from the database (as strings), comverted to byte arrays, decrypted and then converted to strings again. I am also using a 256 bit key. However, I seem to be doing something wrong and I am not familiar enough with the concept to come up with a fix.

Encryption code:

private static string EncryptString(SymmetricAlgorithm symAlg, string inString)
{
    byte[] inBlock = Encoding.Unicode.GetBytes(inString);
    ICryptoTransform xfrm = symAlg.CreateEncryptor();
    return Convert.ToBase64String(xfrm.TransformFinalBlock(inBlock, 0, inBlock.Length));
}

Decryption code:

private static byte[] DecryptString(SymmetricAlgorithm symAlg, string inBytes)
{
    ICryptoTransform xfrm = symAlg.CreateDecryptor();
    return xfrm.TransformFinalBlock(Convert.FromBase64String(inBytes), 0, inBytes.Length);
}

The error I am getting when decrypting:

System.ArgumentOutOfRangeException: Attempt to transform beyond end of buffer.
Parameter name: inputCount
at
System.Security.Cryptography.CapiSymmetricAlgorithm.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
at
CDMEncryptionLibrary.SyncEncryption.SecureCDM.DecryptString(SymmetricAlgorithm symAlg, String inBytes)

I understand that the problem is the conversion from and to bytes but how can I solve it?

--Edit

Decryption code is now:

    private static string DecryptString(SymmetricAlgorithm symAlg, string inBytesString)
    {

        var inBytes = Convert.FromBase64String(inBytesString);
        ICryptoTransform xfrm = symAlg.CreateDecryptor();
        byte[] outBlock= xfrm.TransformFinalBlock(inBytes, 0, inBytes.Length);
        return Encoding.Unicode.GetString(outBlock);
    }

with error The input data is not a complete block.

You are passing the length of the String , not the length of the byte array you convert the String to.

Ie You pass Convert.FromBase64String(inBytes) as the first parameter but inBytes.Length as the last. Simply convert before taking the length;

private static byte[] DecryptString(SymmetricAlgorithm symAlg, string inBytes)
{
    ICryptoTransform xfrm = symAlg.CreateDecryptor();
    return xfrm.TransformFinalBlock(Convert.FromBase64String(inBytes), 0, Convert.FromBase64String(inBytes).Length);
}

or to be more readable;

private static byte[] DecryptString(SymmetricAlgorithm symAlg, string inBytesString)
{
    var inBytes = Convert.FromBase64String(inBytesString);
    ICryptoTransform xfrm = symAlg.CreateDecryptor();
    return xfrm.TransformFinalBlock(inBytes, 0, inBytes.Length);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM