prev = None
for x in range(10):
if prev is not None:
print "not last:", prev
prev = x
print "last:", prev
Output:
not last: 0
not last: 1
not last: 2
not last: 3
not last: 4
not last: 5
not last: 6
not last: 7
not last: 8
last: 9
prev = None
for x in range(10):
if prev is not None:
print "not last:", prev
prev = x
print "last:", prev
RFC 2315, section 10.3, note #2:
2. Some content-encryption algorithms assume the
input length is a multiple of k octets, where k > 1, and
let the application define a method for handling inputs
whose lengths are not a multiple of k octets. For such
algorithms, the method shall be to pad the input at the
trailing end with k - (l mod k) octets all having value k -
(l mod k), where l is the length of the input. In other
words, the input is padded at the trailing end with one of
the following strings:
01 -- if l mod k = k-1
02 02 -- if l mod k = k-2
.
.
.
k k ... k k -- if l mod k = 0
The padding can be removed unambiguously since all input is
padded and no padding string is a suffix of another. This
padding method is well-defined if and only if k < 256;
methods for larger k are an open issue for further study.
class PKCS7Encoder():
"""
Technique for padding a string as defined in RFC 2315, section 10.3,
note #2
"""
class InvalidBlockSizeError(Exception):
"""Raised for invalid block sizes"""
pass
def __init__(self, block_size=16):
if block_size < 2 or block_size > 255:
raise PKCS7Encoder.InvalidBlockSizeError('The block size must be ' \
'between 2 and 255, inclusive')
self.block_size = block_size
def encode(self, text):
text_length = len(text)
amount_to_pad = self.block_size - (text_length % self.block_size)
if amount_to_pad == 0:
amount_to_pad = self.block_size
pad = chr(amount_to_pad)
return text + pad * amount_to_pad
def decode(self, text):
pad = ord(text[-1])
return text[:-pad]
>>> # basic use
>>> encoder = PKCS7Encoder()
>>> padded_value = encoder.encode('hi')
>>> padded_value
'hi\x0e\x0e\x0e\x0e\x0e\x0e\x0e\x0e\x0e\x0e\x0e\x0e\x0e\x0e'
>>> len(padded_value)
16
>>> encoder.decode(padded_value)
'hi'
>>> # empty string
>>> padded_value = encoder.encode('')
>>> padded_value
'\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10'
>>> len(padded_value)
16
>>> encoder.decode(padded_value)
''
>>> # string that is longer than a single block
>>> padded_value = encoder.encode('this string is long enough to span blocks')
>>> padded_value
'this string is long enough to span blocks\x07\x07\x07\x07\x07\x07\x07'
>>> len(padded_value)
48
>>> len(padded_value) % 16
0
>>> encoder.decode(padded_value)
'this string is long enough to span blocks'
>>> # using the max block size
>>> encoder = PKCS7Encoder(255)
>>> padded_value = encoder.encode('hi')
>>> len(padded_value)
255
>>> encoder.decode(padded_value)
'hi'
class Question(models.Model):
question = models.CharField(max_length=250, editable=False)
def __unicode__(self):
return unicode(self.question)
class Answer(models.Model):
asset = models.ForeignKey(Asset)
question = models.ForeignKey(Question)
answer = models.BooleanField(default=False)
def __unicode__(self):
return unicode('%s: %s' % (self.question, self.answer))
class AnswerForm(ModelForm):
to_save = False
question = forms.ModelChoiceField(queryset=Question.objects.all(),
widget=forms.HiddenInput())
class Meta:
model = Answer
exclude = ('asset')
def set_question(self, question):
self.fields['answer'].label = question
def get_answer_formset(asset, data):
questions = StageQuestion.objects.all()
extra = 0
if not asset:
# This is a brand new set, so we should pre-populate the questions.
extra = len(questions)
AnswerFormSet = inlineformset_factory(
Asset,
Answer,
form=AnswerForm,
can_delete=False,
extra=extra,
)
formset = AnswerFormSet(
data,
prefix='que',
instance=asset,
)
for form, question in zip(formset.forms, questions):
form.set_question(question.question)
form.initial = {'question': question.id}
return formset
import pexpect
def get_fingerprint_pexpect(key_file_name):
command = 'ssh-keygen -lf %s' % (key_file_name,)
child = pexpect.spawn(command)
result_id = child.expect([
pexpect.TIMEOUT,
'No such file',
'fail',
'error',
'not a public key',
'[0-9a-f:]+',])
if result_id == 0:
raise Exception, 'Timeout occurred.'
if result_id == 1:
raise Exception, 'File "%s" does not exist.' % (key_file_name,)
if result_id in (2, 3, 4):
raise ValueError, 'Improperly formatted key.'
fingerprint = child.match.group()
return fingerprint
import re
import subprocess
NO_SUCH_FILE_ERROR = re.compile('No such file')
KEY_FORMAT_ERROR = re.compile('(fail|error|not a public key)')
FINGERPRINT = re.compile('[0-9a-f]{2}:[0-9a-f:]+')
def get_fingerprint_subprocess(key_file_name):
command = ['ssh-keygen', '-lf', key_file_name,]
result = subprocess.Popen(command,
stdout = subprocess.PIPE,
stderr = subprocess.STDOUT,
stdin = subprocess.PIPE).communicate()[0]no_such_file_error = NO_SUCH_FILE_ERROR.search(result)
if no_such_file_error:
raise Exception, 'File "%s" does not exist.' % (key_file_name,)
key_format_error = KEY_FORMAT_ERROR.search(result)
if key_format_error:
raise ValueError, 'Improperly formatted key.'
fingerprint = FINGERPRINT.search(result)
if fingerprint:
return fingerprint.group()
raise Exception, 'Error generating key fingerprint.'
[0-9a-f]{2}:[0-9a-f:]+
Then later we say "child.match.group()" to get the actual content that was matched.