- 论坛徽章:
- 0
|
20可用积分
- #include <stdio.h>
- #include <string.h>
- #include <openssl/bio.h>
- #include <openssl/rsa.h>
- #include <openssl/pem.h>
- int main(int argc, char** argv)
- {
- BIO *bpub;
- BIO *bpri;
- RSA *pRSA;
- RSA *rsa_rpu;
- FILE *fp = NULL;
- unsigned char *encryptedString = NULL;
- unsigned char *plainText= NULL;
-
- bpub = BIO_new_file("public.rsa", "w");
- if (!bpub)
- printf("%s","failed to create public bio file\n");
-
- bpri = BIO_new_file("private.rsa", "w");
- if (!bpri)
- printf("%s","failed to create private bio file\n");
- if (!bpub || !bpri)
- return -1;
- pRSA = RSA_generate_key( 1024, RSA_F4, NULL, NULL);
- if (pRSA != NULL) {
- if (!PEM_write_bio_RSAPublicKey(bpub, pRSA) )
- printf("%s","PEM_write_bio_RSAPublicKey: failed\n");
- /*
- int PEM_write_bio_RSAPrivateKey(BIO *bp, RSA *x, const EVP_CIPHER *enc,
- unsigned char *kstr, int klen,
- pem_password_cb *cb, void *u);
- */
- if (!PEM_write_bio_RSAPrivateKey(bpri, pRSA, EVP_des_ede3_cbc(), NULL, 0, 0, "Private"))
- printf("%s","PEM_write_bio_PrivateKey: failed\n");
- }
- if (bpub)
- BIO_free(bpub);
- if (bpri)
- BIO_free(bpri);
- if (pRSA)
- free(pRSA);
-
- printf("done.\n");
-
-
- bpri = BIO_new_file("private.rsa", "r");
- if(bpri==NULL)
- {
- printf("%s\n", "open private.rsa error");
- return -1;
- }
- pRSA = PEM_read_bio_RSAPrivateKey(bpri, NULL, NULL, NULL);
- if (pRSA==NULL){
- printf("%s\n","Reading of private key failed");
- }else{
- printf("%s\n","Reading of private key successful");
- }
-
- bpub = BIO_new_file("public.rsa", "r");
- if(bpub==NULL)
- {
- printf("%s\n", "open public.rsa error");
- return -1;
- }
- rsa_rpu = PEM_read_bio_RSA_PUBKEY(bpub,NULL, NULL, NULL);
- //printf("rsa_rpu is: %s",rsa_rpu);
- if (rsa_rpu==NULL){
- printf("rsa_rpu is:%s\n","Reading of public key failed");
- }
- else{
- printf("rsa_rpu is:%s\n","Reading of public key successful");
- }
-
- encryptedString=(unsigned char *)malloc(RSA_size(rsa_rpu));
- RSA_blinding_off(rsa_rpu);
- if (RSA_public_encrypt(strlen("TrialString")+1,(unsigned char*)"TrialString",(unsigned char*)encryptedString,rsa_rpu,RSA_PKCS1_PADDING)==-1){
- printf("%s\n","encryption failed ");
- }
- else{
- printf("%s\n", "Encryption success");
- }
-
- plainText=(unsigned char *)malloc(RSA_size(pRSA));
- if (RSA_private_decrypt(RSA_size(pRSA),encryptedString,(unsigned char*)plainText,pRSA,RSA_PKCS1_PADDING)==-1){
- printf("%s\n","Decryption failed ");
- }
- else{
- printf("%s\n","Decryption success");
- }
-
- printf("Plain text:%s\n",plainText);
-
- return 0;
- }
复制代码 生成public.rsa和private.rsa后,将public.rsa发给B,自己留private.rsa!!再加解密
为什么从保持有private key的private.rsa中读取RSA会失败呢?
PEM_read_bio_RSAPrivateKey和PEM_read_RSAPrivateKey都尝试过了...
public key 和public.rsa也是一样失败...
因为实际通过过程中肯定是把public.rsa发给用户的...
而我write file的时候使用PEM_write_RSA_PUBKEY和PEM_write_RSAPrivateKey,整个过程就是可以的.... |
|