21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

little-endian machine and word-sized storage, each word will need to be byteswapped<br />

before the value can be treated as a binary string.<br />

Byte swapping can be done with the htonl( ) macro, which can be imported by<br />

including arpa/inet.h on Unix or winsock.h on Windows.<br />

7.10 Performing Raw Encryption with an RSA<br />

Public Key<br />

<strong>Problem</strong><br />

You want to encrypt a small message using an RSA public key so that only an entity<br />

with the corresponding private key can decrypt the message.<br />

Solution<br />

Your cryptographic library should have a straightforward API to the RSA encryption<br />

algorithm: you should be able to give it the public key, the data to encrypt, a buffer<br />

for the results, an indication of the data’s length, and a specification as to what kind<br />

of padding to use (EME-OAEP padding is recommended).<br />

When using OpenSSL, this can be done with the RSA_public_encrypt( ) function,<br />

defined in openssl/rsa.h.<br />

If, for some reason, you need to implement RSA on your own (which we strongly<br />

recommend against), refer to the Public Key Cryptography Standard (PKCS) #1,<br />

Version 2.1 (the latest version).<br />

Discussion<br />

Be sure to read the generic considerations for public key cryptography<br />

in Recipes 7.1 and 7.2.<br />

Conceptually, RSA encryption is very simple. A message is translated into an integer<br />

and encrypted with integer math. Given a message m written as an integer, if you<br />

want to encrypt to a public key, you take the modulus n and the exponent e from<br />

that public key. Then compute c = m e mod n, where c is the ciphertext, written as an<br />

integer. Given the ciphertext, you must have the private key to recover m. The private<br />

key consists of a single integer d, which can undo the encipherment with the<br />

operation m = c d mod n.<br />

This scheme is believed to be as “hard” as factoring a very large number. That’s<br />

because n is the product of two secret primes, p and q. Given p and q, it is easy to<br />

332 | Chapter 7: Public Key Cryptography<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!