Objective#C等效代码的C#代码

mad*_*989 7 c# encryption cryptography objective-c

我试图将用C#编写的代码转换为目标c,我试过但无法得到相同的结果.任何帮助都会很明显.

internal static class Common  {
    static string encryptionKey = "0C61L2FSL2F3E7X8E9T1L2F3E4O5";
    static byte[] salt = new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76};
         
    internal static string Encrypt(string clearText)
    {
        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(encryptionKey, salt);

            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);

            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                clearText = Convert.ToBase64String(ms.ToArray());
            }
        }
        return clearText;
    }   
}   
Run Code Online (Sandbox Code Playgroud)

以上代码用于加密.我试图获得RFC2898derivebytes的等效函数.

我试过的目标代码:

-(void)doEncryption {

    NSString *url = @"www.google.com";

    const char salt[] = {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76};

    NSData *saltData =[NSData dataWithBytes:salt length:13];

    NSData* myPassData = [EncryptionKey dataUsingEncoding:NSUTF8StringEncoding];


    unsigned char key[32];

    CCKeyDerivationPBKDF(kCCPBKDF2, myPassData.bytes, myPassData.length, saltData.bytes, saltData.length, kCCPRFHmacAlgSHA1, 1000, key, 32);

    unsigned char InitialVector[16];

    CCKeyDerivationPBKDF(kCCPBKDF2, myPassData.bytes, myPassData.length, saltData.bytes, saltData.length, kCCPRFHmacAlgSHA1, 1000, InitialVector, 16);


    NSString *Aeskey = [[NSString alloc] initWithBytes:key length:sizeof(key) encoding:NSUnicodeStringEncoding];
    NSLog(@"Key AES : %@",Aeskey);



    NSString *AesIV = [[NSString alloc] initWithBytes:InitialVector length:sizeof(key) encoding:NSASCIIStringEncoding];

    NSString *encryptedString =  [AESCrypt encrypt:url password:Aeskey  andIV:AesIV];


    [self doDecryption:encryptedString withKey:nil];
 }
Run Code Online (Sandbox Code Playgroud)

Maa*_*wes 4

您面临的问题是,调用 PBKDF2 函数一次并提取前 32 个字节,然后提取 16 个字节与调用它两次并从单独的函数调用中提取 32 个字节和 16 个字节不同。目前,您可能会看到密钥的前 16 个字节和 IV 的前 16 个字节是相同的(因为一旦参数建立,PBKDF2 就是确定性的)。

应该有效的是要求 32 + 16 = 48 字节,然后提取前 32 字节作为密钥,接下来的 16 字节作为 IV。

一个更好但更难实现的选项是对 PBKDF2 的结果使用 KBKDF(基于密钥的密钥导出函数)。问题在于 PBKDF2 在内部被调用三次以创建 48 字节(因为 SHA-1 的输出大小为 20 字节)。这意味着您必须执行三次调用(包括所有迭代),而攻击者可能只需要执行一两次调用。