Search code examples
c#encryptioncryptographyaespassword-encryption

CryptDeriveKey algorithm names


public byte[] CryptDeriveKey(
    string algname,
    string alghashname,
    int keySize,
    byte[] rgbIV
)

Can someone please enlighten me as to what options there are in algname? If I want to specify an encryption algorithm for AES-128 and AES-256, what should I put in the algname?


Solution

  • I'm not 100% sure but, algname is your algorithm name. keySize is size of the key.

    You should use AES-128 and AES-256 like this;

    CryptDeriveKey("AES", "SHA1", 128, aes.IV)
    

    and

    CryptDeriveKey("AES", "SHA1", 256, aes.IV)
    

    Check out for more details from MSDN.

    Here is a decompiled code for PasswordDeriveBytes.CryptDeriveKey method.

    [SecuritySafeCritical]
    public byte[] CryptDeriveKey(string algname, string alghashname, int keySize, byte[] rgbIV)
    {
        if (keySize < 0)
        {
            throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeySize"));
        }
        int algidHash = X509Utils.NameOrOidToAlgId(alghashname, OidGroup.HashAlgorithm);
        if (algidHash == 0)
        {
            throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_InvalidAlgorithm"));
        }
        int algid = X509Utils.NameOrOidToAlgId(algname, OidGroup.AllGroups);
        if (algid == 0)
        {
            throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_InvalidAlgorithm"));
        }
        if (rgbIV == null)
        {
            throw new CryptographicException(Environment.GetResourceString("Cryptography_PasswordDerivedBytes_InvalidIV"));
        }
        byte[] o = null;
        DeriveKey(this.ProvHandle, algid, algidHash, this._password, this._password.Length, keySize << 0x10, rgbIV, rgbIV.Length, JitHelpers.GetObjectHandleOnStack<byte[]>(ref o));
        return o;
    }
    

    Here is a decompiled code of NameOrOidToAlgId method.

    internal static int NameOrOidToAlgId(string oid, OidGroup oidGroup)
    {
        if (oid == null)
        {
            return 0x8004;
        }
        string str = CryptoConfig.MapNameToOID(oid, oidGroup);
        if (str == null)
        {
            str = oid;
        }
        int algIdFromOid = GetAlgIdFromOid(str, oidGroup);
        switch (algIdFromOid)
        {
            case 0:
            case -1:
                throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidOID"));
        }
        return algIdFromOid;
    }