Skip to content

Instantly share code, notes, and snippets.

@fcicq
Created June 25, 2012 13:48
Show Gist options
  • Select an option

  • Save fcicq/2988707 to your computer and use it in GitHub Desktop.

Select an option

Save fcicq/2988707 to your computer and use it in GitHub Desktop.
pkcs#1 padding, see RFC 3447 7.2.1
import random
def random_bytes(size):
return "".join(chr(random.randrange(1, 256)) for i in xrange(size))
def pkcs1_pad(text, size = 128):
l = size - len(text) - 3
if l >= 8: # see RFC3447 7.2.1
padding = random_bytes(l)
return '\x00\x02' + padding + '\x00' + text
else:
return text
# from http://kfalck.net/2011/03/07/decoding-pkcs1-padding-in-python
def pkcs1_unpad(text):
if text and (text[0] == '\x02' or text[0:2] == '\x00\x02'):
# Find end of padding marked by nul
pos = text.find('\x00',1)
if pos > 0:
return text[pos+1:]
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment