如何将 XML RSA 密钥转换为 PEM 文件?

发布于 2024-09-06 10:56:33 字数 711 浏览 6 评论 0 原文

我有两个 XML 文件,结构如下:

我的密钥

<RSAKeyValue>
  <Modulus> ... </Modulus>
  <Exponent> ... </Exponent>
  <P> ... </P>
  <Q> ... </Q>
  <DP> ... </DP>
  <DQ> ... </DQ>
  <InverseQ> ... </InverseQ>
  <D> ... </D>
</RSAKeyValue>

公钥

<RSAKeyValue>
   <Modulus> ... </Modulus>
   <Exponent> ... </Exponent>
</RSAKeyValue>

我正在使用 Robert Richards 的 xmlseclibs 库,它需要 .PEM密钥的表示形式,以便加密和解密事物。

作为一个加密新手,我不知道从哪里开始,粗略的谷歌搜索没有显示任何特别明显的东西......

谢谢!

I have two XML files, structured as follows:

My Key

<RSAKeyValue>
  <Modulus> ... </Modulus>
  <Exponent> ... </Exponent>
  <P> ... </P>
  <Q> ... </Q>
  <DP> ... </DP>
  <DQ> ... </DQ>
  <InverseQ> ... </InverseQ>
  <D> ... </D>
</RSAKeyValue>

A Public Key

<RSAKeyValue>
   <Modulus> ... </Modulus>
   <Exponent> ... </Exponent>
</RSAKeyValue>

I am using the xmlseclibs library by Robert Richards which requires a .PEM representation of the key in order to encrypt and decrypt things.

As an encryption novice, I'm not sure where to begin, and a cursory Google search did not reveal anything particularly obvious...

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

眼泪也成诗 2024-09-13 10:56:33

我找到了一个可以做到这一点的 Java 实用程序

I have found a Java utility that can do it.

墨小墨 2024-09-13 10:56:33

对于那些希望 BouncyCastle 能够读取生成的 PEM 的人:

  1. 请使用 XMLSec2PEM 工具获取 pem 文件
  2. 将 pem 转换为 pkcs8 并返回(!)

最终的解决方案我很高兴与:

  1. java XMLSec2PEM my.xml > my.pem
  2. 手动编辑 my.pem
  3. org.bouncycastle.openssl.PEMReader.readObject() 返回 null :- (
  4. openssl pkcs8 -topk8 -inform pem -in my.pem -outform pem -nocrypt -out my.pkcs8
  5. openssl pkcs8 -inform pem -nocrypt -in my.pkcs8 -out my.pkcs8 .pem
  6. 现在可以使用 PEMReader 读取 my.pkcs8.pem

For those who want the resulting PEM to be readable by BouncyCastle:

  1. use XMLSec2PEM tool to get a pem file
  2. convert pem to pkcs8 and back (!)

The final solution I am happy with:

  1. java XMLSec2PEM my.xml > my.pem
  2. edit my.pem manually a bit
  3. org.bouncycastle.openssl.PEMReader.readObject() returns null :-(
  4. openssl pkcs8 -topk8 -inform pem -in my.pem -outform pem -nocrypt -out my.pkcs8
  5. openssl pkcs8 -inform pem -nocrypt -in my.pkcs8 -out my.pkcs8.pem
  6. now my.pkcs8.pem is readable with the PEMReader
只有一腔孤勇 2024-09-13 10:56:33

我在 python 中的解决方案是这样的:

  1. 从 xml 中提取模数和指数
    xml = etree.fromstring(key_bin)
    模数 = xml.find('模数').text
    指数 = xml.find('指数').text
    
  2. 以 Base64 解码它们并迭代结果以将其保存为
    长度为2的字符串:

    mod_b64 = b64decode(modulus.encode())
    exp_b64 = b64decode(exponent.encode())
    exp = ''.join(['{:02x}'.format(x) for x in exp_b64])
    mod = ''.join(['{:02x}'.format(x) for x in mod_b64]) 
    
  3. 将十六进制字符串转换为整数并生成rsa
    rsa 库的公钥:

    exp_num = int(exp, 16)
    mod_num = int(mod, 16)
    rsa_key = rsa.PublicKey(mod_num, exp_num)
    
  4. 最后任何文本都可以被加密:
    msg_cryp = rsa.encrypt(msg.encode('ascii'), rsa_key)
    msg_cryp_str = b64encode(msg_cryp).decode('ascii') 
    

我进行此开发是为了使用一个 Web 服务,该服务要求从 XML 格式的公钥发送加密密码。通过这种方式,我成功地加密了密码并毫无问题地使用网络服务。

my solution in python works like this:

  1. extract modulus and exponent from xml
    xml = etree.fromstring(key_bin)
    modulus = xml.find('Modulus').text
    exponent = xml.find('Exponent').text
    
  2. decode them in base64 and iterate the result to save it as a
    character string of length 2:

    mod_b64 = b64decode(modulus.encode())
    exp_b64 = b64decode(exponent.encode())
    exp = ''.join(['{:02x}'.format(x) for x in exp_b64])
    mod = ''.join(['{:02x}'.format(x) for x in mod_b64]) 
    
  3. Convert the hexadecimal string to integer and generate the rsa
    public key with the rsa library:

    exp_num = int(exp, 16)
    mod_num = int(mod, 16)
    rsa_key = rsa.PublicKey(mod_num, exp_num)
    
  4. Finally any text can be encrypted:
    msg_cryp = rsa.encrypt(msg.encode('ascii'), rsa_key)
    msg_cryp_str = b64encode(msg_cryp).decode('ascii') 
    

I did this development to consume a web service which requires that an encrypted password be sent from a public key in XML format. In this way I managed to encrypt the password and consume the web service without problems.

波浪屿的海角声 2024-09-13 10:56:33

由于 xmlseclibs 是 PHP,因此似乎可能需要另一个 PHP 解决方案。具体方法如下:

<?php
include('Crypt/RSA.php');

$rsa = new Crypt_RSA();
$rsa->loadKey('<RSAKeyValue>
  <Modulus> ... </Modulus>
  <Exponent> ... </Exponent>
  <P> ... </P>
  <Q> ... </Q>
  <DP> ... </DP>
  <DQ> ... </DQ>
  <InverseQ> ... </InverseQ>
  <D> ... </D>
</RSAKeyValue>');

$privatekey = $rsa->getPrivateKey();
$publickey = $rsa->getPublicKey();
?>

phpseclib 内置了对 XML 密钥、PuTTY 密钥和 PKCS1 密钥的支持。它会自动检测格式并加载它,如果没有提供参数,getPrivateKey / getPublicKey 将默认输出 PKCS1 格式的密钥。更多信息:

http://phpseclib.sourceforge.net/rsa/examples.html#convert< /a>

Since xmlseclibs is PHP it seems like another PHP solution might be desirable. Here's how:

<?php
include('Crypt/RSA.php');

$rsa = new Crypt_RSA();
$rsa->loadKey('<RSAKeyValue>
  <Modulus> ... </Modulus>
  <Exponent> ... </Exponent>
  <P> ... </P>
  <Q> ... </Q>
  <DP> ... </DP>
  <DQ> ... </DQ>
  <InverseQ> ... </InverseQ>
  <D> ... </D>
</RSAKeyValue>');

$privatekey = $rsa->getPrivateKey();
$publickey = $rsa->getPublicKey();
?>

phpseclib has built in support for XML keys, PuTTY keys and PKCS1 keys. It'll auto detect the format and load it and getPrivateKey / getPublicKey will output PKCS1 formatted keys by default if no parameters are provided. More info:

http://phpseclib.sourceforge.net/rsa/examples.html#convert

带上头具痛哭 2024-09-13 10:56:33

这是一个 ruby​​ 版本脚本,用于将 RSA 转换为 pem,反之亦然。

  1. 确保 Ruby 已安装。

  2. 在终端中启动 irb

    <前><代码>> IRB

  3. 将以下代码粘贴到 irb 控制台。

    需要“openssl”
    需要“base64”
    需要“rexml/文档”
    
    类 PKeyRSAConverter
      def 初始化(from_pem:nil, from_xml:nil)
        @from_pem = from_pem
        @from_xml = from_xml
      结尾
    
      def to_xml
        xml = ''
        xml += "<模数>#{xml_base64(xml_pkey.n)}"
        xml += "<指数>#{xml_base64(xml_pkey.e)}"
        xml += ''
        XML
      结尾
    
      def to_pem
        pem_key.to_pem
      结尾
    
      私人的
    
      def pem_key
        指数 = xml_find_exponent.to_s
        模数 = xml_find_modulus.to_s
        密钥 = OpenSSL::PKey::RSA.new
        key.set_key(pem_base64(模数), pem_base64(指数), nil)
        钥匙
      结尾
    
      def xml_find_modulus
        REXML::XPath.match(xml_document.root, "//RSAKeyValue/Modulus/text()")[0]
      结尾
    
      def xml_find_exponent
        REXML::XPath.match(xml_document.root, "//RSAKeyValue/Exponent/text()")[0]
      结尾
    
      def xml_文档
        @xml_document ||= REXML::Document.new(@from_xml.to_s)
      结尾
    
      def pem_base64(字符串)
        Base64.urlsafe_decode64(string).bytes.inject(0){|a,e| (a << 8)| e }
      结尾
    
      def xml_pkey
        @xml_pkey ||= OpenSSL::PKey::RSA.new(@from_pem)
      结尾
    
      def xml_base64(int)
        Base64.encode64([int.to_s(16).downcase].pack('H*')).split("\n").join
      结尾
    结尾
    
  4. pem-> xml

    这是将 PEM 转换为 xml 的示例

    rsa_pem="-----开始公共密钥-----\nMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJYOlB8N/EdJL9nqEsRNF+No/9QkmPaX\n/xxpPleZTTNgakTkUlmyZPud8eEGsaX7nLgoVF39zTrXeg4hIeaWsAsCAweA AQ==\n-----结束公钥---- -\n"
    
    将“将 PEM 转换为 XML”
    to_xml = PKeyRSAConverter.new(from_pem: rsa_pem).to_xml
    放入 to_xml == rsa_xml
    
  5. xml ->质子交换膜

    这是将 xml 转换为 PEM 的示例

    rsa_xml="<模数>lg6UHw38R0kv2eoSxE0X42j/1CSY9pf/HGk+V5lNM2BqRORSWbJk+53x4QaxpfucuChUXf3NOtd6DiEh5pawCw==<指数>AQAB "
    
    将“将 XML 转换为 PEM”
    to_pem = PKeyRSAConverter.new(from_xml: rsa_xml).to_pem
    将 rsa_pem == to_pem
    

参考

  1. Github Gist: anicet/pkey_rsa_converter.rb

Here is a ruby version script to convert RSA to pem, vice versa.

  1. Make sure Ruby has been installed.

  2. start irb in your terminal

    > irb
    
  3. Paste the following code to the irb console.

    require 'openssl'
    require 'base64'
    require 'rexml/document'
    
    class PKeyRSAConverter
      def initialize(from_pem:nil, from_xml:nil)
        @from_pem = from_pem
        @from_xml = from_xml
      end
    
      def to_xml
        xml  = '<RSAKeyValue>'
        xml += "<Modulus>#{xml_base64(xml_pkey.n)}</Modulus>"
        xml += "<Exponent>#{xml_base64(xml_pkey.e)}</Exponent>"
        xml += '</RSAKeyValue>'
        xml
      end
    
      def to_pem
        pem_key.to_pem
      end
    
      private
    
      def pem_key
        exponent = xml_find_exponent.to_s
        modulus = xml_find_modulus.to_s
        key = OpenSSL::PKey::RSA.new
        key.set_key(pem_base64(modulus), pem_base64(exponent), nil)
        key
      end
    
      def xml_find_modulus
        REXML::XPath.match(xml_document.root, "//RSAKeyValue/Modulus/text()")[0]
      end
    
      def xml_find_exponent
        REXML::XPath.match(xml_document.root, "//RSAKeyValue/Exponent/text()")[0]
      end
    
      def xml_document
        @xml_document ||= REXML::Document.new(@from_xml.to_s)
      end
    
      def pem_base64(string)
        Base64.urlsafe_decode64(string).bytes.inject(0){|a,e| (a << 8)| e }
      end
    
      def xml_pkey
        @xml_pkey ||= OpenSSL::PKey::RSA.new(@from_pem)
      end
    
      def xml_base64(int)
        Base64.encode64([int.to_s(16).downcase].pack('H*')).split("\n").join
      end
    end
    
  4. pem -> xml

    Here is an example to convert PEM to xml

    rsa_pem="-----BEGIN PUBLIC KEY-----\nMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJYOlB8N/EdJL9nqEsRNF+No/9QkmPaX\n/xxpPleZTTNgakTkUlmyZPud8eEGsaX7nLgoVF39zTrXeg4hIeaWsAsCAwEAAQ==\n-----END     PUBLIC KEY-----\n"
    
    puts 'Convert PEM to XML'
    to_xml = PKeyRSAConverter.new(from_pem: rsa_pem).to_xml
    puts to_xml == rsa_xml
    
  5. xml -> pem

    Here is an example to convert xml to PEM

    rsa_xml="<RSAKeyValue><Modulus>lg6UHw38R0kv2eoSxE0X42j/1CSY9pf/HGk+V5lNM2BqRORSWbJk+53x4QaxpfucuChUXf3NOtd6DiEh5pawCw==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"
    
    puts 'Convert XML to PEM'
    to_pem = PKeyRSAConverter.new(from_xml: rsa_xml).to_pem
    puts rsa_pem == to_pem
    

Reference

  1. Github Gist: anicet/pkey_rsa_converter.rb
谁的年少不轻狂 2024-09-13 10:56:33

发现这个有用的在线工具RSA Key Converter,它支持

  • XML ->质子交换
  • 膜质子交换膜-> XML

Found this useful online tool RSA Key Converter, which supports

  • XML -> PEM
  • PEM -> XML
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文