8

到目前为止,我已经为此花了两天时间,并梳理了我可以使用的所有资源,所以这是最后的手段。

我有一个 X509 证书,其公钥存储在 iPhone 的钥匙串中(此时仅模拟器)。在 ASP.NET 方面,我在证书存储中使用私钥获得了证书。当我在 iPhone 上加密一个字符串并在服务器上解密它时,我得到一个CryptographicException“坏数据”。我尝试了页面中的Array.Reverse建议RSACryptoServiceProvider,但没有帮助。

我比较了两边的base-64字符串,它们是相等的。我在解码后比较了原始字节数组,它们也是相等的。如果我在服务器上使用公钥加密,字节数组与 iPhone 的版本不同,并且很容易使用私钥解密。原始明文字符串为 115 个字符,因此它在我的 2048 位密钥的 256 字节限制之内。

这是 iPhone 加密方法(从CryptoExercise 示例应用程序的方法中几乎一字不差wrapSymmetricKey):

+ (NSData *)encrypt:(NSString *)plainText usingKey:(SecKeyRef)key error:(NSError **)err
{
    size_t cipherBufferSize = SecKeyGetBlockSize(key);
    uint8_t *cipherBuffer = NULL;
    cipherBuffer = malloc(cipherBufferSize * sizeof(uint8_t));
    memset((void *)cipherBuffer, 0x0, cipherBufferSize);
    NSData *plainTextBytes = [plainText dataUsingEncoding:NSUTF8StringEncoding];
    OSStatus status = SecKeyEncrypt(key, kSecPaddingNone,
                                (const uint8_t *)[plainTextBytes bytes], 
                                [plainTextBytes length], cipherBuffer, 
                                &cipherBufferSize);
    if (status == noErr)
    {
        NSData *encryptedBytes = [[[NSData alloc]
                    initWithBytes:(const void *)cipherBuffer 
                    length:cipherBufferSize] autorelease];
        if (cipherBuffer)
        {
            free(cipherBuffer);
        }
        NSLog(@"Encrypted text (%d bytes): %@",
                    [encryptedBytes length], [encryptedBytes description]);
        return encryptedBytes;
    }
    else
    {
        *err = [NSError errorWithDomain:@"errorDomain" code:status userInfo:nil];
        NSLog(@"encrypt:usingKey: Error: %d", status);
        return nil;
    }
}

这是服务器端 C# 解密方法:

private string Decrypt(string cipherText)
{
    if (clientCert == null)
    {
        // Get certificate
        var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
        store.Open(OpenFlags.ReadOnly);
        foreach (var certificate in store.Certificates)
        {
            if (certificate.GetNameInfo(X509NameType.SimpleName, false) == CERT)
            {
                clientCert = certificate;
                break;
            }
        }
    }

    using (var rsa = (RSACryptoServiceProvider)clientCert.PrivateKey)
    {
        try
        {
            var encryptedBytes = Convert.FromBase64String(cipherText);
            var decryptedBytes = rsa.Decrypt(encryptedBytes, false);
            var plaintext = Encoding.UTF8.GetString(decryptedBytes);
            return plaintext;
        }
        catch (CryptographicException e)
        {
            throw(new ApplicationException("Unable to decrypt payload.", e));
        }
    }
}

我怀疑平台之间存在一些编码问题。我知道一个是大端,另一个是小端,但我不知道哪个是哪个或如何克服差异。Mac OS X、Windows 和 iPhone 都是 little-endian,所以这不是问题。

新理论:如果将 OAEP 填充布尔值设置为 false,则默认为 PKCS#1 1.5 填充。SecKey只有、、和SecPadding的定义。也许 Microsoft 的 PKCS#1 1.5 != Apple 的 PKCS1 等填充会影响加密的二进制输出。我尝试与set to一起使用,但仍然无法正常工作。PKCS1PKCS1MD2PKCS1MD5PKCS1SHA1kSecPaddingPKCS1fOAEPfalse显然,kSecPaddingPKCS1相当于PKCS #1 1.5。回到理论的绘图板......

其他新尝试的理论:

  1. iPhone 上的证书(.cer 文件)与服务器上的 PKCS#12 包(.pfx 文件)并不完全相同,因此它永远无法工作。在不同的证书存储中安装了 .cer 文件,并且服务器加密的字符串往返就好了;
  2. 转换为 base-64 和 POST 到服务器的行为导致了同一个类往返中不存在的奇怪,所以我首先尝试了一些 URLEncoding/Decoding,然后从 iPhone 发布原始二进制文件,验证它是相等的,并得到相同的坏数据;
  3. 我的原始字符串是 125 字节,所以我认为它可能会在 UTF-8(长镜头)中被截断,所以我将其裁剪为 44 字节的字符串而没有结果;
  4. 回顾 System.Cryptography 库以确保我使用了适当的类并发现了“RSAPKCS1KeyExchangeDeformatter”,对新的前景感到高兴,当它的行为完全相同时感到沮丧。

成功!

事实证明,我在 iPhone 模拟器上的钥匙串中有一些东西弄脏了水,可以这么说。我删除了 Keychain DB 以~/Library/Application Support/iPhone Simulator/User/Library/Keychains/keychain-2-debug.db使其重新创建并且工作正常。感谢您的所有帮助。数字这将是一些简单但不明显的事情。(我学到了两件事:1)从模拟器中卸载应用程序不会清除其钥匙串条目,2)定期重新启动。)

注意:钥匙串文件的通用路径取决于 iOS 版本:~/Library/Application Support/iPhone Simulator/[version]/Library/Keychains/keychain-2-debug.db 例如,~/Library/Application Support/ iPhone模拟器/4.3/Library/Keychains/keychain-2-debug.db

4

4 回答 4

3

嗯......第一步(正如你所说的那样)是使用 iPhone 和 C# 实现使用相同的初始化向量加密相同的消息。你应该得到相同的输出。你说你没有,所以有问题。

这意味着:

  • RSA 的 iPhone 实现不正确。
  • RSA 的 .NET 实现不正确。
  • 密钥文件不同(或解释不同)。

我建议前两个不太可能,但是它们是远程可能的。

您声明:“在不同的证书存储中安装 .cer 文件和服务器加密的字符串往返就好了”......这并不能证明任何事情:这一切都证明了给定一组特定的随机数字,您可以成功加密/解密一个平台。您不能保证两个平台看到的是同一组随机数。

所以我建议你把它降到尽可能低的水平。检查两个平台上加密的直接(字节数组)输入和输出。如果使用完全相同的(二进制)输入,您没有得到相同的输出,那么您就有平台问题。我认为这不太可能,所以我猜你会发现 IV 的解释不同。

于 2009-07-17T20:55:09.380 回答
1

这是我在stackoverflow上的第一个答案,所以如果我做错了请原谅我!

我不能给你一个完整的答案,但是当我尝试与 PHP 集成时,我遇到了非常相似的问题——Apple 证书文件的格式似乎与其他软件(包括 openssl)所期望的格式略有不同。

以下是我在 PHP 中解密加密签名的方法——我实际上是从传输的公钥中手动提取模数和 PK 并将其用于 RSA 内容,而不是尝试导入密钥:

// Public key format in hex (2 hex chars = 1 byte):
//30480241009b63495644db055437602b983f9a9e63d9af2540653ee91828483c7e302348760994e88097d223b048e42f561046c602405683524f00b4cd3eec7e67259c47e90203010001
//<IGNORE><--------------------------------------------- MODULUS --------------------------------------------------------------------------><??>< PK > 
// We're interested in the modulus and the public key.
// PK = Public key, probably 65537

// First, generate the sha1 of the hash string:
$sha1 = sha1($hashString,true);

// Unencode the user's public Key:
$pkstr = base64_decode($publicKey);
// Skip the <IGNORE> section:
$a = 4;
// Find the very last occurrence of \x02\x03 which seperates the modulus from the PK:
$d = strrpos($pkstr,"\x02\x03");
// If something went wrong, give up:
if ($a == false || $d == false) return false;
// Extract the modulus and public key:
$modulus = substr($pkstr,$a,($d-$a));
$pk = substr($pkstr,$d+2);

// 1) Take the $signature from the user
// 2) Decode it from base64 to binary
// 3) Convert the binary $pk and $modulus into (very large!) integers (stored in strings in PHP)
// 4) Run rsa_verify, from http://www.edsko.net/misc/rsa.php
$unencoded_signature = rsa_verify(base64_decode($signature), binary_to_number($pk), binary_to_number($modulus), "512");

//Finally, does the $sha1 we calculated match the $unencoded_signature (less any padding bytes on the end)?
return ($sha1 == substr($unencoded_signature,-20)); // SHA1 is only 20 bytes, whilst signature is longer than this.  

生成这个公钥的objective-c是:

NSData * data = [[SecKeyWrapper sharedWrapper] getPublicKeyBits];
[req addValue:[data base64Encoding] forHTTPHeaderField: @"X-Public-Key"];
data = [[SecKeyWrapper sharedWrapper] getSignatureBytes:[signatureData dataUsingEncoding:NSUTF8StringEncoding]];
[req addValue:[data base64Encoding] forHTTPHeaderField: @"X-Signature"];

使用 Apple 示例项目 CryptoExercise 中的 SecKeyWrapper(您可以在此处查看文件:https ://developer.apple.com/iphone/library/samplecode/CryptoExercise/listing15.html )

我希望这有帮助?

于 2009-07-20T10:15:07.963 回答
0

这会帮助你吗?

使用 .NET 和 C# 的非对称密钥加密

  • 对不起,简短的帖子,时间限制等等。无论如何,看到你的 Twitter 请求帮助.. 这显示了我是如何使用 PHP 做到这一点并在 .NET 上解密的,类似。我注意到您的解密类与我的略有不同,因此本文可能会有所帮助。
于 2009-07-17T17:07:21.680 回答
-2

我相信你自己已经回答了这个问题。问题肯定在于字节序。

这是编写双向转换方法的一种可能方式:

short convert_short(short in)
{
 short out;
 char *p_in = (char *) &in;
 char *p_out = (char *) &out;
 p_out[0] = p_in[1];
 p_out[1] = p_in[0];  
 return out;
}

long convert_long(long in)
{
 long out;
 char *p_in = (char *) &in;
 char *p_out = (char *) &out;
 p_out[0] = p_in[3];
 p_out[1] = p_in[2];
 p_out[2] = p_in[1];
 p_out[3] = p_in[0];  
 return out;
} 

这对您来说可能是一个很好的资源(维基百科除外):http ://betterexplained.com/articles/understanding-big-and-little-endian-byte-order/

于 2009-07-15T22:26:48.817 回答