2011-03-18 02:51:52 +01:00
|
|
|
# -*- ruby encoding: utf-8 -*-
|
2010-03-20 05:18:10 +01:00
|
|
|
require 'stringio'
|
|
|
|
|
2010-04-19 07:52:57 +02:00
|
|
|
##
|
|
|
|
# BER extensions to the String class.
|
2010-03-20 05:18:10 +01:00
|
|
|
module Net::BER::Extensions::String
|
|
|
|
##
|
|
|
|
# Converts a string to a BER string. Universal octet-strings are tagged
|
|
|
|
# with 0x04, but other values are possible depending on the context, so we
|
|
|
|
# let the caller give us one.
|
|
|
|
#
|
|
|
|
# User code should call either #to_ber_application_string or
|
|
|
|
# #to_ber_contextspecific.
|
|
|
|
def to_ber(code = 0x04)
|
2011-09-09 18:47:39 +02:00
|
|
|
raw_string = raw_utf8_encoded
|
|
|
|
[code].pack('C') + raw_string.length.to_ber_length_encoding + raw_string
|
2010-03-20 05:18:10 +01:00
|
|
|
end
|
|
|
|
|
2011-09-09 18:47:39 +02:00
|
|
|
def raw_utf8_encoded
|
|
|
|
if self.respond_to?(:encode)
|
|
|
|
# Strings should be UTF-8 encoded according to LDAP.
|
|
|
|
# However, the BER code is not necessarily valid UTF-8
|
|
|
|
self.encode('UTF-8').force_encoding('ASCII-8BIT')
|
|
|
|
else
|
|
|
|
self
|
|
|
|
end
|
|
|
|
end
|
|
|
|
private :raw_utf8_encoded
|
|
|
|
|
2010-03-20 05:18:10 +01:00
|
|
|
##
|
|
|
|
# Creates an application-specific BER string encoded value with the
|
|
|
|
# provided syntax code value.
|
|
|
|
def to_ber_application_string(code)
|
|
|
|
to_ber(0x40 + code)
|
|
|
|
end
|
|
|
|
|
|
|
|
##
|
|
|
|
# Creates a context-specific BER string encoded value with the provided
|
|
|
|
# syntax code value.
|
|
|
|
def to_ber_contextspecific(code)
|
|
|
|
to_ber(0x80 + code)
|
|
|
|
end
|
|
|
|
|
|
|
|
##
|
|
|
|
# Nondestructively reads a BER object from this string.
|
|
|
|
def read_ber(syntax = nil)
|
|
|
|
StringIO.new(self).read_ber(syntax)
|
|
|
|
end
|
2010-03-20 14:18:15 +01:00
|
|
|
|
2010-03-20 05:18:10 +01:00
|
|
|
##
|
2010-03-20 14:18:15 +01:00
|
|
|
# Destructively reads a BER object from the string.
|
2010-03-20 15:04:32 +01:00
|
|
|
def read_ber!(syntax = nil)
|
2010-03-20 14:18:15 +01:00
|
|
|
io = StringIO.new(self)
|
|
|
|
|
|
|
|
result = io.read_ber(syntax)
|
|
|
|
self.slice!(0...io.pos)
|
|
|
|
|
|
|
|
return result
|
2010-03-20 05:18:10 +01:00
|
|
|
end
|
|
|
|
end
|