21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

#define MIN(x,y) ((x) > (y) ? (y) : (x))<br />

unsigned char *generate_and_package_128_bit_secret(RSA *recip_pub_key,<br />

RSA *signers_key, unsigned char *sec, unsigned int *olen) {<br />

unsigned char *tmp = 0, *to_encrypt = 0, *sig = 0, *out = 0, *p, *ptr;<br />

unsigned int len, ignored, b_per_ct;<br />

int bytes_remaining; /* MUST NOT BE UNSIGNED. */<br />

unsigned char hash[20];<br />

/* Generate the secret. */<br />

if (!RAND_bytes(sec, 16)) return 0;<br />

/* Now we need to sign the public key and the secret both.<br />

* Copy the secret into tmp, then the public key and the exponent.<br />

*/<br />

len = 16 + RSA_size(recip_pub_key) + BN_num_bytes(recip_pub_key->e);<br />

if (!(tmp = (unsigned char *)malloc(len))) return 0;<br />

memcpy(tmp, sec, 16);<br />

if (!BN_bn2bin(recip_pub_key->n, tmp + 16)) goto err;<br />

if (!BN_bn2bin(recip_pub_key->e, tmp + 16 + RSA_size(recip_pub_key))) goto err;<br />

/* Now sign tmp (the hash of it), again mallocing space for the signature. */<br />

if (!(sig = (unsigned char *)malloc(BN_num_bytes(signers_key->n)))) goto err;<br />

if (!SHA1(tmp, len, hash)) goto err;<br />

if (!RSA_sign(NID_sha1, hash, 20, sig, &ignored, signers_key)) goto err;<br />

/* How many bytes we can encrypt each time, limited by the modulus size<br />

* and the padding requirements.<br />

*/<br />

b_per_ct = RSA_size(recip_pub_key) - (2 * 20 + 2);<br />

if (!(to_encrypt = (unsigned char *)malloc(16 + RSA_size(signers_key))))<br />

goto err;<br />

/* The calculation before the mul is the number of encryptions we're<br />

* going to make. After the mul is the output length of each<br />

* encryption.<br />

*/<br />

*olen = ((16 + RSA_size(signers_key) + b_per_ct - 1) / b_per_ct) *<br />

RSA_size(recip_pub_key);<br />

if (!(out = (unsigned char *)malloc(*olen))) goto err;<br />

/* Copy the data to encrypt into a single buffer. */<br />

ptr = to_encrypt;<br />

bytes_remaining = 16 + RSA_size(signers_key);<br />

memcpy(to_encrypt, sec, 16);<br />

memcpy(to_encrypt + 16, sig, RSA_size(signers_key));<br />

p = out;<br />

while (bytes_remaining > 0) {<br />

/* encrypt b_per_ct bytes up until the last loop, where it may be fewer. */<br />

if (!RSA_public_encrypt(MIN(bytes_remaining,b_per_ct), ptr, p,<br />

recip_pub_key, RSA_PKCS1_OAEP_PADDING)) {<br />

Securely Signing and Encrypting with RSA | 345<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!