Difference between PKCS1-padding/RSA encryption ios objc and java

前端 未结 3 1278
清歌不尽
清歌不尽 2021-02-01 16:01

I’m developing a application for ios and Android. I’m relatively new to crypto tasks and for the last 3 Days I keep banging my head against the wall because I’m not able to get

3条回答
  •  北荒
    北荒 (楼主)
    2021-02-01 16:58

    Decoding the Base64 key gives:

    MCwwDQYJKoZIhvcNAQEBBQADGwAwGAIRAK+dBpbOKw+1VKMWoFxjU6UCAwEAAQ==
    -> 302c300d06092a864886f70d0101010500031b003018021100af9d0696ce2b0fb554a316a05c6353a50203010001
    

    Interpreting this as DER-encoded ASN.1, we find:

    30(2c) //SEQUENCE
      30(0d)  //SEQUENCE
        06(09): 2a 86 48 86 f7 0d 01 01 01  //OID 1.2.840.113548.1.1.1 (RSA Encryption)
        05(00): //NULL                           
        03(1b): [00] 30 18 02 11 00 af 9d 06 96 ce 2b 0f b5 54 a3 16 a0 5c 63 53 a5 02 03 01 00 01 //BITSTRING
    

    Where the BITSTRING also seems to contain DER-encoded ASN.1:

    30(18) //SEQUENCE
      02(11): 00 af 9d 06 96 ce 2b 0f b5 54 a3 16 a0 5c 63 53 a5 02 03 01 00 01 //INTEGER
    
     = 0xaf9d0696ce2b0fb554a316a05c6353a50203010001
    

    Walking through the IOS code, you can see that it is parsing the DER-encoded ASN.1. It correctly identifies the first two SEQUENCE tags, and skips over the OID field without even verifying that it is an OID. Then the problem occurs: the IOS code expects the next tag to be BITSTRING(0x03)---but in our data, we have an additional NULL(0x05) field to denote that the public exponent is implicit. The IOS code raises an exception upon encountering the 0x05 tag. If the NULL weren't there, we see that the IOS code would have successfully extracted the contents of the BITSTRING.

    So: either the NULL is an optional field, and the IOS code isn't permitting it, or the IOS code is expecting a different ASN.1 structure. For example, it appears that the BITSTRING is also a DER-encoded ASN.1 INTEGER (presumably the RSA modulus). Yet the IOS code makes no attempt to parse it. It may be that the IOS SecKeyEncrypt routine expects this format for the modulus, or it may be that the caller is supposed to extract the raw bytes of the modulus.

    So there's a little bit of experimentation still needed. But the following additional conditional is definately necessary if this code is to parse the supplied data object:

    /* Skip OID */
    i += 15;
    
    if (i >= bytesLen - 2)
        [Exception raise:FAILURE function:__PRETTY_FUNCTION__ line:__LINE__ description:@"Could not set public key."];
    
    if (bytes[i] == 0x05)    /* This should handle the spurious ASN.1 NULL field */
        i += 2;
    
    if (bytes[i++] != 0x03)
    

提交回复
热议问题