OpenSSLでRSA暗号処理
概要
OpenSSLが提供しているC言語のAPIを使ってRSA暗号を実施します。パディングはOAEPを利用します。OpenSSLのマニュアルにも公開鍵での暗号処理のパディングはOAEPを推奨しています。
利用するAPI
RSA暗号を実行するためのAPI
- RSA_new()
RSA構造体を初期化します。 - RSA_public_encrypt()
公開鍵を利用してメッセージを暗号化します。 - RSA_private_decrypt()
秘密鍵を利用して暗号文を復号します。 - RSA_free()
RSA構造体を解放します。
サンプルプログラム
RSA暗号処理を実行する
この例では"Trusted Design encrypto message."というメッセージを暗号処理します。
RSA暗号の場合,通常は鍵はあらかじめ作ってあり,公開鍵は認証局に署名された公開鍵証明書として保持されています。今回は,サンプルの中で鍵生成も実施しています。
#include "openssl/rsa.h"
#include "openssl/err.h"
/*
バイト列を出力する関数
*/
int PrintBytes(unsigned char* bytes, unsigned int bytesLen)
{
for (int i = 1; i <= bytesLen; i++) {
printf("%02x ", *bytes++);
if (i % 16 == 0) printf("\n");
}
printf("\n");
return 1;
}
int main()
{
/* RSA鍵生成のためBIGNUMを利用する */
BIGNUM* bn = NULL;
unsigned long long e = RSA_F4; // 65537
bn = BN_new();
BN_set_word(bn, e);
RSA* rsa = NULL;
const unsigned char from[] = { "Trusted Design encrypto message." };
int fromLen = sizeof(from);
unsigned char to[128]; // 1024bit暗号
int bits = 1024; // 鍵長
int rtn = 0;
rsa = RSA_new();
/* テスト用にRSA鍵ペアを生成する。通常は既存の鍵ペアを利用する。*/
if (!RSA_generate_key_ex(rsa, bits, bn, NULL))
{
/* Error */
printf("Error: %s\n", ERR_reason_error_string(ERR_get_error()));
return 0;
}
/* RSA暗号処理 */
rtn = RSA_public_encrypt(fromLen, from, to, rsa, RSA_PKCS1_OAEP_PADDING);
if (rtn == -1) {
/* Error */
printf("Error: %s\n", ERR_reason_error_string(ERR_get_error()));
return 0;
}
PrintBytes(to, rtn);
/* RSA復号処理 */
rtn = RSA_private_decrypt(rtn, to, to, rsa, RSA_PKCS1_OAEP_PADDING);
if (rtn == -1) {
/* Error */
printf("Error: %s\n", ERR_reason_error_string(ERR_get_error()));
return 0;
}
printf("Message is : %s", to);
RSA_free(rsa);
BN_free(bn);
}
実行結果
暗号処理の実行結果です。
98 eb 4e df 87 03 a6 e5 27 10 0e ba 7b a0 ca a7
0f 74 af b2 09 f5 0d d5 38 2e f8 6a 45 61 f7 87
ca 19 00 15 9c d5 10 b5 75 92 ae a2 e0 6e b2 41
d8 71 b2 54 eb 93 c3 69 fe 28 d9 1e ba e6 20 89
3e 71 b1 0e 09 25 19 13 d2 a2 e3 40 07 09 ff c5
e7 74 3c 78 9b da 59 d4 d2 61 fd ab cc 0b 18 bf
f7 77 f3 f3 91 21 98 65 9e 8d 2a 07 a8 be c3 56
c3 58 6b 25 2e db 14 f5 84 1e e9 1a cb 51 9c 47
Message is : Trusted Design encrypto message.