Permalink
Browse files

Prioritize nsscrypto when its available over pycrypo.

  • Loading branch information...
1 parent 616be39 commit 4733630c0359636f5ab8e1b2b33470c67b5ba4fc @bbangert committed Aug 7, 2012
Showing with 51 additions and 2 deletions.
  1. +6 −2 beaker/crypto/__init__.py
  2. +45 −0 beaker/crypto/nsscrypto.py
View
8 beaker/crypto/__init__.py
@@ -14,10 +14,14 @@
pass
else:
try:
- from beaker.crypto.pycrypto import getKeyLength, aesEncrypt, aesDecrypt
+ from beaker.crypto.nsscrypto import getKeyLength, aesEncrypt, aesDecrypt
keyLength = getKeyLength()
except ImportError:
- pass
+ try:
+ from beaker.crypto.pycrypto import getKeyLength, aesEncrypt, aesDecrypt
+ keyLength = getKeyLength()
+ except ImportError:
+ pass
if not keyLength:
has_aes = False
View
45 beaker/crypto/nsscrypto.py
@@ -0,0 +1,45 @@
+"""Encryption module that uses nsscrypto"""
+import nss.nss
+
+nss.nss.nss_init_nodb()
+
+# Apparently the rest of beaker doesn't care about the particluar cipher,
+# mode and padding used.
+# NOTE: A constant IV!!! This is only secure if the KEY is never reused!!!
+_mech = nss.nss.CKM_AES_CBC_PAD
+_iv = '\0' * nss.nss.get_iv_length(_mech)
+
+def aesEncrypt(data, key):
+ slot = nss.nss.get_best_slot(_mech)
+
+ key_obj = nss.nss.import_sym_key(slot, _mech, nss.nss.PK11_OriginGenerated,
+ nss.nss.CKA_ENCRYPT, nss.nss.SecItem(key))
+
+ param = nss.nss.param_from_iv(_mech, nss.nss.SecItem(_iv))
+ ctx = nss.nss.create_context_by_sym_key(_mech, nss.nss.CKA_ENCRYPT, key_obj,
+ param)
+ l1 = ctx.cipher_op(data)
+ # Yes, DIGEST. This needs fixing in NSS, but apparently nobody (including
+ # me :( ) cares enough.
+ l2 = ctx.digest_final()
+
+ return l1 + l2
+
+def aesDecrypt(data, key):
+ slot = nss.nss.get_best_slot(_mech)
+
+ key_obj = nss.nss.import_sym_key(slot, _mech, nss.nss.PK11_OriginGenerated,
+ nss.nss.CKA_DECRYPT, nss.nss.SecItem(key))
+
+ param = nss.nss.param_from_iv(_mech, nss.nss.SecItem(_iv))
+ ctx = nss.nss.create_context_by_sym_key(_mech, nss.nss.CKA_DECRYPT, key_obj,
+ param)
+ l1 = ctx.cipher_op(data)
+ # Yes, DIGEST. This needs fixing in NSS, but apparently nobody (including
+ # me :( ) cares enough.
+ l2 = ctx.digest_final()
+
+ return l1 + l2
+
+def getKeyLength():
+ return 32

0 comments on commit 4733630

Please sign in to comment.