已有十六進位格式的 RSA 公鑰(如 "123A123A...")與待加密資料("F12F45F1..."),需呼叫 RSA_public_encrypt (OpenSSL) 或同類 API。關鍵在於資料類型轉換。
// 1. 十六進位字串轉 BIGNUM
BIGNUM *bn = BN_new();
BN_hex2bn(&bn, "123A123A123F13123F123F123F12F1F1FFF");
// 2. 建立 RSA 結構並設定 n (modulus) 和 e (public exponent)
// 假設 e = 65537 (0x10001)
BIGNUM *e = BN_new();
BN_set_word(e, 65537);
RSA *rsa = RSA_new();
rsa->n = bn; // modulus
rsa->e = e; // public exponent
// 若有 d、p、q 等私鑰參數則對應設定,公鑰加密只需 n、e
// 將十六進位字串轉為 unsigned char 陣列
std::vector<unsigned char> data;
for (size_t i = 0; i < hexStr.length(); i += 2) {
data.push_back((unsigned char)strtol(hexStr.substr(i, 2).c_str(), nullptr, 16));
}
// data.data() 即為加密輸入緩衝區
int rsaSize = RSA_size(rsa);
std::vector<unsigned char> encrypted(rsaSize);
int len = RSA_public_encrypt(data.size(), data.data(), encrypted.data(), rsa, RSA_PKCS1_PADDING);
if (len == -1) { /* ERR_get_error() 處理錯誤 */ }
n 長度決定最大加密資料長度(PKCS#1 v1.5 padding 下為 rsaSize - 11 位元組)。RSA_free、BN_free 釋放資源。