2
0

util.lua 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. local nixio = require "nixio"
  11. local table = require "table"
  12. module "px5g.util"
  13. local preamble = {
  14. key = "-----BEGIN RSA PRIVATE KEY-----",
  15. cert = "-----BEGIN CERTIFICATE-----",
  16. request = "-----BEGIN CERTIFICATE REQUEST-----"
  17. }
  18. local postamble = {
  19. key = "-----END RSA PRIVATE KEY-----",
  20. cert = "-----END CERTIFICATE-----",
  21. request = "-----END CERTIFICATE REQUEST-----"
  22. }
  23. function der2pem(data, type)
  24. local b64 = nixio.bin.b64encode(data)
  25. local outdata = {preamble[type]}
  26. for i = 1, #b64, 64 do
  27. outdata[#outdata + 1] = b64:sub(i, i + 63)
  28. end
  29. outdata[#outdata + 1] = postamble[type]
  30. outdata[#outdata + 1] = ""
  31. return table.concat(outdata, "\n")
  32. end
  33. function pem2der(data)
  34. local b64 = data:gsub({["\n"] = "", ["%-%-%-%-%-.-%-%-%-%-%-"] = ""})
  35. return nixio.bin.b64decode(b64)
  36. end