|
| 1 | +#include <fstream> |
| 2 | +#include <openssl/evp.h> |
| 3 | +#include "x509_certificate.pb.h" |
| 4 | + |
| 5 | +#include "asn1_pdu_to_der.h" |
| 6 | +#include "x509_certificate_to_der.h" |
| 7 | + |
| 8 | +std::string base64_encode(const unsigned char *buf, int len) { |
| 9 | + const auto expected_size = 4 * ((len + 2) / 3); |
| 10 | + auto output = reinterpret_cast<char *>(calloc(expected_size + 1, 1)); |
| 11 | + const auto actual_size = EVP_EncodeBlock(reinterpret_cast<unsigned char *>(output), buf, len); |
| 12 | + if (expected_size != actual_size) { |
| 13 | + std::cerr << "Wrong base64 output length: expected " << expected_size << " but got " << actual_size << ".\n"; |
| 14 | + } |
| 15 | + return output; |
| 16 | +} |
| 17 | + |
| 18 | +std::string readFile(const char* path) { |
| 19 | + printf("Reading file at %s\n", path); |
| 20 | + std::ifstream file(path, std::ios::in | std::ios::binary); |
| 21 | + std::string str = std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); |
| 22 | + printf("Read %ld bytes\n\n", str.length()); |
| 23 | + return str; |
| 24 | +} |
| 25 | + |
| 26 | +void writeFile(const char* path, std::vector<uint8_t> data) { |
| 27 | + printf("Writing %ld bytes to %s\n", data.size(), path); |
| 28 | + std::ofstream file(path, std::ios::out | std::ios::binary); |
| 29 | + std::copy(data.begin(), data.end(), std::ostreambuf_iterator<char>(file)); |
| 30 | +} |
| 31 | + |
| 32 | +int main(int argc, char **argv) { |
| 33 | + if (argc != 3) { |
| 34 | + printf("Usage: ./protobuf_to_der.o <in file> <out file>\n"); |
| 35 | + return 1; |
| 36 | + } |
| 37 | + |
| 38 | + std::string protobuf = readFile(argv[1]); |
| 39 | + std::string b64Protobuf = base64_encode((unsigned char *)protobuf.c_str(), protobuf.length()); |
| 40 | + printf("Protobuf: %s\n\n", b64Protobuf.c_str()); |
| 41 | + |
| 42 | + x509_certificate::X509Certificate input; |
| 43 | + bool parse_ok = input.ParseFromArray(protobuf.c_str(), protobuf.length()); |
| 44 | + if (!parse_ok) { |
| 45 | + printf("ParseFromArray failed!\n"); |
| 46 | + return 1; |
| 47 | + } |
| 48 | + |
| 49 | + std::string serialized; |
| 50 | + input.SerializeToString(&serialized); |
| 51 | + std::string b64Serialized = base64_encode((unsigned char *)serialized.c_str(), serialized.length()); |
| 52 | + printf("Re-serialized protobuf: %s\n\n", b64Serialized.c_str()); |
| 53 | + |
| 54 | + std::vector<uint8_t> asn1 = x509_certificate::X509CertificateToDER(input); |
| 55 | + |
| 56 | + std::string b64asn1 = base64_encode(asn1.data(), asn1.size()); |
| 57 | + printf("ASN.1: %s\n", b64asn1.c_str()); |
| 58 | + |
| 59 | + writeFile(argv[2], asn1); |
| 60 | + |
| 61 | + return 0; |
| 62 | +} |
0 commit comments