Comparison

util/x509.lua @ 6152:fbab74c28e31

util.x509: And functions for converting between DER and PEM
author Kim Alvefur <zash@zash.se>
date Thu, 24 Apr 2014 23:38:47 +0200
parent 5845:c48f717c2fd6
child 6153:8fb54ec34741
comparison
equal deleted inserted replaced
6149:2ae6e9063e88 6152:fbab74c28e31
18 -- [LDAP] - http://tools.ietf.org/html/rfc4519 18 -- [LDAP] - http://tools.ietf.org/html/rfc4519
19 -- [PKIX] - http://tools.ietf.org/html/rfc5280 19 -- [PKIX] - http://tools.ietf.org/html/rfc5280
20 20
21 local nameprep = require "util.encodings".stringprep.nameprep; 21 local nameprep = require "util.encodings".stringprep.nameprep;
22 local idna_to_ascii = require "util.encodings".idna.to_ascii; 22 local idna_to_ascii = require "util.encodings".idna.to_ascii;
23 local base64 = require "util.encodings".base64;
23 local log = require "util.logger".init("x509"); 24 local log = require "util.logger".init("x509");
24 local pairs, ipairs = pairs, ipairs; 25 local pairs, ipairs = pairs, ipairs;
25 local s_format = string.format; 26 local s_format = string.format;
26 local t_insert = table.insert; 27 local t_insert = table.insert;
27 local t_concat = table.concat; 28 local t_concat = table.concat;
212 213
213 -- If all else fails, well, why should we be any different? 214 -- If all else fails, well, why should we be any different?
214 return false 215 return false
215 end 216 end
216 217
218 local pat = "%-%-%-%-%-BEGIN ([A-Z ]+)%-%-%-%-%-\r?\n"..
219 "([0-9A-Za-z+/=\r\n]*)\r?\n%-%-%-%-%-END %1%-%-%-%-%-";
220
221 function pem2der(pem)
222 local typ, data = pem:match(pat);
223 if typ and data then
224 return base64.decode(data), typ;
225 end
226 end
227
228 local wrap = ('.'):rep(64);
229 local envelope = "-----BEGIN %s-----\n%s\n-----END %s-----\n"
230
231 function der2pem(data, typ)
232 typ = typ and typ:upper() or "CERTIFICATE";
233 data = base64.encode(data);
234 return s_format(envelope, typ, data:gsub(wrap, '%0\n', (#data-1)/64), typ);
235 end
236
217 return _M; 237 return _M;