Module: OpenPGP::Armor

Defined in:
lib/openpgp/armor.rb

Overview

OpenPGP ASCII Armor utilities.

Defined Under Namespace

Modules: Markers Classes: CRCError

Class Method Summary collapse

Class Method Details

.decode(text, marker = nil, options = {}) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/openpgp/armor.rb', line 55

def self.decode(text, marker = nil, options = {})
  data, crc, state = Buffer.new, nil, :begin

  text.each_line do |line|
    line.chomp!
    case state
      when :begin
        case line
          when /^-----BEGIN PGP ([^-]+)-----$/
            state = :head if marker.nil? || marker(marker) == $1
        end
      when :head
        state = :body if line =~ /^\s*$/
      when :body
        case line
          when /^=(....)$/
            crc = ("\0" << decode64($1)).unpack('N').first
            state = :end
          when /^-----END PGP ([^-]+)-----$/
            state = :end
          else
            data << decode64(line)
        end
      when :end
        break
    end
  end

  data = data.string
  if options[:crc] && crc != (crc_data = OpenPGP.crc24(data))
    raise CRCError.new("ASCII armor says 0x#{crc.to_s(16)}, but data has 0x#{crc_data.to_s(16)}")
  end
  data
end

.encode(data, marker = :message, options = {}) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/openpgp/armor.rb', line 38

def self.encode(data, marker = :message, options = {})
  Buffer.write do |text|
    text << self.header(marker)     << "\n"
    text << "Version: #{options[:version]}\n" if options[:version]
    text << "Comment: #{options[:comment]}\n" if options[:comment]
    if options[:headers]
      options[:headers].each { |key, value| text << "#{key}: #{value}\n" }
    end
    text << "\n" << encode64(data, options[:line_length])
    text << "="  << encode64([OpenPGP.crc24(data)].pack('N')[1, 3])
    text << self.footer(marker)     << "\n"
  end
end


30
31
32
# File 'lib/openpgp/armor.rb', line 30

def self.footer(marker)
  "-----END PGP #{marker(marker)}-----"
end

.header(marker) ⇒ Object



24
25
26
# File 'lib/openpgp/armor.rb', line 24

def self.header(marker)
  "-----BEGIN PGP #{marker(marker)}-----"
end

.marker(marker) ⇒ Object



17
18
19
20
# File 'lib/openpgp/armor.rb', line 17

def self.marker(marker)
  marker = Markers.const_get(marker.to_s.upcase.to_sym) if marker.is_a?(Symbol)
  marker.to_s.upcase
end