OpenSSL RSA key format problem solved the key format problem of PHP and C + + co-development

Source: Internet
Author: User
Tags begin rsa private key decrypt modulus openssl rsa
OpenSSL programming-rsa programming
This paper was published by Tai Tong on June 26, 2014, viewed: 1,954 times, Comments: 0

One. RSA PEM file format

1. PEM private key format file
-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----

2. PEM Public key format file
-----BEGIN Public KEY-----
-----END Public KEY-----

3. PEM rsapublickey Public key format file
-----BEGIN RSA Public KEY-----
-----END RSA Public KEY-----

Two. OpenSSL key-related commands

1. Generate key
OpenSSL genrsa-out Key.pem 1024
-OUT Specifies the makefile, which contains both the public key and the private key, so that it can be encrypted or decrypted
1024 the length of the generated key

2. Extracting the PEM-formatted public key
OpenSSL rsa-in key.pem-pubout-out Pubkey.pem
-in specifying the input key file
-OUT Specifies the file to extract the generated public key (PEM public key format)

3. Extracting the PEM rsapublickey format public key
OpenSSL rsa-in key.pem-rsapublickey_out-out Pubkey.pem
-in specifying the input key file
-OUT Specifies the file to extract the generated public key (PEM rsapublickey format)

4. Public Key encrypted files
OpenSSL rsautl-encrypt-in Input.file-inkey pubkey.pem-pubin-out output.file
-in specifying the Encrypted file
-inkey specifying an encrypted public key file
-pubin surface is encrypted with a pure public key file
-out specifying the Encrypted file

5. Private key decryption file
OpenSSL rsautl-decrypt-in Input.file-inkey key.pem-out output.file
-in specify the files that need to be decrypted
-inkey specifying the private key file
-out specifying the decrypted file

Three. RSA-related APIs

1. Basic data structure
struct {
Bignum *n; Public modulus
Bignum *e; public exponent
Bignum *d; Private exponent
Bignum *p; Secret prime factor
Bignum *q; Secret prime factor
Bignum *DMP1; d MoD (p-1)
Bignum *dmq1; d MoD (q-1)
Bignum *iqmp; Q^-1 mod p
// ...
} RSA;


2. BN Large number series function
Reborn into a bignum structure
Bignum *bn_new (void);

Release a bignum structure, release after A=null;
void Bn_free (Bignum *a);

Initialize all items to 0, typically Bn_ init (&c)
void Bn_init (Bignum *);

Assigns all items in a to a value of 0, but memory is not released
void Bn_clear (Bignum *a);

Rather with the bn_free and bn_clear synthesis, or assign a value of 0, or free space.
void Bn_clear_free (Bignum *a);

Set the large number A to an integer w
int Bn_set_word (bignum *a, unsigned long w);

If the large number a can be expressed as a long type, then a long number is returned
unsigned long Bn_get_word (Bignum *a);

Generates a pseudo-random number of strong bits for encryption
If top=-1, the highest bit is 0,top=0, the highest bit is 1,top=1, the highest and second highs are 1,bottom true, and the random number is even
int Bn_rand (bignum *rnd, int bits, int top, int bottom);

The space to convert a into a string to,to must be greater than bn_num_bytes (a)
int Bn_bn2bin (const bignum *a, unsigned char *to);

Converts a positive integer in the Len bit in S to a large number
Bignum *bn_bin2bn (const unsigned char *s, int len, bignum *ret);

Convert a large number to a 16 binary string
Char *bn_bn2hex (const bignum *a);

Convert a large number to a 10 binary string
Char *bn_bn2dec (const bignum *a);

Converts a 16 binary string into a large number
int bn_hex2bn (bignum **a, const char *STR);

To pass a 10 binary string to a large number
int bn_dec2bn (bignum **a, const char *STR);

3. RSA Series functions
Initializing an RSA structure
RSA * rsa_new (void);

Releasing an RSA structure
void Rsa_free (RSA *rsa);

RSA private key Generation function
Generates a key pair that is modeled as Num bits, and E is the public encryption exponent, typically 65537 (0x10001)
RSA *rsa_generate_key (int num, unsigned long e,void (*callback) (int,int,void *), void *cb_arg);

Determine the number of bits function and return the bits of the RSA modulo
int rsa_size (const RSA *RSA);

Test whether P, Q is a prime number
int Rsa_check_key (RSA *rsa);

4. PEM Series functions
Load the Rsapublickey format public key certificate from the file
RSA *pem_read_rsapublickey (FILE *FP, RSA **x, PEM_PASSWORD_CB *cb, void *u);

Reload Rsapublickey format public key certificate from bio
RSA *pem_read_bio_rsapublickey (Bio *BP, RSA **x, PEM_PASSWORD_CB *cb, void *u);

Output Rsapublickey Public key certificate to file
int Pem_write_rsapublickey (FILE *fp, RSA *x);

Output Rsapublickey Public key certificate to bio
int Pem_write_bio_rsapublickey (bio *bp, RSA *x);

5. RSA Encryption API
int rsa_public_encrypt (int flen, unsigned char *from, unsigned char *to, RSA *rsa, int padding);

Parameter description:
Flen: To encrypt information length
From: To encrypt information
To: Information after encryption
padding: The encryption scheme taken, divided into: rsa_pkcs1_padding, rsa_pkcs1_oaep_padding, rsa_sslv23_padding, rsa_no_padding

6. RSA Decryption API
int rsa_private_decrypt (int flen, unsigned char *from, unsigned char *to, RSA *rsa, int padding);

Parameter description:
Flen: Length of information to decrypt
From: Information to decrypt
To: Decrypted information
padding: The decryption scheme taken

Four. RSA Programming Example

1. Data encryption and decryption example
#include
#include
#include
#include
#include
#include

#define Prikey "Prikey.pem"
#define PubKey "Pubkey.pem"
#define BUFFSIZE 4096

/************************************************************************
* RSA Cryptographic decryption function
*
* FILE:TEST_RSA_ENCDEC.C
* Gcc-wall-o2-o Test_rsa_encdec Test_rsa_encdec.c-lcrypto-lssl
*
* Author:tonglulin@gmail.com bywww.qmailer.net
************************************************************************/

Char *my_encrypt (char *str, char *pubkey_path)
{
RSA *rsa = NULL;
FILE *FP = NULL;
char *en = NULL;
int len = 0;
int rsa_len = 0;

if (fp = fopen (Pubkey_path, "R")) = = = NULL) {
return NULL;
}

/* Read the public key Pem,pubkey format PEM using the Pem_read_rsa_pubkey function */
if (RSA = Pem_read_rsapublickey (FP, NULL, NULL, NULL)) = = = NULL) {
return NULL;
}

RSA_PRINT_FP (stdout, RSA, 0);

len = strlen (str);
Rsa_len = Rsa_size (RSA);

En = (char *) malloc (Rsa_len + 1);
memset (en, 0, rsa_len + 1);

if (Rsa_public_encrypt (Rsa_len, (unsigned char *) str, (unsigned char*) en, RSA, rsa_no_padding) < 0) {
return NULL;
}

Rsa_free (RSA);
Fclose (FP);

Return en;
}

Char *my_decrypt (char *str, char *prikey_path)
{
RSA *rsa = NULL;
FILE *FP = NULL;
char *de = NULL;
int rsa_len = 0;

if (fp = fopen (Prikey_path, "R")) = = = NULL) {
return NULL;
}

if (RSA = Pem_read_rsaprivatekey (FP, NULL, NULL, NULL)) = = = NULL) {
return NULL;
}

RSA_PRINT_FP (stdout, RSA, 0);

Rsa_len = Rsa_size (RSA);
De = (char *) malloc (Rsa_len + 1);
memset (DE, 0, Rsa_len + 1);

if (Rsa_private_decrypt (Rsa_len, (unsigned char *) str, (unsigned char*) de, RSA, rsa_no_padding) < 0) {
return NULL;
}

Rsa_free (RSA);
Fclose (FP);

Return de;
}

int main (int argc, char *argv[])
{
char *src = "Hello, world!";
char *en = NULL;
char *de = NULL;

printf ("src is:%s\n", SRC);

En = My_encrypt (src, pubkey);
printf ("Enc is:%s\n", en);

De= my_decrypt (en, Prikey);
printf ("Dec is:%s\n", de);

if (en = NULL) {
Free (en);
}

if (de! = NULL) {
Free (DE);
}

return 0;
}

2. Pem/bignum Public Key Conversion example
#include
#include

#include
#include

/************************************************************************
* RSA pem/bignum Public key conversion function
*
* FILE:TEST_RSA_PUBKEY.C
* Gcc-wall-o2-o Test_rsa_pubkey Test_rsa_pubkey.c-lcrypto-lssl
*
* Author:tonglulin@gmail.com bywww.qmailer.net
************************************************************************/

const char *n = " c7301b330c4e123e4fa9f54f49121e8ce07974d8bfef1d39ec9245d573d66e7fac258f86e2b0816c6ba875f10673e655e6a8df48defddb655e253ed5a 4a0fbad50d68e91d0459f9f2377bb8ca1583e3f83c06343a5a1177c903f498a6d14015cc975522be4446cd1eb87e88ef05a863af0dd7c4d413cf603ed F4893eec063be3 ";

const char *pubkey = "-----BEGIN RSA Public KEY-----\nmigjaogbamcwgzmmthi+t6n1t0kshozgextyv+8doeysrdvz1m5/ Rcwphukwgwxr\nqhxxbnpmveao30je/dtlxiu+1asg+61q1o6r0ewfnyn3u4yhwd4/g8bjq6whf3yq\ np0mkbrqbxml1uivkrgzr64fojvbahjrw3xxnqtz2a+30it7sbjvjagmbaae=\n-----END RSA public KEY-----";

int main (int argc, char *argv[])
{
RSA *rsa = NULL;
BIO *bio = NULL;
Bignum *bne = NULL;
Bignum *BNN = NULL;
FILE *FP = NULL;
unsigned long e = 65537;

if (ARGC < 2) {
printf ("%s pem|bignum args\n", argv[0]);
return-1;
}

/* Convert the PEM to a large number of strings */
if (strcasecmp (argv[1], "bignum") = = 0) {
if (argc = = 3) {
/* Read from external file */
fp = fopen (argv[2], "R");
if (fp = = NULL) {
return-1;
}

RSA = Pem_read_rsapublickey (FP, &rsa, NULL, NULL);
if (RSA = = NULL) {
return-1;
}
}
else {
/* Read from memory data */
Bio = Bio_new (Bio_s_mem ());
Bio_puts (bio, PubKey);

RSA = Pem_read_bio_rsapublickey (bio, &rsa, null, NULL);
if (RSA = = NULL) {
return-1;
}
}

RSA_PRINT_FP (stdout, RSA, 0);
printf ("%s\n", Bn_bn2hex (Rsa->n));
printf ("%s\n", Bn_bn2hex (rsa->e));

if (argc = = 3) {
Fclose (FP);
}
else {
Bio_free (bio);
}
Rsa_free (RSA);
}
/* Convert a large number of strings to a PEM file */
else if (strcasecmp (argv[1], "PEM") = = 0) {

BNE = Bn_new ();
if (bne = = NULL) {
return-1;
}

BNN = Bn_new ();
if (BNN = = NULL) {
Bn_free (BNE);
return-1;
}

RSA = Rsa_new ();
if (RSA = = NULL) {
Bn_free (BNN);
Bn_free (BNE);
return-1;
}

Rsa->e = BNE;
Rsa->n = BNN;

/* Set modulus */
Bn_set_word (BNE, E);
if (argc = = 3) {
Bn_hex2bn (&BNN, argv[2]);
}
else {
Bn_hex2bn (&BNN, N);
}

Pem_write_rsapublickey (stdout, RSA);

Rsa_free (RSA);
}
else {
return-1;
}

return 0;
}

3. Key Generation Example
#include
#include
#include
#include
#include
#include

/************************************************************************
* RSA key Generation function
*
* FILE:TEST_RSA_GENKEY.C
* Gcc-wall-o2-o Test_rsa_genkey Test_rsa_genkey.c-lcrypto
*
* Author:tonglulin@gmail.com bywww.qmailer.net
************************************************************************/
int main (int argc, char *argv[])
{
/* Generate RSA Key */
RSA *rsa = Rsa_generate_key (1024x768, 65537, NULL, NULL);

printf ("Bignum:%s\n", Bn_bn2hex (Rsa->n));

/* Extract the private key */
printf ("prikey:\n");
Pem_write_rsaprivatekey (stdout, RSA, NULL, NULL, 0, NULL, NULL);

/* Extract the public key */
unsigned char *n_b = (unsigned char *) calloc (rsa_size (RSA), sizeof (unsigned char));
unsigned char *e_b = (unsigned char *) calloc (rsa_size (RSA), sizeof (unsigned char));

int n_size = Bn_bn2bin (Rsa->n, N_b);
int b_size = Bn_bn2bin (rsa->e, E_b);

RSA *pubrsa = Rsa_new ();
Pubrsa->n = Bn_bin2bn (N_b, N_size, NULL);
Pubrsa->e = Bn_bin2bn (E_b, B_size, NULL);

printf ("PubKey: \ n");
Pem_write_rsapublickey (stdout, PUBRSA);

Rsa_free (RSA);
Rsa_free (PUBRSA);

return 0;
}

The above describes the OpenSSL RSA key format problem, to solve the PHP and C + + cooperative development of the key format problem, including the aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.