简体   繁体   中英

C# TripleDESCryptoServiceProvider - how it is possible that it can work with short key

I'm trying to port following code to java, but wondering how this can work in C#. Provider is being initialized with keySize = 192, but key is only 16 bytes long. When doing this in java I got error about incorrect key size.

Can someone explain what is going on here?

public static byte[] TripleDesEncryptOneBlock(byte[] plainText)
{
    //This is key of length 16 bytes (128 bits)
    byte[] key = Encoding.ASCII.GetBytes("0123456789abcdef");
    byte[] result;
    try
    {
        int count = (plainText.Length > 8) ? 8 : plainText.Length;
        byte[] array = new byte[8];
        Buffer.BlockCopy(plainText, 0, array, 0, count);
        ICryptoTransform cryptoTransform = new TripleDESCryptoServiceProvider
        {
            KeySize = 192,
            Key = key,
            Mode = CipherMode.ECB,
            Padding = PaddingMode.None
        }.CreateEncryptor();
        byte[] array2 = cryptoTransform.TransformFinalBlock(array, 0, 8);
        result = array2;
    }
    catch (Exception)
    {
        result = null;
    }
    return result;
}

It's copying the first 8 bytes of the key to the end of the key. The TDEA standard calls this "keying option 2", and it only provides 80 bits of effective security (that is, it's a weak cipher).

Many Java providers won't do this automatically; by forcing the application to do it explicitly, unsuspecting fallback to a weaker scheme is less likely.

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