| 1 | // Implements PEM (Privacy Enhanced Mail) data encoding |
| 2 | // according to RFC 1421 |
| 3 | module pem |
| 4 | |
| 5 | const pem_begin = '-----BEGIN ' |
| 6 | const pem_end = '\n-----END ' |
| 7 | const pem_eol = '-----' |
| 8 | const colon = ':' |
| 9 | |
| 10 | @[params] |
| 11 | pub struct EncodeConfig { |
| 12 | pub mut: |
| 13 | // inner text wrap around |
| 14 | line_length int = 64 |
| 15 | // line ending (alternatively '\r\n') |
| 16 | line_ending string = '\n' |
| 17 | } |
| 18 | |
| 19 | // Headers as described in RFC 1421 Section 9 |
| 20 | pub enum Header { |
| 21 | proctype |
| 22 | contentdomain |
| 23 | dekinfo |
| 24 | origid_asymm |
| 25 | origid_symm |
| 26 | recipid_asymm |
| 27 | recipid_symm |
| 28 | cert |
| 29 | issuercert |
| 30 | micinfo |
| 31 | keyinfo |
| 32 | crl |
| 33 | } |
| 34 | |
| 35 | // str returns the string representation of the header |
| 36 | pub fn (header Header) str() string { |
| 37 | return match header { |
| 38 | .proctype { 'Proc-Type' } |
| 39 | .contentdomain { 'Content-Domain' } |
| 40 | .dekinfo { 'DEK-Info' } |
| 41 | .origid_asymm { 'Originator-ID-Asymmetric' } |
| 42 | .origid_symm { 'Originator-ID-Symmetric' } |
| 43 | .recipid_asymm { 'Recipient-ID-Asymmetric' } |
| 44 | .recipid_symm { 'Recipient-ID-Symmetric' } |
| 45 | .cert { 'Originator-Certificate' } |
| 46 | .issuercert { 'Issuer-Certificate' } |
| 47 | .micinfo { 'MIC-Info' } |
| 48 | .keyinfo { 'Key-Info' } |
| 49 | .crl { 'CRL' } |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | pub struct Block { |
| 54 | pub mut: |
| 55 | // from preamble |
| 56 | block_type string |
| 57 | // optional headers |
| 58 | headers map[string][]string |
| 59 | // decoded contents |
| 60 | data []u8 |
| 61 | } |
| 62 | |
| 63 | // Block.new returns a new `Block` with the specified block_type |
| 64 | @[inline] |
| 65 | pub fn Block.new(block_type string) Block { |
| 66 | return Block{ |
| 67 | block_type: block_type |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | // free the resources taken by the Block `block` |
| 72 | @[unsafe] |
| 73 | pub fn (mut block Block) free() { |
| 74 | $if prealloc { |
| 75 | return |
| 76 | } |
| 77 | unsafe { |
| 78 | block.block_type.free() |
| 79 | block.headers.free() |
| 80 | block.data.free() |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | // header_by_key returns the selected key using the Header enum |
| 85 | // |
| 86 | // same as `block.headers[key.str()]` |
| 87 | @[inline] |
| 88 | pub fn (block Block) header_by_key(key Header) []string { |
| 89 | return block.headers[key.str()] |
| 90 | } |
| 91 | |