Openssl庫 - RSA

RSA_new

創建RSA對象

RSA_public_encrypt

用公鑰解密

RSA_private_decrypt

用私鑰加密

示例

        RSA*    rsa;
        int     bits = 1024;
        BIGNUM  *big_num;
        unsigned char *input_string, *encrypt_string, *decrypt_string;
        input_string = (unsigned char*)"123456";
        rsa = RSA_new();
        big_num = BN_new();
        BN_set_word(big_num, RSA_3);
        if(RSA_generate_key_ex(rsa, bits, big_num, NULL) != 1){
                printf("函數RSA_generate_key_ex返回失敗");
                return 1;
        }
        encrypt_string = (unsigned char*)calloc(RSA_size(rsa), sizeof(unsigned char));
        int encrypt_size = RSA_public_encrypt(strlen((char*)input_string),
                input_string, encrypt_string, rsa, RSA_PKCS1_OAEP_PADDING);
        decrypt_string = (unsigned char*)calloc(RSA_size(rsa), sizeof(unsigned char));
        int decrypt_size = RSA_private_decrypt(encrypt_size,
                    encrypt_string, decrypt_string, rsa, RSA_PKCS1_OAEP_PADDING);
        printf("encrypted string = ");
        for (int i=0; i < encrypt_size; ++i) {
                printf("%x%x", (encrypt_string[i] >> 4) & 0xf, encrypt_string[i] & 0xf);    
        }
        printf("\n");
        printf("decrypted string = %s\n", decrypt_string);

        RSA_free(rsa);
        free(encrypt_string);
        free(decrypt_string);
        return 0;
發佈了40 篇原創文章 · 獲贊 6 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章