python模拟生成微软序列号程序_如何使用Python生成SSH密钥对

I'm attempting to write a script to generate SSH Identity key pairs for me.

from M2Crypto import RSA

key = RSA.gen_key(1024, 65337)

key.save_key("/tmp/my.key", cipher=None)

The file /tmp/my.key looks great now.

By running ssh-keygen -y -f /tmp/my.key > /tmp/my.key.pub I can extract the public key.

My question is how can I extract the public key from python? Using key.save_pub_key("/tmp/my.key.pub") saves something like:

-----BEGIN PUBLIC KEY-----

MFwwDQYJKoZIhvcNAQEBBQADASDASDASDASDBarYRsmMazM1hd7a+u3QeMP

...

FZQ7Ic+BmmeWHvvVP4Yjyu1t6vAut7mKkaDeKbT3yiGVUgAEUaWMXqECAwEAAQ==

-----END PUBLIC KEY-----

When I'm looking for something like:

ssh-rsa AAAABCASDDBM$%3WEAv/3%$F ..... OSDFKJSL43$%^DFg==

解决方案

Use cryptography! pycrypto is not in active development anymore and if possible you should be using cryptography. Since June it's possible to generate SSH public keys as well:

from cryptography.hazmat.primitives import serialization as crypto_serialization

from cryptography.hazmat.primitives.asymmetric import rsa

from cryptography.hazmat.backends import default_backend as crypto_default_backend

key = rsa.generate_private_key(

backend=crypto_default_backend(),

public_exponent=65537,

key_size=2048

)

private_key = key.private_bytes(

crypto_serialization.Encoding.PEM,

crypto_serialization.PrivateFormat.PKCS8,

crypto_serialization.NoEncryption())

public_key = key.public_key().public_bytes(

crypto_serialization.Encoding.OpenSSH,

crypto_serialization.PublicFormat.OpenSSH

)

Note: You need at least version 1.4.0.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值