OpenSSLでRSAパディング実施
概要
OpenSSLが提供しているC言語のAPIを使ってRSAパディングを実施します。RSAでは暗号や署名を実行するメッセージは鍵長と同じ長さにする必要があります。そこで,パディングを実施します。
パディングの方式は複数あって,今回はPKCS#1の方式とOAEPの方式を紹介します。OAEPパディングはRSAの暗号/復号処理で推奨されています。
利用するAPI
RSAパディングを実行するためのAPI
- RSA_padding_add_PKCS1_type_1()
PKCS#1形式で与えられたメッセージにパディングを付加します。 - RSA_padding_check_PKCS1_type_1()
正しくパディングされているかを検証します。 - RSA_padding_add_PKCS1_OAEP()
OAEP形式で与えられたメッセージにパディングを付加します。 - RSA_padding_check_PKCS1_OAEP()
正しくパディングされているかを検証します。
サンプルプログラム
RSAパディングを実行する
この例では"Trusted Design add Padding."というメッセージにパディングを付加します。
#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()
{
unsigned char to[128]; // パディング付加したデータを格納するバッファ
int tlen = 128; // バイト数(通常は鍵長)
const unsigned char f[] = { "Trusted Design add Padding." };
int flen = sizeof(f);
int ret = 0;
unsigned char msg[128]; // 検証のためのバッファ
int msglen = 128;
/* PKCS#1パディングを行う */
ret = RSA_padding_add_PKCS1_type_1(to, tlen, f, flen);
if (ret == -1) {
/* Error */
printf("Error: %s\n", ERR_reason_error_string(ERR_get_error()));
return 0;
}
PrintBytes(to, tlen);
/* PKCS#1パディングの検証を行う */
ret = RSA_padding_check_PKCS1_type_1(msg, msglen,to, tlen, tlen);
if (ret == -1) {
/* Error */
printf("Error: %s\n", ERR_reason_error_string(ERR_get_error()));
return 0;
}
printf("Message is : %s\n\n", msg);
/* OAEPパディングを行う */
memset(to, 0x00, tlen);
ret = RSA_padding_add_PKCS1_OAEP(to, tlen, f, flen, NULL, 0);
if (ret == -1) {
/* Error */
printf("Error: %s\n", ERR_reason_error_string(ERR_get_error()));
return 0;
}
PrintBytes(to, tlen);
/* OAEPパディングの検証を行う */
ret = RSA_padding_check_PKCS1_OAEP(msg, msglen, to, tlen, tlen, NULL, 0);
if (ret == -1) {
/* Error */
printf("Error: %s\n", ERR_reason_error_string(ERR_get_error()));
return 0;
}
printf("Message is : %s\n", msg);
}
実行結果
パディング実行結果です。PKCS#1形式のパディングは,0xffでパディングされていることがわかります。一方のOAEPパディングは元のメッセージも含めてすぐにはわからないバイト列になっています。
00 01 ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
ff ff ff 00 54 72 75 73 74 65 64 20 44 65 73 69
67 6e 20 61 64 64 20 50 61 64 64 69 6e 67 2e 00
Message is : Trusted Design add Padding.
00 1c 46 72 f8 ba 3e 32 5a 75 c1 2a b8 3d c9 73
b0 fc 09 d9 be 2e 22 59 8e ad f1 b8 02 e4 f8 3e
44 48 f1 34 32 81 d8 9d b6 0f f5 51 49 65 4b c3
b9 dc 5a 38 01 a0 53 43 c7 c3 8f de cf 60 78 63
18 a2 83 b4 5d 15 a5 e3 a3 10 f2 f5 88 a0 bf d6
f2 d1 df 9d 5d 80 d3 ad 89 dc 24 41 bf 93 8f de
d5 09 c0 65 0b 09 82 7e 33 ad 5c 38 ac 44 07 ba
b9 d0 41 45 d2 72 0e 07 97 72 90 28 22 29 27 de
Message is : Trusted Design add Padding.