TakeScoop / SwiftyRSA

RSA public/private key encryption in Swift
MIT License
1.28k stars 346 forks source link

Keys Generated by iOS app not Working on Online RSA Encryption /Decryption websites.. #187

Open taimoorsuleman opened 4 years ago

taimoorsuleman commented 4 years ago

Keys Generated by iOS app not Working on Online RSA Encryption /Decryption websites.. https://www.devglan.com/online-tools/rsa-encryption-decryption

the above website is java based. any body faced this isssue ?

hasretsariyer commented 3 years ago

I find a solution, it works for me.Taken from https://github.com/reejosamuel/RSA/blob/master/RSA/RSA/RSA.m#L121 `

(NSString *)getKeyForJavaServer:(NSData*)keyBits {

        static const unsigned char _encodedRSAEncryptionOID[15] = {

            /* Sequence of length 0xd made up of OID followed by NULL */
            0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
            0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00

        };

        // That gives us the "BITSTRING component of a full DER
        // encoded RSA public key - We now need to build the rest

        unsigned char builder[15];
        NSMutableData * encKey = [[NSMutableData alloc] init];
        int bitstringEncLength;

        // When we get to the bitstring - how will we encode it?

        if  ([keyBits length ] + 1  < 128 )
            bitstringEncLength = 1 ;
        else
            bitstringEncLength = (int)(([keyBits length] + 1 ) / 256 ) + 2;

        // Overall we have a sequence of a certain length
        builder[0] = 0x30;    // ASN.1 encoding representing a SEQUENCE
        // Build up overall size made up of -
        // size of OID + size of bitstring encoding + size of actual key
        size_t i = sizeof(_encodedRSAEncryptionOID) + 2 + bitstringEncLength +
        [keyBits length];
        size_t j = encodeLength(&builder[1], i);
        [encKey appendBytes:builder length:j +1];

        // First part of the sequence is the OID
        [encKey appendBytes:_encodedRSAEncryptionOID
                     length:sizeof(_encodedRSAEncryptionOID)];

        // Now add the bitstring
        builder[0] = 0x03;
        j = encodeLength(&builder[1], [keyBits length] + 1);
        builder[j+1] = 0x00;
        [encKey appendBytes:builder length:j + 2];

        // Now the actual key
        [encKey appendData:keyBits];

        // base64 encode encKey and return
        return [encKey base64EncodedStringWithOptions:0];

}

size_t encodeLength(unsigned char * buf, size_t length) {
        // encode length in ASN.1 DER format
        if (length < 128) {
            buf[0] = length;
            return 1;
        }

        size_t i = (length / 256) + 1;
        buf[0] = i + 0x80;
        for (size_t j = 0 ; j < i; ++j) {
            buf[i - j] = length & 0xFF;
            length = length >> 8;
        }

        return i + 1;
}

`