OpenSSL  1.0.1c
 All Classes Files Functions Variables Typedefs Enumerations Enumerator Macros
example2.c
Go to the documentation of this file.
1 /* NOCW */
2 /*
3  Please read the README file for condition of use, before
4  using this software.
5 
6  Maurice Gittens <[email protected]> January 1997
7 */
8 
9 #include <stdlib.h>
10 #include <stdio.h>
11 #include <strings.h>
12 
13 #include <openssl/rsa.h>
14 #include <openssl/evp.h>
15 #include <openssl/objects.h>
16 #include <openssl/x509.h>
17 #include <openssl/err.h>
18 #include <openssl/pem.h>
19 #include <openssl/ssl.h>
20 
21 #include "loadkeys.h"
22 
23 #define PUBFILE "cert.pem"
24 #define PRIVFILE "privkey.pem"
25 #define STDIN 0
26 #define STDOUT 1
27 
28 int main()
29 {
30  char *ct = "This the clear text";
31  char *buf;
32  char *buf2;
33  EVP_PKEY *pubKey;
34  EVP_PKEY *privKey;
35  int len;
36 
38 
39  privKey = ReadPrivateKey(PRIVFILE);
40  if (!privKey)
41  {
42  ERR_print_errors_fp (stderr);
43  exit (1);
44  }
45 
46  pubKey = ReadPublicKey(PUBFILE);
47  if(!pubKey)
48  {
49  EVP_PKEY_free(privKey);
50  fprintf(stderr,"Error: can't load public key");
51  exit(1);
52  }
53 
54  /* No error checking */
55  buf = malloc(EVP_PKEY_size(pubKey));
56  buf2 = malloc(EVP_PKEY_size(pubKey));
57 
58  len = RSA_public_encrypt(strlen(ct)+1, ct, buf, pubKey->pkey.rsa,RSA_PKCS1_PADDING);
59 
60  if (len != EVP_PKEY_size(pubKey))
61  {
62  fprintf(stderr,"Error: ciphertext should match length of key\n");
63  exit(1);
64  }
65 
66  RSA_private_decrypt(len, buf, buf2, privKey->pkey.rsa,RSA_PKCS1_PADDING);
67 
68  printf("%s\n", buf2);
69 
70  EVP_PKEY_free(privKey);
71  EVP_PKEY_free(pubKey);
72  free(buf);
73  free(buf2);
74  return 0;
75 }