06 December, 2013

RSA Cryptology

RSA Laboratories currently recommends key sizes of 1024 bits for corporate use and 2048 bits for extremely valuable keys like the root key pair used by a certifying authority.

For normal websites, they are using 2048 bit key for SSL protocol.

RSA has 3 padding mode mainly:
RAW, PKCS, OAEP.

After I tested these three modes with android platform, here is the result:
RAW:
Max length of plain text: (RSA key length / 8 )       
Cipher text length: RSA key length
PKCS: (mostly used)
Max length of plain text: (RSA key length / 8 )  - 11             
Cipher text length: RSA key length
OAEP:
Max length of plain text: (RSA key length / 8 )  - 42             
Cipher text length: RSA key length
And we should hash the plain text before encrypt for security consideration.

Here are native APIs on android / ios platform:
Android:

  • How to get publick key from https request:
SSLSocketFactory factory = HttpsURLConnection.getDefaultSSLSocketFactory();
SSLSocket socket = (SSLSocket)factory.createSocket(url, 443);   
Certificate[] certs = socket.getSession().getPeerCertificates();

  • How to encrypt data with public key
    c = Cipher.getInstance("RSA/ECB/PKCS1Padding");            
c.init(Cipher.ENCRYPT_MODE, mCertificate.getPublicKey());   
byte[] encArray = c.doFinal(plainText.getBytes());
iOS:
  • How to get publick key from https request:

Within the method of delegate NSURLConnectionDelegate:
- (void)connection:(NSURLConnection *)connection      didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge:
SecTrustRef trustRef = [[challenge protectionSpace] serverTrust];
SecKeyRef secKey = SecTrustCopyPublicKey(trustRef);

  • How to encrypt data with public key

long maxPlainTextLen = SecKeyGetBlockSize(key) -11; // kSecPaddingPKCS1
void *plain = malloc(plainLen);
[content getBytes:plain length:plainLen];
   
size_t cipherLen = 256; // RSA key length is set to 2048 bits
void *cipher = malloc(cipherLen);    
OSStatus returnCode = SecKeyEncrypt(secKey, kSecPaddingPKCS1, plain,
                                       plainLen, cipher, &cipherLen);