티스토리 뷰

728x90
반응형
순수 C++로 RSA 키 PEM 저장 및 불러오기

순수 C++로 RSA 키 PEM 저장 및 불러오기

🧠 설명

이 코드는 OpenSSL 없이 순수 C++만을 이용하여 RSA 2048비트 키를 PEM 파일 형식으로 저장하거나 불러올 수 있도록 구현한 예제입니다. 공개키, 개인키 모두 지원하며, KCMVP 인증용, 경량 시스템, 보안 제품 개발 시 매우 유용합니다.

🧩 원인

  • 외부 라이브러리에 의존하지 않고 독립적인 PEM 처리 구현 필요
  • KCMVP, CC 인증 등 보안 요구사항 충족
  • 경량 OS 또는 보안 펌웨어에서 사용 목적

🧰 핵심 기능

  • PEM 파일에서 Base64 부분 추출: LoadPem()
  • Base64 ↔ 바이너리 변환: Base64Encode(), Base64Decode()
  • PEM 저장: SavePrivateKeyToPemFile(), SavePublicKeyToPemFile()
  • 구조체나 DER 데이터를 PEM으로 저장: ExportPrivateKeyToPemFile(), ExportPublicKeyToPemFile()

✅ 예제 코드

1. Base64 인코딩

std::vector<unsigned char> der = { 0x30, 0x82, 0x01, 0x0a, ... }; // DER 데이터
std::string base64;
rsa::RsaKeyLoader::Base64Encode(der, base64);

2. PEM 저장

// 직접 저장
rsa::RsaKeyLoader::SavePrivateKeyToPemFile("my_priv.pem", base64);

// 혹은 DER → PEM까지 한 번에
rsa::RsaKeyLoader::ExportPrivateKeyToPemFile("my_priv.pem", der);

3. PEM 파일 로딩

std::string base64Loaded;
rsa::RsaKeyLoader::LoadPem("my_priv.pem", base64Loaded);

📌 전체 예제

#include "RsaKeyLoader.hpp"
#include <iostream>

int main() {
    std::vector<unsigned char> der = { /* DER-encoded private key */ };
    std::string path = "rsa_priv.pem";

    if (rsa::RsaKeyLoader::ExportPrivateKeyToPemFile(path, der)) {
        std::cout << "PEM 저장 성공: " << path << std::endl;
    } else {
        std::cerr << "저장 실패" << std::endl;
    }

    std::string loadedBase64;
    if (rsa::RsaKeyLoader::LoadPem(path, loadedBase64)) {
        std::cout << "Base64 길이: " << loadedBase64.size() << std::endl;
    }
}

🔐 마무리

이 구현은 완전히 독립적으로 동작하며, 어떠한 외부 라이브러리(OpenSSL 포함)에도 의존하지 않습니다. PEM 포맷 저장/불러오기, Base64 인코딩/디코딩, 구조체 ↔ DER 변환 기능이 필요한 모든 보안 프로젝트에 활용될 수 있습니다.

📁 전체 소스 코드

🔹 RsaKeyLoader.hpp

#pragma once

#include 
#include 
#include 

#ifndef IN
#define IN
#endif
#ifndef OUT
#define OUT
#endif
#ifndef INOUT
#define INOUT
#endif

struct stRsa2048PublicKey {
    uint32_t bits = 2048;
    uint32_t n_dat[66] = {0};
    uint32_t e_dat[66] = {0};
};

struct stRsa2048PrivateKey {
    uint32_t bits = 2048;
    uint32_t n_dat[66] = {0};
    uint32_t e_dat[66] = {0};
#if defined(NO_USE_CRT)
    uint32_t d_dat[66] = {0};
#elif defined(USE_CRT)
    uint32_t p_dat[66] = {0};
    uint32_t q_dat[66] = {0};
    uint32_t dmp1_dat[66] = {0};
    uint32_t dmq1_dat[66] = {0};
    uint32_t qimp_dat[66] = {0};
#endif
};

namespace rsa {
class RsaKeyLoader {
public:
    static bool LoadPem(IN const std::string& _filePath, OUT std::string& _base64Out) noexcept;
    static bool SavePrivateKeyToPemFile(IN const std::string& _filePath, IN const std::string& _base64Data) noexcept;
    static bool SavePublicKeyToPemFile(IN const std::string& _filePath, IN const std::string& _base64Data) noexcept;
    static bool ExportPrivateKeyToPemFile(IN const std::string& _filePath, IN const std::vector& _der) noexcept;
    static bool ExportPublicKeyToPemFile(IN const std::string& _filePath, IN const std::vector& _der) noexcept;

    static bool Base64Encode(IN const std::vector& _input, OUT std::string& _output) noexcept;
    static bool Base64Decode(IN const std::string& _input, OUT std::vector& _output) noexcept;
};
} // namespace rsa

🔹 RsaKeyLoader.cpp

#include "RsaKeyLoader.hpp"
#include 
#include 
#include 
#include 

namespace rsa {

bool RsaKeyLoader::LoadPem(IN const std::string& _filePath, OUT std::string& _base64Out) noexcept {
    std::ifstream file(_filePath);
    if (!file.is_open()) return false;

    std::stringstream ss;
    ss << file.rdbuf();
    std::string pem = ss.str();

    size_t begin = pem.find("-----BEGIN");
    size_t end = pem.find("-----END");
    if (begin == std::string::npos || end == std::string::npos) return false;

    begin = pem.find('\n', begin);
    end = pem.rfind('\n', end);
    if (begin == std::string::npos || end == std::string::npos || begin >= end) return false;

    _base64Out = pem.substr(begin + 1, end - begin - 1);
    _base64Out.erase(std::remove(_base64Out.begin(), _base64Out.end(), '\n'), _base64Out.end());
    _base64Out.erase(std::remove(_base64Out.begin(), _base64Out.end(), '\r'), _base64Out.end());
    return true;
}

bool RsaKeyLoader::SavePrivateKeyToPemFile(IN const std::string& _filePath, IN const std::string& _base64Data) noexcept {
    std::ofstream file(_filePath);
    if (!file.is_open()) return false;

    file << "-----BEGIN RSA PRIVATE KEY-----\n";
    for (size_t i = 0; i < _base64Data.size(); i += 64)
        file << _base64Data.substr(i, 64) << "\n";
    file << "-----END RSA PRIVATE KEY-----\n";
    return true;
}

bool RsaKeyLoader::SavePublicKeyToPemFile(IN const std::string& _filePath, IN const std::string& _base64Data) noexcept {
    std::ofstream file(_filePath);
    if (!file.is_open()) return false;

    file << "-----BEGIN RSA PUBLIC KEY-----\n";
    for (size_t i = 0; i < _base64Data.size(); i += 64)
        file << _base64Data.substr(i, 64) << "\n";
    file << "-----END RSA PUBLIC KEY-----\n";
    return true;
}

bool RsaKeyLoader::Base64Encode(IN const std::vector& _input, OUT std::string& _output) noexcept {
    static const char base64_chars[] =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

    _output.clear();
    int val = 0, valb = -6;
    for (unsigned char c : _input) {
        val = (val << 8) + c;
        valb += 8;
        while (valb >= 0) {
            _output.push_back(base64_chars[(val >> valb) & 0x3F]);
            valb -= 6;
        }
    }
    if (valb > -6) _output.push_back(base64_chars[((val << 8) >> (valb + 8)) & 0x3F]);
    while (_output.size() % 4) _output.push_back('=');
    return true;
}

bool RsaKeyLoader::Base64Decode(IN const std::string& _input, OUT std::vector& _output) noexcept {
    static const std::string base64_chars =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

    size_t in_len = _input.size();
    int i = 0, j = 0, in_ = 0;
    unsigned char char_array_4[4], char_array_3[3];
    _output.clear();

    while (in_len-- && (_input[in_] != '=') &&
           (isalnum(_input[in_]) || (_input[in_] == '+') || (_input[in_] == '/'))) {
        char_array_4[i++] = _input[in_++];
        if (i == 4) {
            for (i = 0; i < 4; ++i)
                char_array_4[i] = static_cast(base64_chars.find(char_array_4[i]));

            char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
            char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
            char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

            for (i = 0; i < 3; ++i)
                _output.push_back(char_array_3[i]);
            i = 0;
        }
    }

    if (i) {
        for (j = i; j < 4; ++j)
            char_array_4[j] = 0;

        for (j = 0; j < 4; ++j)
            char_array_4[j] = static_cast(base64_chars.find(char_array_4[j]));

        char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
        char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
        char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

        for (j = 0; j < i - 1; ++j)
            _output.push_back(char_array_3[j]);
    }
    return true;
}

bool RsaKeyLoader::ExportPrivateKeyToPemFile(IN const std::string& _filePath, IN const std::vector& _der) noexcept {
    std::string base64;
    if (!Base64Encode(_der, base64)) return false;
    return SavePrivateKeyToPemFile(_filePath, base64);
}

bool RsaKeyLoader::ExportPublicKeyToPemFile(IN const std::string& _filePath, IN const std::vector& _der) noexcept {
    std::string base64;
    if (!Base64Encode(_der, base64)) return false;
    return SavePublicKeyToPemFile(_filePath, base64);
}

} // namespace rsa
728x90
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함