opensslラッパー
pycryptoをインストールするのは案外大変だったので,多くの環境で既にインストールされていると思われるopensslを使って,RSAに関連する機能のラッパーを作成してみました.rsabyopenssl.py←右クリックで保存できます.
#!/usr/bin/evn python #conding: utf-8 import subprocess def subprocess_pipe(cmd, inbuff): p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) return p.communicate(inbuff) def genrsa(nbits, private_key_file, public_key_file, passphrase=None): if( passphrase == None ): pin = '' pout = '' else: pin = ' -passin pass:%s ' % passphrase pout = ' -des3 -passout pass:%s ' % passphrase cmd = 'openssl genrsa %s | openssl rsa -out %s %s' % ( str(nbits), private_key_file, pout) subprocess.call(cmd, shell=True) cmd = 'openssl rsa %s -in %s -pubout -out %s' % ( pin, private_key_file, public_key_file ) subprocess.call(cmd, shell=True) def encrypto( public_key_file, buff ): cmd = 'openssl rsautl -encrypt -pubin -inkey %s' % public_key_file response = subprocess_pipe( cmd, buff ) return response def decrypto( private_key_file, buff, passphrase=None ): if( passphrase == None ): pin = '' else: pin = ' -passin pass:%s ' % passphrase cmd = 'openssl rsautl -decrypt %s -inkey %s' % ( pin, private_key_file ) response = subprocess_pipe( cmd, buff ) return response def rand( nbytes ): cmd = 'openssl rand ' + str(nbytes) return subprocess.check_output( cmd, shell=True ) if(__name__=='__main__'): import base64 import sys nbits = 2048 private_key_file = 'rsa.pri' public_key_file = 'rsa.pub' passphrase = 'Hello_RSA!' text = 'You got money!' genrsa(1024, private_key_file, public_key_file, passphrase ) print text enc, ret = encrypto( public_key_file, text ) if( ret != '' ): print 'encrypto error' sys.exit() print base64.b64encode(enc) dec, ret = decrypto( private_key_file, enc, passphrase ) if( ret != '' ): print 'decrypto error' sys.exit() print dec