I need help
require 'openssl'
Encoding.default_external = Encoding::UTF_8
certificate = OpenSSL::X509::Certificate.new(File.open('!^9e1209.cer'))
puts certificate.subject
from this cert file: cert file i get subject such as:
: /C=UA/ST=\xD0\x96\xD0\xB8\xD1\x82\xD0\xBE\xD0\xBC\xD0\xB8\xD1\x80\
but if i copy this string from windows console and paste in editor:
Encoding.default_external = Encoding::UTF_8
puts a = "/C=UA/ST=\xD0\x96\xD0\xB8\xD1\x82\xD0\xBE\xD0\xBC\xD0\xB8\xD1\x80\xD"
i get:
: /C=UA/ST=Житомир
what can i do for encoding certificate.subject immediately after extraction from certificate?
I stumbled upon your question while searching for another related issue with X509 certificates and Ruby. Having already seen this issue in the ruby/openssl Github repository (issue 26), you can use the code in the original question to solve your own.
require 'openssl'
### Note 1 ###
# I had to look this up in the OpenSSL include files.
# I couldn't find it in ruby anyplace.
ASN1_STRFLGS_ESC_MSB = 4
Encoding.default_external = Encoding::UTF_8
certificate = OpenSSL::X509::Certificate.new(File.open('!^9e1209.cer'))
i_expected_this_to_work = certificate.subject.to_s
puts i_expected_this_to_work
puts i_expected_this_to_work.encoding
# Following instructions from https://wiki.openssl.org/index.php/Manual:X509_NAME_print_ex(3)
# to get UTF-8.
puts
puts 'The "Using magic flags" approach'
oh_so_close = certificate.subject.to_s(OpenSSL::X509::Name::ONELINE & ~ASN1_STRFLGS_ESC_MSB)
puts oh_so_close
puts oh_so_close.encoding
puts
puts 'The "Fix the magic flags" approach'
corrected_approach = oh_so_close.force_encoding(Encoding::UTF_8)
puts corrected_approach
puts corrected_approach.encoding
The result will be:
/C=UA/ST=\xD0\x96\xD0\xB8\xD1\x82\xD0\xBE\xD0\xBC\xD0\xB8\xD1\x80\xD1\x81\xD1\x8C\xD0\xBA\xD0\xB0/L=\xD0\x96\xD0\xB8\xD1\x82\xD0\xBE\xD0\xBC\xD0\xB8\xD1\x80/O=\xD0\xA3\xD0\xBF\xD1\x80\xD0\xB0\xD0\xB2\xD0\xBB\xD1\x96\xD0\x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9F\xD0\xB5\xD1\x82\xD1\x80\xD0\xBE\xD0\xB2\xD0\xB8\xD1\x87/serialNumber=00000DF9/UID=9E1209
ASCII-8BIT
The "Using magic flags" approach
C = UA, ST = Житомирська, L = Житомир, O = Управління НБУ в Житомирській області, OU = Відділ готівкового обігу і касових операцій, OU = Сектор касових операцій та зберігання цінностей, title = старший касир, CN = Бодров Микола Петрович, serialNumber = 00000DF9, UID = 9E1209
ASCII-8BIT
The "Fix the magic flags" approach
C = UA, ST = Житомирська, L = Житомир, O = Управління НБУ в Житомирській області, OU = Відділ готівкового обігу і касових операцій, OU = Сектор касових операцій та зберігання цінностей, title = старший касир, CN = Бодров Микола Петрович, serialNumber = 00000DF9, UID = 9E1209
UTF-8
Good luck!