5 Author: Tatu Ylonen <ylo@cs.hut.fi>
7 Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
10 Created: Fri Mar 3 22:07:06 1995 ylo
12 Description of the RSA algorithm can be found e.g. from the following sources:
14 Bruce Schneier: Applied Cryptography. John Wiley & Sons, 1994.
16 Jennifer Seberry and Josed Pieprzyk: Cryptography: An Introduction to
17 Computer Security. Prentice-Hall, 1989.
19 Man Young Rhee: Cryptography and Secure Data Communications. McGraw-Hill,
22 R. Rivest, A. Shamir, and L. M. Adleman: Cryptographic Communications
23 System and Method. US Patent 4,405,829, 1983.
25 Hans Riesel: Prime Numbers and Computer Methods for Factorization.
28 The RSA Frequently Asked Questions document by RSA Data Security, Inc., 1995.
30 RSA in 3 lines of perl by Adam Back <aba@atlax.ex.ac.uk>, 1995, as included
33 gone - had to be deleted - what a pity
51 key = RSA_generate_key(32, 3, NULL, NULL);
58 /* Generates RSA public and private keys. This initializes the data
59 structures; they should be freed with rsa_clear_private_key and
60 rsa_clear_public_key. */
63 rsa_generate_key(RSA *prv, RSA *pub, unsigned int bits)
68 printf("Generating RSA keys: ");
72 key = RSA_generate_key(bits, 35, NULL, NULL);
74 fatal("rsa_generate_key: key generation failed.");
76 /* Copy public key parameters */
78 BN_copy(pub->n, key->n);
80 BN_copy(pub->e, key->e);
82 /* Copy private key parameters */
84 BN_copy(prv->n, key->n);
86 BN_copy(prv->e, key->e);
88 BN_copy(prv->d, key->d);
90 BN_copy(prv->p, key->p);
92 BN_copy(prv->q, key->q);
95 BN_copy(prv->dmp1, key->dmp1);
98 BN_copy(prv->dmq1, key->dmq1);
100 prv->iqmp = BN_new();
101 BN_copy(prv->iqmp, key->iqmp);
106 printf("Key generation complete.\n");
110 rsa_public_encrypt(BIGNUM *out, BIGNUM *in, RSA* key)
112 char *inbuf, *outbuf;
117 if (BN_num_bits(key->e) < 2 || !BN_is_odd(key->e))
118 fatal("rsa_public_encrypt() exponent too small or not odd");
120 out_len = BN_num_bytes(key->n);
121 outbuf = xmalloc(out_len);
123 in_len = BN_num_bytes(in);
124 inbuf = xmalloc(in_len);
125 BN_bn2bin(in, inbuf);
127 if ((len = RSA_public_encrypt(in_len, inbuf, outbuf, key,
128 RSA_PKCS1_PADDING)) <= 0)
129 fatal("rsa_public_encrypt() failed");
131 BN_bin2bn(outbuf, len, out);
133 memset(outbuf, 0, out_len);
134 memset(inbuf, 0, in_len);
140 rsa_private_decrypt(BIGNUM *out, BIGNUM *in, RSA *key)
142 char *inbuf, *outbuf;
147 out_len = BN_num_bytes(key->n);
148 outbuf = xmalloc(out_len);
150 in_len = BN_num_bytes(in);
151 inbuf = xmalloc(in_len);
152 BN_bn2bin(in, inbuf);
154 if ((len = RSA_private_decrypt(in_len, inbuf, outbuf, key,
155 RSA_SSLV23_PADDING)) <= 0)
156 fatal("rsa_private_decrypt() failed");
158 BN_bin2bn(outbuf, len, out);
160 memset(outbuf, 0, out_len);
161 memset(inbuf, 0, in_len);
166 /* Set whether to output verbose messages during key generation. */
169 rsa_set_verbose(int verbose)
171 rsa_verbose = verbose;