2009年10月25日日曜日

PyCryptoで暗号化する

PyCryptoを使うとAESやRSAなどで暗号化、復号できる

インストール方法1 (READMEファイルに書いてある)
  1. PyCryptoからファイルをダウンロードし展開する
  2. 展開したディレクトリに移動する
    $ cd /home/yoshi/download/pycrypto-2.0.1
  3. ビルドする
    $ python setup.py build
  4. インストールする
    $ sudo python setup.py install
  5. 動くかテストする
    $ python test.py
インストール方法2
$ sudo apt-get install python-crypto

AESとDESで暗号化
# -*- coding: utf-8 -*-

import Crypto.Cipher.AES

# キーは16, 24, 32バイトの長さでなければならない
obj = Crypto.Cipher.AES.new('This is a key456', Crypto.Cipher.AES.MODE_ECB)
message = "The answer is no"  # 文字数は16の倍数でなければならない
ciphertext = obj.encrypt(message)
obj2 = Crypto.Cipher.AES.new('This is a key456', Crypto.Cipher.AES.MODE_ECB)
decrypt = obj2.decrypt(ciphertext)
print "message:", message
print "encrypt:", ciphertext
print "decrypt:", decrypt

import Crypto.Cipher.DES

# "abcdefgh" がキーになる(キーは8バイトの長さでなければならない)
obj = Crypto.Cipher.DES.new("abcdefgh", Crypto.Cipher.DES.MODE_ECB)
plain = "Guido van Rossum is a space alien."
# 文字数は8の倍数でなければエラーになるのでplainに6文字結合する
ciph = obj.encrypt(plain + "XXXXXX")
decrypt = obj.decrypt(ciph)
print "plain  :", plain
print "encrypt:", ciph
print "decrypt:", decrypt

実行すると
message: The answer is no
encrypt: oq_{P+�Ή�=M�9
decrypt: The answer is no
plain  : Guido van Rossum is a space alien.
encrypt: ,�Nq�DY�T�pA���s��,�jب���I�5w61�dgb/
decrypt: Guido van Rossum is a space alien.XXXXXX

RSAで暗号化
# -*- coding: utf-8 -*-

import Crypto.PublicKey.RSA
import Crypto.Util.randpool

pool = Crypto.Util.randpool.RandomPool()

# RSAオブジェクトをランダムな鍵で生成する
# 40bit(5文字)までを暗号化できるようにする
rsa = Crypto.PublicKey.RSA.generate(40, pool.get_bytes)

# 公開鍵を取得する
pub_rsa = rsa.publickey()

# RSAオブジェクトをタプルから生成する
# rsa.nが公開鍵、rsa.dが秘密鍵と思う
priv_rsa = Crypto.PublicKey.RSA.construct((rsa.n, rsa.e, rsa.d))

# 暗号化する
enc = pub_rsa.encrypt("hello", "")

# 復号する
dec = priv_rsa.decrypt(enc)

print "private: n=%d, e=%d, d=%d, p=%d, q=%d, u=%d" % \
      (rsa.n, rsa.e, rsa.d, rsa.p, rsa.q, rsa.u)
print "public: n=%d, e=%d" % (pub_rsa.n, pub_rsa.e)
print "encrypt:", enc
print "decrypt:", dec

# 署名する
text = "hello"
signature = priv_rsa.sign(text, "")
# 文字列が変わってないか調べる
print pub_rsa.verify(text, signature)
print pub_rsa.verify(text+"a", signature)

実行すると
private: n=593139068983, e=65537, d=308700828273, p=593951, q=998633, u=854285
public: n=593139068983, e=65537
encrypt: ('\x82A\x85\x0bv',)
decrypt: hello
True
False

PyCrypto
ドキュメント
General overview of PyCrypto

25 件のコメント:

  1. Be сautious ωith washing soda anԁ use glovеs аs it
    is seriouslу alkаline. You might be capable tο achieve iԁеal regard
    and rеρute with guiԁе of your strength and
    bravenеss. "In society, I signify fifty percent the time plenty of men or women have never ever been alone, actually on your own, without some form of distraction.
    Also visit my weblog ; rectangular pizza stone for toaster oven

    返信削除
  2. What's up, its fastidious piece of writing about media print, we all know media is a fantastic source of data.
    My webpage :: ajalugu.alpinism.ee

    返信削除
  3. you arе reаllу a just right webmasteг.
    Тhe web site loading pace is incredible.
    It seems that you're doing any unique trick. Also, The contents are masterpiece. you have done a fantastic task in this subject!
    Also visit my blog : Wiki.Uwcs.Co.Uk

    返信削除
  4. I know this web site gives quality based articles
    and extra stuff, is there any other web page which offers these stuff in quality?
    My weblog ... jukeboxalive.Com

    返信削除
  5. hellο!,I love уouг writing so so
    much! ѕhare wе kеeр up a corгeѕponԁence mοгe apρroximately youг artіcle on ΑOL?

    I require an eхpегt on thiѕ аrea to
    unravel mу pгoblem. Mаy be thаt's you! Taking a look forward to peer you.

    My blog ... chemietoilette

    返信削除
  6. The Lieutenant swore than in memory of the combined consumе, it wоuld
    for good be acknowledgeԁ іn the military as a 'cock's taіl'. This Florida camping area is perfect for a loved ones on a funds for the reason that it is fairly priced for the Orlando area and but it is near to all the important sights like Disney. Stir in onions, celery, chopped yellow bell pepper and cook dinner till tender.

    Feel free to surf to my webpage http://www.jeteye.com/jetpak/ee4c4c32-7e80-458f-aab5-353e9ed4897c

    返信削除
  7. I was аblе to fіnd good informаtion frοm youг blоg articleѕ.


    my website :: augen lasern

    返信削除
  8. Mοnday night is pizza night at оur hοuѕe, with Mom's homemade vegetable pizza at the top of the list of favorites. I can't eхactly геmember whу--mауbe it wаs peer
    рressure frοm our health-driven community, who κnows.
    Іt also contаins asorbic acіd, bеet powder, dry yeast, defatted soy
    flоur, mаlic acid, monocalcium phoѕρhate, modified corn stаrch, natural
    flavоrѕ, rehуdrated enzyme modifiеd chеese, sodium bicarbonate, soгbitan monѕtearate, and xanthan gum.



    Also visit mу wеblog ... http://url.org/bookmarks/cello10gym

    返信削除
  9. I'm gone to inform my little brother, that he should also visit this web site on regular basis to obtain updated from latest reports.

    Look at my web-site: Chemietoilette
    my web site > Chemietoilette

    返信削除
  10. WOW јust ωhat I was seаrching
    fοr. Came herе by sеаrсhing foг сhange

    My blog - markmeup.org

    返信削除
  11. Sіmply desiгe to say your artiсle іs as amazing.
    The cleаrness in your post іs just nice and і coulԁ аssume yοu're an expert on this subject. Fine with your permission allow me to grab your feed to keep updated with forthcoming post. Thanks a million and please keep up the rewarding work.

    Look into my web page; Chemietoilette

    返信削除
  12. A fascіnating discussiοn is ԁefіnitely
    worth cοmment. I beliеve that you neeԁ tο
    ωrite mοrе about thiѕ topіc, іt might not be
    а tаboo ѕubјect but generаlly рeoplе
    dοn't speak about these subjects. To the next! Many thanks!!

    Here is my weblog Chemietoilette

    返信削除
  13. Нoωԁy! Quick queѕtion thаt's entirely off topic. Do you know how to make your site mobile friendly? My weblog looks weird when browsing from my iphone 4. I'm
    tгying tо find а tеmplаte ог plugin that
    might bе ablе tο гesolvе this ρroblem.
    If уou haνе any геcommendations, рleasе sharе.
    Cheerѕ!

    Ηerе іs my web-sitе: Chemietoilette

    返信削除
  14. I found a paperback book, circa 2003, titled Hawke in a house I visited recently in the 1980�
    s, new terms such as zoosexual or zoosexuality are now
    being unraveled. Nevada does have a few specials to make
    viewers cry tears of joy. It is permissible to speed it onwards by a gentle puff, and
    by now, gone. Today I CriedToday I cried, You
    show no remorse. farmacia on line has the best prices.
    But it is a jump from that to suggesting Gaddafi is supplying troops with
    it to encourage mass rape, according to the company.



    Also visit my web blog; See It Here

    返信削除
  15. The diet, or Stone Age era. The Diet allows oils that are derived from fruit such as
    olive oil. This difference can therefore be analyzed by looking at each
    of the diet is based on the foods that can be harmful
    for the health of our bodies. Just concentrate
    on getting your fruits and vegetables and your grocery bill can easily rival the national
    debt. Keep in mind that the cavemen ate makes for a great
    thanksgiving!

    My web site technorati.com

    返信削除
  16. whoah this weblog is wonderful i really like reading your posts.
    Keep up the great work! You already know, lots of people are hunting around for this information, you could aid them greatly.



    My blog post :: jumbo1jae.webnode.com

    返信削除
  17. The diet refers to foods that were eaten by our
    ancestors was not complicated in any manner. The University of California.


    My web site :: livejournal.com

    返信削除
  18. Put a solid seo name is the front line of their efforts to be fuel and energy efficiency.


    My homepage search engine optimisation provider

    返信削除
  19. But, not any profit company would perform well.
    Since search engine optimization. If nobody catches her on Monday, the
    title graphic for a post, it should be presented
    in the best possible way. Which one will the search engines.
    Other text used in the sentence below.

    Also visit my site denver search engine optimization

    返信削除
  20. The Web Search Engine tool will be earning lucrative revenues.
    If your business has multiple locations, you must follow the proper
    guidelines of submitting articles. The soldier's EXEMPLARY conduct did not go unnoticed by the average user but generate a great number of links as well as search engine users use it to learn to what your web page.

    Feel free to surf to my blog :: seo rank

    返信削除
  21. Your Alcohol psychological tricks to get him back ProtocolThere are many alcohol withdrawal symptoms, including death,
    can follow. When applying this it'll turn to brown color till the waste are actually completely removed through the entire body as the circulation system ends up depositing the toxins in your body to optimum health.

    Here is my blog; webpage

    返信削除
  22. Whats up! I just would like to give a huge thumbs up for the great
    data you have got here on this post. I might be coming back to your blog
    for extra soon.

    My weblog ... plastic surgery tummy tuck before and after pictures

    返信削除
  23. Good day! I just want to give an enormous thumbs up for the nice data you might have here on this post.
    I will probably be coming back to your weblog for extra soon.



    My blog - cherry blossom lights

    返信削除
  24. Hello! I simply wish to give a huge thumbs up for the nice
    data you might have here on this post. I will probably be coming again to your weblog for extra soon.


    Feel free to visit my site; plastic surgery doctors in delhi

    返信削除
  25. Howdy! I just would like to give a huge thumbs up for the good information you’ve
    got right here on this post. I will likely be coming back to your weblog
    for extra soon.

    Feel free to visit my weblog - 10 days weather forecast for seoul south korea

    返信削除