Rework LuCI build system
[project/luci.git] / libs / luci-lib-px5g / lua / px5g / util.lua
1 --[[
2 * px5g - Embedded x509 key and certificate generator based on PolarSSL
3 *
4 * Copyright (C) 2009 Steven Barth <steven@midlink.org>
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License, version 2.1 as published by the Free Software Foundation.
9 ]]--
10
11 local nixio = require "nixio"
12 local table = require "table"
13
14 module "px5g.util"
15
16 local preamble = {
17 key = "-----BEGIN RSA PRIVATE KEY-----",
18 cert = "-----BEGIN CERTIFICATE-----",
19 request = "-----BEGIN CERTIFICATE REQUEST-----"
20 }
21
22 local postamble = {
23 key = "-----END RSA PRIVATE KEY-----",
24 cert = "-----END CERTIFICATE-----",
25 request = "-----END CERTIFICATE REQUEST-----"
26 }
27
28 function der2pem(data, type)
29 local b64 = nixio.bin.b64encode(data)
30
31 local outdata = {preamble[type]}
32 for i = 1, #b64, 64 do
33 outdata[#outdata + 1] = b64:sub(i, i + 63)
34 end
35 outdata[#outdata + 1] = postamble[type]
36 outdata[#outdata + 1] = ""
37
38 return table.concat(outdata, "\n")
39 end
40
41 function pem2der(data)
42 local b64 = data:gsub({["\n"] = "", ["%-%-%-%-%-.-%-%-%-%-%-"] = ""})
43 return nixio.bin.b64decode(b64)
44 end