code
stringlengths 114
1.05M
| path
stringlengths 3
312
| quality_prob
float64 0.5
0.99
| learning_prob
float64 0.2
1
| filename
stringlengths 3
168
| kind
stringclasses 1
value |
---|---|---|---|---|---|
from math import log, sqrt, pi, ceil, log1p
from samson.math.general import random_int, lcm
from tqdm import tqdm
import operator as _operator
import json
import difflib as _difflib
import os
RC4_BIAS_MAP = [163, 0, 131, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 240, 17, 18, 0, 20, 21, 22, 0, 24, 25, 26, 0, 28, 29, 0, 31, 224, 33, 0, 0, 0, 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 208, 0, 0, 0]
def longest_subsequence(seq_a: list, seq_b: list) -> list:
"""
Finds the longest matching subsequence between two enumerable objects.
Parameters:
seq_a (list): First enumerable.
seq_b (list): Second enumerable.
Returns:
list: Longest subsequence.
"""
seqMatch = _difflib.SequenceMatcher(None, seq_a, seq_b)
match = seqMatch.find_longest_match(0, len(seq_a), 0, len(seq_b))
return seq_a[match.a: match.a + match.size]
def hamming_distance(bytes1: bytes, bytes2: bytes) -> int:
"""
Calculates the Hamming distance between two byte-strings.
Parameters:
bytes1 (bytes): First byte-string.
bytes2 (bytes): Second byte-string.
Returns:
int: Hamming distance.
"""
from samson.encoding.general import bytes_to_bitstring
assert len(bytes1) == len(bytes2)
bitstring1 = bytes_to_bitstring(bytes1)
bitstring2 = bytes_to_bitstring(bytes2)
distance = 0
for bit1, bit2 in zip(bitstring1, bitstring2):
if bit1 != bit2: distance += 1
return distance
def str_hamming_distance(s1: str, s2: str) -> int:
"""
Computes the Hamming distance between two equal-length strings
Parameters:
s1 (str): First string.
s2 (str): Second string.
Returns:
int: Hamming Distance.
"""
if len(s1) != len(s2):
raise ValueError("Strings MUST be equal length")
return sum(letter1 != letter2 for letter1, letter2 in zip(s1, s2))
def levenshtein_distance(seq_a: list, seq_b: list) -> int:
"""
Calculates the Levenshtein Distance between two enumerable objects.
Parameters:
seq_a (list): First enumerable.
seq_b (list): Second enumerable.
Returns:
int: Levenshtein Distance.
"""
if len(seq_a) < len(seq_b):
return levenshtein_distance(seq_b, seq_a)
if len(seq_b) == 0:
return len(seq_a)
previous_row = range(len(seq_b) + 1)
for i, c1 in enumerate(seq_a):
current_row = [i + 1]
for j, c2 in enumerate(seq_b):
insertions = previous_row[j + 1] + 1 # j+1 instead of j since previous_row and current_row are one character longer
deletions = current_row[j] + 1 # than seq_b
substitutions = previous_row[j] + (c1 != c2)
current_row.append(min(insertions, deletions, substitutions))
previous_row = current_row
return previous_row[-1]
def count_items(items: list) -> dict:
"""
Counts the items in an enumerable object.
Parameters:
items (list): Enumerable of items.
Returns:
dict: Dictionary of {item, count}.
"""
item_ctr = {curr_item: 0 for curr_item in items}
for curr_item in items:
item_ctr[curr_item] += 1
return item_ctr
def chisquare(observed_dict: dict, expected_freq_dict: dict, length_override: int=0) -> float:
"""
Calculates the Chi-squared score of an `observed_dict` against the `expected_freq_dict`.
Parameters:
observed_dict (dict): Dictionary of observed items and their counts.
expected_freq_dict (dict): Dictionary of expected items and their counts.
Returns:
float: Chi-squared score.
"""
observed_items = observed_dict.items()
observed_len = length_override or sum([v for _k, v in observed_items])
total = 0
for key, freq_value in expected_freq_dict.items():
if key in observed_dict:
obs_val = observed_dict[key]
else:
obs_val = 0
expected_number = observed_len * freq_value
total += (expected_number - obs_val) ** 2 / expected_number
for key, obs_value in observed_dict.items():
if key not in expected_freq_dict:
obs_val = obs_value
else:
obs_val = 0
total += obs_val ** 2
return total
def find_repeating_key_size(ciphertext: bytes, key_range: list) -> list:
"""
Attempts to find the key size of a repeating XOR cipher.
Parameters:
ciphertext (bytes): Ciphertext to analyze.
key_range (list): List of key sizes to test.
Returns:
list: Sorted list of most likely key sizes.
"""
key_distances = {}
for size in key_range:
size_sum = 0
num_blocks = (len(ciphertext) // size)
for block in range(num_blocks - 1):
size_sum += hamming_distance(ciphertext[block * size: (block + 1) * size], ciphertext[(block + 1) * size: (block + 2) * size]) / size
key_distances[size] = size_sum / num_blocks
return sorted(key_distances.items(), key=_operator.itemgetter(1))
def birthday_attack_analysis(bits: int, probability: float) -> float:
"""
Determines the average number of attempts before a collision occurs against `bits` with `probability`.
Parameters:
bits (int): Number of bits in the keyspace.
probability (float): Target probability.
Returns:
float: Average number of attempts before collision.
References:
https://en.wikipedia.org/wiki/Birthday_attack#Mathematics
"""
return sqrt(2 * 2**bits * -log1p(-probability))
EULER_MASCHERONI_CONSTANT = 0.5772156649015329
def coupon_collector_analysis(n: int) -> (float, float):
"""
Determines the average number of attempts to collect all `n` items from a pseudorandom function.
Parameters:
n (int): Number of items.
Returns:
(float, float): Tuple formatted as (average_number, standard_deviation).
References:
https://brilliant.org/wiki/coupon-collector-problem/
"""
average_number = n * (log(n) + EULER_MASCHERONI_CONSTANT) + 0.5
standard_deviation = sqrt((pi**2 * n**2) / 6 - n * (log(n) + EULER_MASCHERONI_CONSTANT) - 0.5)
return (average_number, standard_deviation)
def ncr(n: int, r: int) -> int:
"""
`n` choose `r`.
Parameters:
n (int): Number to choose from.
r (int): Number of those to choose.
Returns:
int: Number of elements in nCr.
"""
r = min(r, n-r)
numer = 1
for i in range(n, n-r, -1):
numer *= i
denom = 1
for i in range(1, r+1):
denom *= i
return numer // denom
def num_expected_collisions(bits: int, num_inputs: int) -> float:
"""
Calculates the number of expected collisions with `num_inputs` over `bits` keyspace.
Parameters:
bits (int): Number of bits in the keyspace.
num_inputs (int): Hypothetical number of inputs.
Returns:
float: Number of expected collisions.
"""
return 2**(-bits)*ncr(num_inputs, 2)
def probability_of_x_occurences(n: int, x: int, p: float) -> float:
"""
Calculates the probability of an event with probability `p` occuring exactly `x` times in `n` trials.
Parameters:
n (int): Number of trials.
x (int): Number of times for event to occur.
p (float): Probability event will occur.
Returns:
float: Probability of total event.
References:
https://math.stackexchange.com/questions/2348827/probability-of-an-event-occurring-x-number-of-times-in-a-sequence-of-events
"""
return ncr(n, x) * p**x * (1-p)**(n-x)
def probability_of_at_least_x_occurences(n: int, x: int, p: float) -> float:
"""
Calculates the probability of an event with probability `p` occuring at least `x` times in `n` trials.
Parameters:
n (int): Number of trials.
x (int): Number of times for event to occur.
p (float): Probability event will occur.
Returns:
float: Probability of total event.
"""
return sum(probability_of_x_occurences(n, k, p) for k in range(x, n))
def number_of_attempts_to_reach_probability(p: float, desired_prob: float) -> int:
"""
Calculates the minimum number of attempts of an event with probability `p` to occur with `desired_prob` probability.
Parameters:
p (float): Probability event will occur.
desired_prob (float): Probability to reach.
Returns:
int: Number of attempts.
Examples:
>>> from samson.analysis.general import number_of_attempts_to_reach_probability, simulate_event
>>> d = number_of_attempts_to_reach_probability(1/100, 0.5)
>>> # Note we're checking how many times it happens at least once, not the number of times it happens
>>> result = sum([simulate_event(1/100, d) > 0 for _ in range(10000)]) / 10000
>>> d, abs(result - 0.5) < 0.05
(69, True)
"""
return ceil(log1p(-desired_prob)/log1p(-p))
def __float_to_discrete_probability(p: float):
from samson.math.algebra.rings.integer_ring import ZZ
QQ = ZZ.fraction_field()
p_frac = QQ(p)
space = int(lcm(p_frac.numerator, p_frac.denominator))
cutoff = int(p_frac*space)
return space, cutoff
def simulate_event(p: float, attempts: int) -> int:
"""
Simulates an event with probability `p` for `attempts` attempts and returns the number of times it occured.
Parameters:
p (float): Probability event will occur.
attempts (int): Number of attempts.
Returns:
int: Number of occurences.
"""
space, cutoff = __float_to_discrete_probability(p)
total = 0
for _ in range(attempts):
total += random_int(space) < cutoff
return total
def simulate_until_event(p: float, runs: int, visual: bool=False) -> float:
"""
Simulates an event with probability `p` for `runs` runs and returns the average number of attempts until it occured.
Parameters:
p (float): Probability event will occur.
runs (int): Number of runs.
visual (bool): Whether or not to display a progress bar.
Returns:
float: Average number of attempts.
"""
space, cutoff = __float_to_discrete_probability(p)
total = 0
r_iter = range(runs)
if visual:
r_iter = tqdm(r_iter)
for _ in r_iter:
curr = 0
while True:
curr += 1
if random_int(space) < cutoff:
break
total += curr
return total / runs
def generate_rc4_bias_map(ciphertexts):
bias_map = [{} for i in range(256)]
for c in ciphertexts:
for i, byte in enumerate(c):
if byte in bias_map[i]:
bias_map[i][byte] = bias_map[i][byte] + 1
else:
bias_map[i][byte] = 1
for i,_ in enumerate(bias_map):
bias_map[i] = sorted(bias_map[i].items(), key=lambda kv: kv[1], reverse=True)
return bias_map
def generate_random_rc4_bias_map(data=b'\x00' * 51, key_size=128, sample_size=2**20):
from samson.stream_ciphers.rc4 import RC4
ciphertexts = []
for _ in range(sample_size):
key = os.urandom(key_size // 8)
cipher = RC4(key)
ciphertexts.append(cipher.generate(len(data)) ^ data)
return generate_rc4_bias_map(ciphertexts)
def incremental_rc4_bias_map_gen(filepath, start_idx=0, data=b'\x00' * 51, key_size=128, sample_size=2**30, chunk_size=2**24):
if sample_size % chunk_size > 0:
iteration_mod = 1
else:
iteration_mod = 0
iterations = sample_size // chunk_size + iteration_mod
for i in range(start_idx, iterations):
if i == iterations - 1 and iteration_mod == 1:
mod_sample_size = sample_size % chunk_size
else:
mod_sample_size = chunk_size
bias_map = generate_random_rc4_bias_map(data, key_size, mod_sample_size)
with open(filepath + ".{}".format(i), "w+") as f:
f.write(json.dumps(bias_map))
del bias_map
def merge_rc4_bias_map_files(base_path, num):
bias_maps = []
for i in range(num):
with open("{}.{}".format(base_path, i)) as f:
content = f.read()
bias_maps.append(json.loads(content))
return merge_rc4_bias_maps(bias_maps)
def merge_rc4_bias_maps(bias_maps):
merged_map = [{} for i in range(256)]
for bias_map in bias_maps:
for i,_ in enumerate(bias_map):
for k,v in bias_map[i]:
if k in merged_map[i]:
merged_map[i][k] += v
else:
merged_map[i][k] = v
for i,_ in enumerate(merged_map):
merged_map[i] = sorted(merged_map[i].items(), key=lambda kv: kv[1], reverse=True)
return merged_map
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/analysis/general.py
| 0.838515 | 0.480844 |
general.py
|
pypi
|
from samson.block_ciphers.rijndael import Rijndael
from samson.block_ciphers.des import DES
from samson.block_ciphers.tdes import TDES
from samson.block_ciphers.modes.cbc import CBC
from samson.hashes.md5 import MD5
from samson.utilities.manipulation import get_blocks
from samson.utilities.bytes import Bytes
import re
import base64
import math
from enum import Enum
class RFC1423Algorithms(Enum):
DES_CBC = (DES, 8)
DES_EDE3_CBC = (TDES, 24)
AES_128_CBC = (Rijndael, 16)
AES_192_CBC = (Rijndael, 24)
AES_256_CBC = (Rijndael, 32)
def _get_alg_params(algo: str):
if type(algo) is RFC1423Algorithms:
return algo.value
else:
return RFC1423Algorithms.__members__[algo.replace('-', '_')].value
def _get_alg_name(algo: str):
if type(algo) is RFC1423Algorithms:
name = algo.name
else:
name = RFC1423Algorithms.__members__[algo.replace('-', '_')].name
return name.replace('_', '-')
def derive_pem_key(passphrase: bytes, salt: bytes, key_size: int) -> Bytes:
"""
Derives a valid PEM encryption key by mimicking EVP_BytesToKey in OpenSSL.
Parameters:
passphrase (bytes): Passphrase.
salt (bytes): Salt.
key_size (int): Desired key size.
Returns:
Bytes: Derived key.
"""
md5 = MD5()
key = Bytes(b'')
for _ in range(math.ceil(key_size / 16)):
key += md5.hash(key + passphrase + salt)
return key[:key_size]
def create_pem_cbc_obj(passphrase: bytes, algo: str, iv: bytes=None) -> CBC:
"""
Creates a valid CBC cryptor for PEM.
Parameters:
passphrase (bytes): Passphrase to key CBC.
algo (str): RFC1423 encryption algorithm (e.g. 'DES-EDE3-CBC').
iv (bytes): (Optional) IV to use for CBC encryption.
Returns:
CBC: Valid CBC cryptor.
"""
try:
cipher, key_size = _get_alg_params(algo)
except KeyError:
raise ValueError(f'Unsupported cipher "{algo}"')
if not iv:
iv = Bytes.random(16)
key = derive_pem_key(passphrase, iv[:8], key_size)
cipher_obj = cipher(key=key)
cbc = CBC(cipher_obj, iv[:cipher_obj.block_size])
return cbc
PRE_ENCAPSULATION_BOUNDARY_RE = re.compile(rb'\s*----(-| )BEGIN (.*)(-| )----')
POST_ENCAPSULATION_BOUNDARY_RE = re.compile(rb'----(-| )END (.*)(-| )----\s*')
HEADER_RE = re.compile(rb'[A-Za-z\-]+: .*')
# https://golang.org/src/crypto/x509/pem_decrypt.go
# https://golang.org/src/crypto/x509/pem_decrypt_test.go
def pem_decode(pem_bytes: bytes, passphrase: bytes=None) -> bytes:
"""
Decodes PEM bytes into raw bytes.
Parameters:
pem_bytes (bytes): PEM-encoded bytes.
passphrase (bytes): Passphrase to decrypt DER-bytes (if applicable).
Returns:
bytes: Decoded bytes.
"""
pem_bytes = pem_bytes.strip()
if not PRE_ENCAPSULATION_BOUNDARY_RE.match(pem_bytes):
raise ValueError('`pem_bytes` must have a valid pre-encapsulation boundary')
if not POST_ENCAPSULATION_BOUNDARY_RE.search(pem_bytes):
raise ValueError('`pem_bytes` must have a valid post-encapsulation boundary')
boundaries_removed = pem_bytes.split(b'\n')[1:-1]
if boundaries_removed[0] == b'Proc-Type: 4,ENCRYPTED':
if not passphrase:
raise ValueError('Encryption header found but passphrase not specified.')
enc_spec_header = boundaries_removed[1]
assert enc_spec_header.startswith(b'DEK-Info: ')
algo, iv = enc_spec_header[10:].split(b',')
iv = Bytes(iv).unhex()
cbc = create_pem_cbc_obj(passphrase, algo.decode(), iv)
headers_removed = base64.b64decode(b''.join(boundaries_removed[2:]).replace(b' ', b''))
headers_removed = cbc.decrypt(headers_removed)
else:
while HEADER_RE.search(boundaries_removed[0]):
del boundaries_removed[0]
headers_removed = base64.b64decode(b''.join(boundaries_removed).replace(b' ', b''))
return headers_removed
def pem_encode(der_bytes: bytes, marker: str, width: int=70, encryption: str=None, passphrase: bytes=None, iv: bytes=None, use_rfc_4716: bool=False) -> bytes:
"""
PEM-encodes DER-encoded bytes.
Parameters:
der_bytes (bytes): DER-encoded bytes.
marker (str): Header and footer marker (e.g. 'RSA PRIVATE KEY').
width (int): Maximum line width before newline.
encryption (str): (Optional) RFC1423 encryption algorithm (e.g. 'DES-EDE3-CBC').
passphrase (bytes): (Optional) Passphrase to encrypt DER-bytes (if applicable).
iv (bytes): (Optional) IV to use for CBC encryption.
use_rfc_4716 (bool): Use RFC4716 (SSH2) formatting rather than RFC1421 (PEM).
Returns:
bytes: PEM-encoded bytes.
"""
additional_headers = ''
if encryption:
if not passphrase:
raise ValueError('Encryption requested found but passphrase not specified.')
cbc = create_pem_cbc_obj(passphrase, encryption, iv)
der_bytes = cbc.encrypt(der_bytes)
additional_headers = f'Proc-Type: 4,ENCRYPTED\nDEK-Info: {_get_alg_name(encryption)},{cbc.iv.hex().upper().decode()}\n\n'
data = b'\n'.join(get_blocks(base64.b64encode(der_bytes), block_size=width, allow_partials=True))
if use_rfc_4716:
begin_delim = '---- '
end_delim = ' ----'
else:
begin_delim = '-----'
end_delim = '-----'
return f"{begin_delim}BEGIN {marker}{end_delim}\n{additional_headers}".encode('utf-8') + data + f"\n{begin_delim}END {marker}{end_delim}".encode('utf-8')
from samson.core.base_object import BaseObject
class PEMEncodable(BaseObject):
DOC_PARAMS = """ buffer (bytes): Buffer to encode.
encode_pem (bool): Whether or not to PEM-encode as well.
marker (str): Marker to use in PEM formatting (if applicable).
encryption (str): (Optional) RFC1423 encryption algorithm (e.g. 'DES-EDE3-CBC').
passphrase (bytes): (Optional) Passphrase to encrypt DER-bytes (if applicable).
iv (bytes): (Optional) IV to use for CBC encryption.
"""
def __init__(self, key, **kwargs):
self.key = key
@classmethod
def transport_encode(cls, buffer: bytes, encode_pem: bool=True, marker: str=None, encryption: str=None, passphrase: bytes=None, iv: bytes=None, **kwargs):
"""
Encodes the PKI.
Parameters:
buffer (bytes): Buffer to encode.
encode_pem (bool): Whether or not to PEM-encode as well.
marker (str): Marker to use in PEM formatting (if applicable).
encryption (str): (Optional) RFC1423 encryption algorithm (e.g. 'DES-EDE3-CBC').
passphrase (bytes): (Optional) Passphrase to encrypt DER-bytes (if applicable).
iv (bytes): (Optional) IV to use for CBC encryption.
Returns:
bytes: Encoded PKI.
"""
if (encode_pem is None and cls.DEFAULT_PEM) or encode_pem:
buffer = pem_encode(buffer, marker or cls.DEFAULT_MARKER, encryption=encryption, passphrase=passphrase, iv=iv, use_rfc_4716=cls.USE_RFC_4716)
return Bytes.wrap(buffer)
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/encoding/pem.py
| 0.629547 | 0.221877 |
pem.py
|
pypi
|
from samson.utilities.manipulation import get_blocks
from pyasn1.codec.der import encoder, decoder
from pyasn1.type.univ import Sequence as _Sequence, Integer as _Integer, SequenceOf as _SequenceOf
from samson.classical.affine import AffineCipher
from samson.analyzers.analyzer import Analyzer
import urllib.parse
import codecs
import re
import base64
import string
import math
# https://github.com/fwenzel/python-bcrypt
_B64_CHARS = ''.join((string.ascii_uppercase, string.ascii_lowercase, string.digits, '+/')).encode('utf-8')
_B64_CHARS_BCRYPT = ''.join(('./', string.ascii_uppercase, string.ascii_lowercase, string.digits)).encode('utf-8')
_B64_CHARS_URL = ''.join((string.ascii_uppercase, string.ascii_lowercase, string.digits, '-_')).encode('utf-8')
_B64_TO_BCRYPT_TRANSLATION = bytes.maketrans(_B64_CHARS, _B64_CHARS_BCRYPT)
_BCRYPT_TO_B64_TRANSLATION = bytes.maketrans(_B64_CHARS_BCRYPT, _B64_CHARS)
_B64_TO_URL_TRANSLATION = bytes.maketrans(_B64_CHARS, _B64_CHARS_URL)
_URL_TO_B64_TRANSLATION = bytes.maketrans(_B64_CHARS_URL, _B64_CHARS)
def bcrypt_b64_encode(bytestring: bytes) -> bytes:
"""
Encodes a bytestring with bcrypt's version of base64.
Parameters:
bytestring (bytes): Bytes to encode.
Returns:
bytes: bcrypt-base64 encoded bytestring.
"""
return base64.b64encode(bytestring).translate(_B64_TO_BCRYPT_TRANSLATION, b'=')
def bcrypt_b64_decode(bytestring: bytes) -> bytes:
"""
Decodes a bytestring with bcrypt's version of base64.
Parameters:
bytestring (bytes): Bytes to decode.
Returns:
bytes: bcrypt-base64 decoded bytestring.
"""
# Handle missing padding
bytestring = bytestring.translate(_BCRYPT_TO_B64_TRANSLATION) + (b'=' * (4 - len(bytestring) % 4))
return base64.b64decode(bytestring)
def url_b64_encode(bytestring: bytes) -> bytes:
"""
Encodes a bytestring with URL-safe version of base64.
Parameters:
bytestring (bytes): Bytes to encode.
Returns:
bytes: url-base64 encoded bytestring.
"""
return base64.b64encode(bytestring).translate(_B64_TO_URL_TRANSLATION, b'=')
def url_b64_decode(bytestring: bytes) -> bytes:
"""
Decodes a bytestring with a URL-safe version of base64.
Parameters:
bytestring (bytes): Bytes to decode.
Returns:
bytes: url-base64 decoded bytestring.
"""
# Handle missing padding
bytestring = bytestring.translate(_URL_TO_B64_TRANSLATION) + (b'=' * (4 - len(bytestring) % 4))
return base64.b64decode(bytestring)
# https://en.wikipedia.org/wiki/Non-adjacent_form
def to_NAF(input_arg: bytes) -> list:
"""
Converts bytes/bytearray or int to Non-adjacent form (NAF).
Parameters:
input_arg (bytes): Raw bytes/integer.
Returns:
list: Sequence in NAF.
"""
if type(input_arg) is int:
E = input_arg
else:
E = int.from_bytes(input_arg, 'big')
z = []
i = 0
while E > 0:
if E % 2 == 1:
z.append(int(2 - (E % 4)))
E -= z[-1]
else:
z.append(0)
E //= 2
i += 1
return z[::-1]
def from_NAF(naf: list) -> int:
"""
Converts a NAF sequence into an integer.
Parameters:
naf (list): NAF sequence.
Returns:
int: Integer representation.
"""
total = 0
reversed_naf = naf[::-1]
for i in range(len(naf)):
total += 2 ** i * reversed_naf[i]
return total
def int_to_bytes(n: int, byteorder: str='big') -> bytes:
"""
Converts an int `n` to bytes.
Parameters:
n (int): Integer.
byteorder (str): Desired byte order ('big' or 'little').
Returns:
bytes: Bytes representation of `n`.
"""
return n.to_bytes(max((n.bit_length() + 7) // 8, 1), byteorder)
def bytes_to_bitstring(input_bytes: bytes, fill: int=8) -> str:
"""
Converts bytes to a bitstring.
Parameters:
input_bytes (bytes): Bytes to convert.
fill (int): Length of the output bitstring. Pads with zeroes.
Returns:
bytes: Bytes representation of `n`.
"""
return ''.join(format(x, 'b').zfill(fill) for x in input_bytes)
# https://stackoverflow.com/questions/32675679/convert-binary-string-to-bytearray-in-python-3
def bitstring_to_bytes(bitstring: str, byteorder: str='big') -> bytes:
"""
Converts a bitstring to bytes.
Parameters:
bitstring (str): Bitstring to convert.
byteorder (str): Desired byte order ('big' or 'little').
Returns:
bytes: Bytes representation.
"""
return int(bitstring, 2).to_bytes(len(bitstring) // 8, byteorder=byteorder)
def export_der(items: list, item_types: list=None) -> bytes:
"""
Converts items (in order) to DER-encoded bytes.
Parameters:
items (list): Items to be encoded.
Returns:
bytes: DER-encoded sequence bytes.
"""
seq = _Sequence()
if not item_types:
item_types = [_Integer] * len(items)
seq_len = 0
for val, item_type in zip(items, item_types):
if item_type == _SequenceOf:
item = item_type()
item.extend(val)
else:
item = item_type(val)
seq.setComponentByPosition(seq_len, item)
seq_len += 1
return encoder.encode(seq)
def bytes_to_der_sequence(buffer: bytes, passphrase: bytes=None) -> _Sequence:
"""
Attempts to PEM-decode `buffer` then decodes the result to a DER sequence.
Parameters:
buffer (bytes): The bytes to DER-decode.
passphrase (bytes): Passphrase to decrypt DER-bytes (if applicable).
Returns:
Sequence: DER sequence.
"""
from samson.encoding.pem import pem_decode
try:
buffer = pem_decode(buffer, passphrase)
except ValueError as e:
if 'passphrase not specified' in str(e):
raise e
seq = decoder.decode(buffer)
items = seq[0]
return items
def oid_tuple_to_bytes(oid_tuple: tuple) -> bytes:
"""
BER-encodes an OID tuple.
Parameters:
oid_tuple (tuple): OID tuple to encode.
Returns:
bytes: BER-encoded OID.
"""
oid_bytes = bytes([oid_tuple[0] * 40 + oid_tuple[1]])
for next_int in oid_tuple[2:]:
if next_int < 256:
oid_bytes += bytes([next_int])
else:
as_bin = bin(next_int)[2:]
as_bin = as_bin.zfill(math.ceil(len(as_bin) / 7) * 7)
bin_blocks = get_blocks(as_bin, 7)
new_bin_blocks = ['1' + block for block in bin_blocks[:-1]]
new_bin_blocks.append('0' + bin_blocks[-1])
oid_bytes += bytes([int(block, 2) for block in new_bin_blocks])
return oid_bytes
from enum import Enum
class PKIEncoding(Enum):
PKCS1 = 0
PKCS8 = 1
X509 = 2
X509_CERT = 3
OpenSSH = 4
SSH2 = 5
JWK = 6
DNS_KEY = 7
X509_CSR = 8
class PKIAutoParser(object):
@staticmethod
def get_encoding(buffer: bytes, passphrase: bytes=None):
from samson.core.encodable_pki import EncodablePKI, ORDER
from samson.encoding.pem import pem_decode
subclasses = [EncodablePKI]
for subclass in subclasses:
subclasses.extend(subclass.__subclasses__())
if buffer.strip().startswith(b'----'):
buffer = pem_decode(buffer, passphrase)
for encoding in ORDER:
for subclass in subclasses:
for encoding_type in [subclass.PRIV_ENCODINGS, subclass.PUB_ENCODINGS]:
if encoding in encoding_type:
encoder = encoding_type[encoding]
if encoder.check(buffer, passphrase=passphrase):
return encoder
raise ValueError("Unable to parse provided key.")
@staticmethod
def import_key(buffer: bytes, passphrase: bytes=None):
from samson.encoding.pem import pem_decode
if buffer.strip().startswith(b'----'):
buffer = pem_decode(buffer, passphrase)
return PKIAutoParser.get_encoding(buffer, passphrase=passphrase).decode(buffer, passphrase=passphrase)
@staticmethod
def resolve_x509_signature_alg(name: str):
from samson.core.encodable_pki import EncodablePKI
subclasses = [EncodablePKI]
for subclass in subclasses:
subclasses.extend(subclass.__subclasses__())
for subclass in subclasses:
if hasattr(subclass, 'X509_SIGNING_ALGORITHMS'):
try:
return subclass.X509_SIGNING_ALGORITHMS[name]
except KeyError:
pass
from samson.auxiliary.lazy_loader import LazyLoader
_bytes = LazyLoader('_bytes', globals(), 'samson.utilities.bytes')
class EncodingScheme(Enum):
PLAIN = 0
URL = 1
ROT13 = 2
BASE64 = 3
BASE64_URL = 4
BASE32 = 5
BASE32_HEX = 6
HEX = 7
OCTAL = 8
BINARY = 9
def encode(self, text: bytes):
return _bytes.Bytes.wrap(_ENCODERS[self](text))
def decode(self, text: bytes):
return _bytes.Bytes.wrap(_DECODERS[self](text))
@staticmethod
def get_valid_charsets(text: bytes) -> list:
candidates = []
for encoding, regex in _CHARSETS.items():
char_re = re.compile(regex.encode('utf-8'))
if char_re.fullmatch(text):
candidates.append(encoding)
return candidates
@staticmethod
def get_valid_decodings(text: bytes) -> dict:
candidates = {}
for encoding in EncodingScheme:
try:
decoded = encoding.decode(text)
if encoding.encode(decoded) == text:
candidates[encoding] = decoded
except:
pass
return candidates
@staticmethod
def get_best_decoding(text: bytes, analyzer: Analyzer) -> bytes:
decodings = EncodingScheme.get_valid_decodings(text)
return analyzer.select_highest_scores(decodings.items(), key=lambda item: item[1])[0]
_CHARSETS = {
EncodingScheme.PLAIN: r'.*',
EncodingScheme.HEX: r'(0x)?([a-f0-9]+|[A-F0-9]+)',
# https://tools.ietf.org/html/rfc4648#section-6
EncodingScheme.BASE32: r'[A-Z2-7]+(=|={3}|={4}|={6})?',
EncodingScheme.BASE32_HEX: r'[A-V0-9]+(=|={3}|={4}|={6})?',
EncodingScheme.BASE64: r'[A-Za-z0-9+/]+={0,2}',
EncodingScheme.BASE64_URL: r'[A-Za-z0-9-_]+',
EncodingScheme.ROT13: r'[a-zA-Z]+',
EncodingScheme.URL: r'[A-Za-z0-9-._~]+',
EncodingScheme.BINARY: r'(0b)?[0-1]+',
EncodingScheme.OCTAL: r'(0o)[0-7]+'
}
_rot13_low = AffineCipher(a=1, b=13, alphabet=string.ascii_lowercase)
_rot13_upp = AffineCipher(a=1, b=13, alphabet=string.ascii_uppercase)
_ENCODERS = {
EncodingScheme.PLAIN: lambda text: text,
EncodingScheme.HEX: lambda text: codecs.encode(text, 'hex_codec'),
EncodingScheme.BASE32: base64.b32encode,
EncodingScheme.BASE64: base64.b64encode,
EncodingScheme.BASE64_URL: url_b64_encode,
EncodingScheme.ROT13: lambda text: _rot13_upp.encrypt(_rot13_low.encrypt(text.decode())).encode('utf-8'),
EncodingScheme.URL: lambda text: urllib.parse.quote_from_bytes(text).encode('utf-8'),
EncodingScheme.BINARY: lambda text: bin(text).encode('utf-8'),
EncodingScheme.OCTAL: lambda text: oct(text).encode('utf-8')
}
_DECODERS = {
EncodingScheme.PLAIN: lambda text: text,
EncodingScheme.HEX: lambda text: codecs.decode(text, 'hex_codec'),
EncodingScheme.BASE32: base64.b32decode,
EncodingScheme.BASE64: base64.b64decode,
EncodingScheme.BASE64_URL: url_b64_decode,
EncodingScheme.ROT13: lambda text: _rot13_upp.decrypt(_rot13_low.decrypt(text.decode())).encode('utf-8'),
EncodingScheme.URL: urllib.parse.unquote_to_bytes,
EncodingScheme.BINARY: lambda text: int_to_bytes(int(text, 2)),
EncodingScheme.OCTAL: lambda text: int_to_bytes(int(text, 8))
}
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/encoding/general.py
| 0.802401 | 0.477371 |
general.py
|
pypi
|
from samson.hashes.sha1 import SHA1
from samson.hashes.sha2 import SHA224, SHA256, SHA384, SHA512
from samson.hashes.md5 import MD5
from samson.hashes.md2 import MD2
from pyasn1_modules import rfc2459, rfc5280
from pyasn1.codec.der import encoder
from pyasn1.type.univ import ObjectIdentifier, OctetString
def invert_dict(dic):
return {v:k for k,v in dic.items()}
# https://www.ietf.org/rfc/rfc5698.txt
HASH_OID_LOOKUP = {
MD2: ObjectIdentifier('1.2.840.113549.2.2'),
MD5: ObjectIdentifier('1.2.840.113549.2.5'),
SHA1: ObjectIdentifier('1.3.14.3.2.26'),
SHA224: ObjectIdentifier('2.16.840.1.101.3.4.2.4'),
SHA256: ObjectIdentifier('2.16.840.1.101.3.4.2.1'),
SHA384: ObjectIdentifier('2.16.840.1.101.3.4.2.2'),
SHA512: ObjectIdentifier('2.16.840.1.101.3.4.2.3')
}
INVERSE_HASH_OID_LOOKUP = invert_dict(HASH_OID_LOOKUP)
RDN_TYPE_LOOKUP = {
'CN': rfc2459.CommonName,
'O': rfc2459.OrganizationName,
'C': rfc2459.X520countryName,
'L': rfc2459.UTF8String,
'ST': rfc5280.X520StateOrProvinceName,
'OU': rfc2459.X520OrganizationalUnitName,
'emailAddress': rfc5280.EmailAddress,
'serialNumber': rfc2459.CertificateSerialNumber,
'streetAddress': rfc2459.StreetAddress
# 'businessCategory': pyasn1_modules doesn't have this one
}
INVERSE_RDN_TYPE_LOOKUP = invert_dict(RDN_TYPE_LOOKUP)
RDN_OID_LOOKUP = {
'CN': ObjectIdentifier([2, 5, 4, 3]),
'O': ObjectIdentifier([2, 5, 4, 10]),
'OU': ObjectIdentifier([2, 5, 4, 11]),
'C': ObjectIdentifier([2, 5, 4, 6]),
'L': ObjectIdentifier([2, 5, 4, 7]),
'ST': ObjectIdentifier([2, 5, 4, 8]),
'emailAddress': ObjectIdentifier('1.2.840.113549.1.9.1'),
'serialNumber': ObjectIdentifier([2, 5, 4, 5]),
'streetAddress': ObjectIdentifier([2, 5, 4, 9]),
'businessCategory': ObjectIdentifier([2, 5, 4, 15]),
}
INVERSE_RDN_OID_LOOKUP = invert_dict(RDN_OID_LOOKUP)
# https://tools.ietf.org/html/rfc8017#appendix-A.2.4
SIGNING_ALG_OIDS = {
'md2WithRSAEncryption': '1.2.840.113549.1.1.2',
'md5WithRSAEncryption': '1.2.840.113549.1.1.4',
'sha1WithRSAEncryption': '1.2.840.113549.1.1.5',
'sha224WithRSAEncryption': '1.2.840.113549.1.1.14',
'sha256WithRSAEncryption': '1.2.840.113549.1.1.11',
'sha384WithRSAEncryption': '1.2.840.113549.1.1.12',
'sha512WithRSAEncryption': '1.2.840.113549.1.1.13',
'sha512-224WithRSAEncryption': '1.2.840.113549.1.1.15',
'sha512-256WithRSAEncryption': '1.2.840.113549.1.1.16',
'ecdsa-with-SHA1': '1.2.840.10045.4.1',
'ecdsa-with-SHA224': '1.2.840.10045.4.3.1',
'ecdsa-with-SHA256': '1.2.840.10045.4.3.2',
'ecdsa-with-SHA384': '1.2.840.10045.4.3.3',
'ecdsa-with-SHA512': '1.2.840.10045.4.3.4',
'id-dsa-with-sha1': '1.2.840.10040.4.3',
'id-dsa-with-sha224': '2.16.840.1.101.3.4.3.1',
'id-dsa-with-sha256': '2.16.840.1.101.3.4.3.2'
}
INVERSE_SIGNING_ALG_OIDS = {v:k for k,v in SIGNING_ALG_OIDS.items()}
def parse_rdn(rdn_str: str, byte_encode: bool=False) -> rfc2459.RDNSequence:
rdn_parts = rdn_str.split('=')
rdn_seq = rfc2459.RDNSequence()
# Here we're careful of commas in RDNs
# We also use 'key_idx' to keep track of the position
# of the RDNs
rdn_dict = {}
key = rdn_parts[0]
key_idx = [key]
next_key = key
for part in rdn_parts[1:-1]:
parts = part.split(',')
curr_val, next_key = ','.join(parts[:-1]), parts[-1]
rdn_dict[key] = curr_val
key = next_key
key_idx.append(key)
rdn_dict[next_key] = rdn_parts[-1]
for i, k in enumerate(key_idx[::-1]):
v = rdn_dict[k]
attr = rfc2459.AttributeTypeAndValue()
try:
attr['type'] = RDN_OID_LOOKUP[k]
# If the human-readable lookup fails, assume it's an OID
except KeyError:
attr['type'] = ObjectIdentifier(k)
try:
rdn_payload = RDN_TYPE_LOOKUP[k](v)
# We need this for rfc2459.X520StateOrProvinceName
except TypeError:
rdn_payload = RDN_TYPE_LOOKUP[k]()
rdn_payload.setComponentByPosition(0, v)
if byte_encode:
attr['value'] = OctetString(encoder.encode(rdn_payload))
else:
attr['value'] = rdn_payload
rdn = rfc2459.RelativeDistinguishedName()
rdn.setComponentByPosition(0, attr)
rdn_seq.setComponentByPosition(i, rdn)
return rdn_seq
def rdn_to_str(rdns: rfc2459.RDNSequence) -> str:
from pyasn1.codec.der import decoder
rdn_map = []
for rdn in rdns[::-1]:
oid_tuple = rdn[0]['type'].asTuple()
try:
rtype = INVERSE_RDN_OID_LOOKUP[ObjectIdentifier(oid_tuple)]
# If we fail to convert it to a human readable, just convert to OID form
except KeyError:
rtype = '.'.join([str(i) for i in oid_tuple])
rval = str(decoder.decode(bytes(rdn[0]['value']))[0])
rdn_map.append((rtype, rval))
return ','.join(f'{rtype}={rval}' for rtype, rval in rdn_map)
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/encoding/asn1.py
| 0.511229 | 0.225076 |
asn1.py
|
pypi
|
from samson.encoding.openssh.core.literal import Literal
from samson.encoding.openssh.core.kdf_params import KDFParams
from samson.encoding.openssh.core.openssh_private_header import OpenSSHPrivateHeader
from samson.encoding.pem import pem_encode
from samson.encoding.general import PKIEncoding
from samson.utilities.bytes import Bytes
import base64
from types import FunctionType
def check_decrypt(params: bytes, decryptor: FunctionType) -> (bytes, bytes):
"""
Performs an optional decryption and checks the "check bytes" to ensure the key is valid.
Parameters:
params (bytes): Current encoded parameter buffer.
decryptor (func): Function to decrypt the private key.
Returns:
(bytes, bytes): Formatted as (check bytes, left over bytes).
"""
if decryptor:
params = decryptor(params)
check_bytes, params = Literal('check_bytes', length=8).unpack(params)
check1, check2 = check_bytes.chunk(4)
if check1 != check2:
raise ValueError(f'Private key check bytes incorrect. Is it encrypted? check1: {check1}, check2: {check2}')
return check_bytes, params
def generate_openssh_private_key(public_key: object, private_key: object, encode_pem: bool=True, marker: str=None, encryption: str=None, iv: bytes=None, passphrase: bytes=None) -> bytes:
"""
Internal function. Generates OpenSSH private keys for various PKI.
Parameters:
public_key (object): OpenSSH public key object.
private_key (object): OpenSSH private key object.
encode_pem (bool): Whether or not to PEM encode.
marker (str): PEM markers.
encryption (str): Encryption algorithm to use.
iv (bytes): IV for encryption algorithm.
passphrase (bytes): Passphrase for KDF.
Returns:
bytes: OpenSSH encoded PKI object.
"""
if encryption:
kdf_params = KDFParams('kdf_params', iv or Bytes.random(16), 16)
else:
kdf_params = KDFParams('kdf_params', b'', b'')
if encryption and type(encryption) is str:
encryption = encryption.encode('utf-8')
header = OpenSSHPrivateHeader(
header=OpenSSHPrivateHeader.MAGIC_HEADER,
encryption=encryption or b'none',
kdf=b'bcrypt' if encryption else b'none',
kdf_params=kdf_params,
num_keys=1
)
encryptor, padding_size = None, 8
if passphrase:
encryptor, padding_size = header.generate_encryptor(passphrase)
encoded = header.pack() + public_key.pack(public_key) + private_key.pack(private_key, encryptor, padding_size)
if encode_pem:
encoded = pem_encode(encoded, marker or 'OPENSSH PRIVATE KEY')
return encoded
def generate_openssh_public_key_params(encoding: PKIEncoding, ssh_header: bytes, public_key: object, user: bytes=None) -> (bytes, bool, str, bool):
"""
Internal function. Generates OpenSSH public key parameters for various PKI.
Parameters:
encoding (PKIEncoding): Encoding to use. Currently supports 'OpenSSH' and 'SSH2'.
ssh_header (bytes): PKI-specific SSH header.
public_key (object): OpenSSH public key object.
Returns:
(bytes, bool, str, bool): PKI public key parameters formatted as (encoded, default_pem, default_marker, use_rfc_4716).
"""
if encoding == PKIEncoding.OpenSSH:
if user and type(user) is str:
user = user.encode('utf-8')
encoded = ssh_header + b' ' + base64.b64encode(public_key.pack(public_key)[4:]) + b' ' + (user or b'nohost@localhost')
elif encoding == PKIEncoding.SSH2:
encoded = public_key.pack(public_key)[4:]
else:
raise ValueError(f'Unsupported encoding "{encoding}"')
return encoded
def parse_openssh_key(buffer: bytes, ssh_header: bytes, public_key_cls: object, private_key_cls: object, passphrase: bytes) -> (object, object):
"""
Internal function. Parses various PKI keys.
Parameters:
buffer (bytes): Byte-encoded OpenSSH key.
ssh_header (bytes): PKI-specific SSH header.
public_key_cls (object): OpenSSH public key class.
private_key_cls (object): OpenSSH private key class.
passphrase (bytes): Passphrase for KDF.
Returns:
(object, object): Parsed private and public key objects formatted as (private key, public key).
"""
priv = None
# SSH private key?
if OpenSSHPrivateHeader.MAGIC_HEADER in buffer:
header, left_over = OpenSSHPrivateHeader.unpack(buffer)
pub, left_over = public_key_cls.unpack(left_over)
decryptor = None
if passphrase:
decryptor = header.generate_decryptor(passphrase)
priv, _left_over = private_key_cls.unpack(left_over, decryptor)
user = priv.host
else:
if buffer.split(b' ')[0][:len(ssh_header)] == ssh_header:
_header, body, user = buffer.split(b' ')
body = base64.b64decode(body)
else:
body = buffer
user = None
pub, _ = public_key_cls.unpack(body, already_unpacked=True)
return priv, pub, Bytes(user) if user else user
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/encoding/openssh/general.py
| 0.792665 | 0.229179 |
general.py
|
pypi
|
from samson.encoding.openssh.core.packed_bytes import PackedBytes
from samson.encoding.openssh.core.literal import Literal
from samson.encoding.openssh.general import check_decrypt
from samson.padding.incremental_padding import IncrementalPadding
from samson.utilities.bytes import Bytes
from types import FunctionType
class DSAPrivateKey(object):
"""
OpenSSH encoding for an DSA private key.
"""
def __init__(self, name: str, check_bytes: bytes=None, p: int=None, q: int=None, g: int=None, y: int=None, x: int=None, host: bytes=None):
"""
Parameters:
name (str): Name for bookkeeping purposes.
check_bytes (bytes): Four random bytes repeated for OpenSSH to check if the decryption worked.
p (int): Prime modulus.
q (int): Prime modulus.
g (int): Generator.
y (int): Public key.
x (int): Private key.
host (bytes): Host the key was generated on.
"""
self.name = name
self.check_bytes = check_bytes or Bytes.random(4) * 2
self.p = p
self.q = q
self.g = g
self.y = y
self.x = x
self.host = host
def __repr__(self):
return f"<DSAPrivateKey: name={self.name}, p={self.p}, q={self.q}, g={self.g}, y={self.y}, x={self.x}, host={self.host}>"
def __str__(self):
return self.__repr__()
@staticmethod
def pack(value: bytes, encryptor: FunctionType=None, padding_size: int=8) -> Bytes:
"""
Packs a private key into an OpenSSH-compliant encoding.
Parameters:
value (bytes): Value to encode.
encryptor (func): (Optional) Function to use as the encryptor.
padding_size (int): The block size to pad to. Usually 8 unless you're encrypting.
Returns:
Bytes: Packed bytes.
"""
check_bytes = Literal('check_bytes', length=8).pack(value.check_bytes)
encoded = check_bytes + PackedBytes('dsa-header').pack(b'ssh-dss') + PackedBytes('p').pack(value.p) + PackedBytes('q').pack(value.q) + PackedBytes('g').pack(value.g) + PackedBytes('y').pack(value.y) + PackedBytes('x').pack(value.x) + PackedBytes('host').pack(value.host)
padder = IncrementalPadding(padding_size)
body = padder.pad(encoded)
if encryptor:
body = encryptor(body)
return PackedBytes('private_key').pack(body)
@staticmethod
def unpack(encoded_bytes: bytes, decryptor: FunctionType=None, already_unpacked: bool=False) -> (object, bytes):
"""
Unpacks bytes into an DSAPrivateKey object.
Parameters:
encoded_bytes (bytes): Bytes to be (partially?) decoded.
already_unpacked (bool): Whether or not to do the initial length-decoding.
Returns:
(DSAPrivateKey, bytes): The decoded object and unused bytes.
"""
encoded_bytes = Bytes.wrap(encoded_bytes)
if already_unpacked:
params, encoded_bytes = encoded_bytes, None
else:
params, encoded_bytes = PackedBytes('private_key').unpack(encoded_bytes)
check_bytes, params = check_decrypt(params, decryptor)
_header, params = PackedBytes('dsa-header').unpack(params)
p, params = PackedBytes('p').unpack(params)
q, params = PackedBytes('q').unpack(params)
g, params = PackedBytes('g').unpack(params)
y, params = PackedBytes('y').unpack(params)
x, params = PackedBytes('x').unpack(params)
host, params = PackedBytes('host').unpack(params)
return DSAPrivateKey('private_key', check_bytes=check_bytes, p=p.int(), q=q.int(), g=g.int(), y=y.int(), x=x.int(), host=host), encoded_bytes
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/encoding/openssh/core/dsa_private_key.py
| 0.80213 | 0.210502 |
dsa_private_key.py
|
pypi
|
from samson.encoding.openssh.core.packed_bytes import PackedBytes
from samson.encoding.openssh.core.literal import Literal
from samson.encoding.openssh.general import check_decrypt
from samson.utilities.bytes import Bytes
from samson.padding.incremental_padding import IncrementalPadding
from types import FunctionType
class RSAPrivateKey(object):
"""
OpenSSH encoding for an RSA private key.
"""
def __init__(self, name: str, check_bytes: bytes=None, n: int=None, e: int=None, d: int=None, q_mod_p: int=None, p: int=None, q: int=None, host: bytes=None):
"""
Parameters:
name (str): Name for bookkeeping purposes.
check_bytes (bytes): Four random bytes repeated for OpenSSH to check if the decryption worked.
n (int): RSA modulus.
e (int): RSA public exponent.
q_mod_p (int): RSA q^{-1} mod p.
p (int): RSA secret prime.
q (int): RSA secret prime.
host (bytes): Host the key was generated on.
"""
self.name = name
self.check_bytes = check_bytes or Bytes.random(4) * 2
self.n = n
self.e = e
self.d = d
self.q_mod_p = q_mod_p
self.p = p
self.q = q
self.host = host
def __repr__(self):
return f"<RSAPrivateKey: name={self.name}, n={self.n}, e={self.e}, d={self.d}, q_mod_p={self.q_mod_p}, p={self.p}, q={self.q}, host={self.host}>"
def __str__(self):
return self.__repr__()
@staticmethod
def pack(value: 'RSAPrivateKey', encryptor: FunctionType=None, padding_size: int=8) -> Bytes:
"""
Packs a private key into an OpenSSH-compliant encoding.
Parameters:
value (RSAPrivateKey): Value to encode.
encryptor (func): (Optional) Function to use as the encryptor.
padding_size (int): The block size to pad to. Usually 8 unless you're encrypting.
Returns:
Bytes: Packed bytes.
"""
check_bytes = Literal('check_bytes', length=8).pack(value.check_bytes)
header = PackedBytes('rsa-header').pack(b'ssh-rsa')
n = PackedBytes('n').pack(value.n)
e = PackedBytes('e').pack(value.e)
d = PackedBytes('d').pack(value.d)
q_mod_p = PackedBytes('q_mod_p').pack(value.q_mod_p)
p = PackedBytes('p').pack(value.p)
q = PackedBytes('q').pack(value.q)
host = PackedBytes('host').pack(value.host)
padder = IncrementalPadding(padding_size)
body = padder.pad(check_bytes + header + n + e + d + q_mod_p + p + q + host)
if encryptor:
body = encryptor(body)
return PackedBytes('private_key').pack(body)
@staticmethod
def unpack(encoded_bytes: bytes, decryptor: FunctionType=None) -> ('RSAPrivateKey', bytes):
"""
Unpacks bytes into an RSAPrivateKey object.
Parameters:
encoded_bytes (bytes): Bytes to be (partially?) decoded.
decryptor (func): (Optional) Function to use as the decryptor.
Returns:
(RSAPrivateKey, bytes): The decoded object and unused bytes.
"""
params, encoded_bytes = PackedBytes('private_key').unpack(encoded_bytes)
check_bytes, params = check_decrypt(params, decryptor)
_header, params = PackedBytes('rsa-header').unpack(params)
n, params = PackedBytes('n').unpack(params)
e, params = PackedBytes('e').unpack(params)
d, params = PackedBytes('d').unpack(params)
q_mod_p, params = PackedBytes('q_mod_p').unpack(params)
p, params = PackedBytes('p').unpack(params)
q, params = PackedBytes('q').unpack(params)
host, params = PackedBytes('host').unpack(params)
return RSAPrivateKey('private_key', check_bytes=check_bytes, n=n.int(), e=e.int(), d=d.int(), q_mod_p=q_mod_p.int(), p=p.int(), q=q.int(), host=host), encoded_bytes
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/encoding/openssh/core/rsa_private_key.py
| 0.78968 | 0.208481 |
rsa_private_key.py
|
pypi
|
from samson.encoding.openssh.core.packed_bytes import PackedBytes
from samson.utilities.bytes import Bytes
class RSAPublicKey(object):
"""
OpenSSH encoding for an RSA public key.
"""
def __init__(self, name: str, n: int=None, e: int=None):
"""
Parameters:
name (str): Name for bookkeeping purposes.
n (int): RSA modulus.
e (int): RSA public exponent.
"""
self.name = name
self.n = n
self.e = e
def __repr__(self):
return f"<RSAPublicKey: name={self.name}, n={self.n}, e={self.e}>"
def __str__(self):
return self.__repr__()
@staticmethod
def pack(value: 'RSAPublicKey') -> Bytes:
"""
Packs a public key into an OpenSSH-compliant encoding.
Parameters:
value (RSAPublicKey): Value to encode.
Returns:
Bytes: Packed bytes.
"""
return PackedBytes('public_key').pack(
PackedBytes('rsa-header').pack(b'ssh-rsa') + PackedBytes('e').pack(value.e) + PackedBytes('n').pack(value.n)
)
@staticmethod
def unpack(encoded_bytes: bytes, already_unpacked: bool=False) -> ('RSAPublicKey', bytes):
"""
Unpacks bytes into an RSAPublicKey object.
Parameters:
encoded_bytes (bytes): Bytes to be (partially?) decoded.
already_unpacked (bool): Whether or not to do the initial length-decoding.
Returns:
(RSAPublicKey, bytes): The decoded object and unused bytes.
"""
if already_unpacked:
params, encoded_bytes = Bytes.wrap(encoded_bytes), None
else:
params, encoded_bytes = PackedBytes('public_key').unpack(encoded_bytes)
_header, params = PackedBytes('rsa-header').unpack(params)
e, params = PackedBytes('e').unpack(params)
n, params = PackedBytes('n').unpack(params)
return RSAPublicKey('public_key', n=n.int(), e=e.int()), encoded_bytes
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/encoding/openssh/core/rsa_public_key.py
| 0.806319 | 0.189352 |
rsa_public_key.py
|
pypi
|
from samson.encoding.openssh.core.packed_bytes import PackedBytes
from samson.utilities.bytes import Bytes
class ECDSAPublicKey(object):
"""
OpenSSH encoding for an ECDSA public key.
"""
def __init__(self, name: str, curve: bytes=None, x_y_bytes: bytes=None):
"""
Parameters:
name (str): Name for bookkeeping purposes.
curve (bytes): Elliptical curve name.
x_y_bytes (bytes): Byte encoding of x and y.
"""
self.name = name
self.curve = curve
self.x_y_bytes = x_y_bytes
def __repr__(self):
return f"<ECDSAPublicKey: name={self.name}, curve={self.curve}, x_y_bytes={self.x_y_bytes}>"
def __str__(self):
return self.__repr__()
@staticmethod
def pack(value: 'ECDSAPublicKey') -> Bytes:
"""
Packs a public key into an OpenSSH-compliant encoding.
Parameters:
value (ECDSAPublicKey): Value to encode.
Returns:
Bytes: Packed bytes.
"""
encoded = PackedBytes('ecdsa-header').pack(b'ecdsa-sha2-' + value.curve) + PackedBytes('curve').pack(value.curve) + PackedBytes('x_y_bytes').pack(value.x_y_bytes)
encoded = PackedBytes('public_key').pack(encoded)
return encoded
@staticmethod
def unpack(encoded_bytes: bytes, already_unpacked: bool=False) -> ('ECDSAPublicKey', bytes):
"""
Unpacks bytes into an ECDSAPublicKey object.
Parameters:
encoded_bytes (bytes): Bytes to be (partially?) decoded.
already_unpacked (bool): Whether or not to do the initial length-decoding.
Returns:
(ECDSAPublicKey, bytes): The decoded object and unused bytes.
"""
encoded_bytes = Bytes.wrap(encoded_bytes)
if already_unpacked:
params, encoded_bytes = encoded_bytes, None
else:
params, encoded_bytes = PackedBytes('public_key').unpack(encoded_bytes)
_header, params = PackedBytes('ecdsa-header').unpack(params)
curve, params = PackedBytes('curve').unpack(params)
x_y_bytes, params = PackedBytes('x_y_bytes').unpack(params)
return ECDSAPublicKey('public_key', curve=curve, x_y_bytes=x_y_bytes), encoded_bytes
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/encoding/openssh/core/ecdsa_public_key.py
| 0.883751 | 0.238927 |
ecdsa_public_key.py
|
pypi
|
from samson.encoding.openssh.core.packed_bytes import PackedBytes
from samson.utilities.bytes import Bytes
from samson.encoding.openssh.general import check_decrypt
from samson.encoding.openssh.core.literal import Literal
from samson.padding.incremental_padding import IncrementalPadding
from types import FunctionType
class ECDSAPrivateKey(object):
"""
OpenSSH encoding for an ECDSA private key.
"""
def __init__(self, name: str, check_bytes: bytes=None, curve: bytes=None, x_y_bytes: bytes=None, d: int=None, host: bytes=None):
"""
Parameters:
name (str): Name for bookkeeping purposes.
check_bytes (bytes): Four random bytes repeated for OpenSSH to check if the decryption worked.
curve (bytes): Elliptical curve name.
x_y_bytes (bytes): Byte encoding of x and y.
host (bytes): Host the key was generated on.
"""
self.name = name
self.check_bytes = check_bytes or Bytes.random(4) * 2
self.curve = curve
self.x_y_bytes = x_y_bytes
self.d = d
self.host = host
def __repr__(self):
return f"<ECDSAPrivateKey: name={self.name}, curve={self.curve}, x_y_bytes={self.x_y_bytes}, d={self.d}, host={self.host}>"
def __str__(self):
return self.__repr__()
@staticmethod
def pack(value: 'ECDSAPrivateKey', encryptor: FunctionType=None, padding_size: int=8) -> Bytes:
"""
Packs a private key into an OpenSSH-compliant encoding.
Parameters:
value (ECDSAPrivateKey): Value to encode.
encryptor (func): (Optional) Function to use as the encryptor.
padding_size (int): The block size to pad to. Usually 8 unless you're encrypting.
Returns:
Bytes: Packed bytes.
"""
check_bytes = Literal('check_bytes', length=8).pack(value.check_bytes)
encoded = check_bytes + PackedBytes('ecdsa-header').pack(b'ecdsa-sha2-' + value.curve) + PackedBytes('curve').pack(value.curve) + PackedBytes('x_y_bytes').pack(value.x_y_bytes) + PackedBytes('d').pack(value.d) + PackedBytes('host').pack(value.host)
padder = IncrementalPadding(padding_size)
body = padder.pad(encoded)
if encryptor:
body = encryptor(body)
body = PackedBytes('private_key').pack(body)
return body
@staticmethod
def unpack(encoded_bytes: bytes, decryptor: FunctionType=None, already_unpacked: bool=False) -> ('ECDSAPrivateKey', bytes):
"""
Unpacks bytes into an ECDSAPrivateKey object.
Parameters:
encoded_bytes (bytes): Bytes to be (partially?) decoded.
already_unpacked (bool): Whether or not to do the initial length-decoding.
Returns:
(ECDSAPrivateKey, bytes): The decoded object and unused bytes.
"""
encoded_bytes = Bytes.wrap(encoded_bytes)
if already_unpacked:
params, encoded_bytes = encoded_bytes, None
else:
params, encoded_bytes = PackedBytes('private_key').unpack(encoded_bytes)
check_bytes, params = check_decrypt(params, decryptor)
_header, params = PackedBytes('ecdsa-header').unpack(params)
curve, params = PackedBytes('curve').unpack(params)
x_y_bytes, params = PackedBytes('x_y_bytes').unpack(params)
d, params = PackedBytes('d').unpack(params)
host, params = PackedBytes('host').unpack(params)
return ECDSAPrivateKey('private_key', check_bytes=check_bytes, curve=curve, x_y_bytes=x_y_bytes, d=d.int(), host=host), encoded_bytes
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/encoding/openssh/core/ecdsa_private_key.py
| 0.863651 | 0.237941 |
ecdsa_private_key.py
|
pypi
|
from samson.encoding.openssh.core.packed_bytes import PackedBytes
from samson.encoding.openssh.core.literal import Literal
from samson.encoding.openssh.core.kdf_params import KDFParams
from samson.utilities.bytes import Bytes
from types import FunctionType
from samson.block_ciphers.rijndael import Rijndael
from samson.block_ciphers.modes.ctr import CTR
from samson.kdfs.bcrypt_pbkdf import BcryptPBKDF
def init_aes256_ctr(key_iv):
key, iv = key_iv[:32], key_iv[32:]
ctr = CTR(Rijndael(key), nonce=b'')
ctr.counter = iv.int()
return ctr
def derive_bcrypt_pbkdf(passphrase, rounds, key_size, salt=None):
kdf = BcryptPBKDF(rounds=rounds)
return kdf.derive(passphrase, salt, key_size)
KDF_ALGS = {
'bcrypt': derive_bcrypt_pbkdf
}
ENC_ALGS = {
'aes256-ctr': (init_aes256_ctr, 48, 16)
}
SPEC = [
Literal('header', 15),
PackedBytes('encryption'),
PackedBytes('kdf'),
KDFParams('kdf_params'),
Literal('num_keys')
]
class OpenSSHPrivateHeader(object):
"""
Represents a full, private OpenSSH key.
"""
MAGIC_HEADER = b'openssh-key-v1\x00'
def __init__(self, header: bytes, encryption: bytes, kdf: bytes, kdf_params: KDFParams, num_keys: int):
"""
Parameters:
header (bytes): Header value to include. Should be b'openssh-v1\x00'
encryption (bytes): Encryption algorithm to use.
kdf (bytes): KDF to use.
kdf_params (KDFParams): Parameters for the KDF.
num_keys (int): Number of keys encoded. Should be 1.
"""
self.spec = SPEC
self.header = header
self.encryption = encryption
self.kdf = kdf
self.kdf_params = kdf_params
self.num_keys = num_keys
def __repr__(self):
return f"<OpenSSHPrivateHeader: header={self.header}, encryption={self.encryption}, kdf={self.kdf}, kdf_params={self.kdf_params}, num_keys={self.num_keys}>"
def __str__(self):
return self.__repr__()
def pack(self) -> Bytes:
"""
Packs a private key into an OpenSSH-compliant encoding.
Parameters:
value (bytes): Value to encode.
Returns:
Bytes: Packed bytes.
"""
val = Bytes(b'')
self_dict = self.__dict__
for item in SPEC:
val += item.pack(self_dict[item.name])
return val
@staticmethod
def unpack(encoded_bytes: bytes):
"""
Unpacks bytes into an OpenSSHPrivateHeader object.
Parameters:
encoded_bytes (bytes): Bytes to be decoded.
Returns:
OpenSSHPrivateHeader: The decoded object.
"""
encoded_bytes = Bytes.wrap(encoded_bytes)
vals = {}
for item in SPEC:
val, encoded_bytes = item.unpack(encoded_bytes)
vals[item.name] = val
vals['num_keys'] = vals['num_keys'].int()
return OpenSSHPrivateHeader(**vals), encoded_bytes
def generate_encryptor(self, passphrase: bytes) -> (FunctionType, int):
"""
Generates an encryptor based on the KDF parameters and `passphrase`.
Parameters:
passphrase (bytes): Passphrase for key derivation.
Returns:
(func, int): Encryption function and padding size.
"""
enc_func, key_size, padding_size = ENC_ALGS[self.encryption.decode()]
key_iv = KDF_ALGS[self.kdf.decode()](passphrase, self.kdf_params.rounds, key_size, self.kdf_params.salt)
return enc_func(key_iv).encrypt, padding_size
# TODO: Add more decryption algorithms
def generate_decryptor(self, passphrase: bytes) -> FunctionType:
"""
Generates an decryptor based on the KDF parameters and `passphrase`.
Parameters:
passphrase (bytes): Passphrase for key derivation.
Returns:
func: Encryption function.
"""
return self.generate_encryptor(passphrase)[0]
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/encoding/openssh/core/openssh_private_header.py
| 0.73077 | 0.212436 |
openssh_private_header.py
|
pypi
|
from samson.encoding.openssh.core.packed_bytes import PackedBytes
from samson.utilities.bytes import Bytes
from samson.encoding.openssh.general import check_decrypt
from samson.encoding.openssh.core.literal import Literal
from samson.padding.incremental_padding import IncrementalPadding
from types import FunctionType
class EdDSAPrivateKey(object):
"""
OpenSSH encoding for an EdDSA private key.
"""
def __init__(self, name: str, check_bytes: bytes=None, a: int=None, h: int=None, host: bytes=None):
"""
Parameters:
name (str): Name for bookkeeping purposes.
check_bytes (bytes): Four random bytes repeated for OpenSSH to check if the decryption worked.
a (int): Public int.
h (int): Hashed private int.
host (bytes): Host the key was generated on.
"""
self.name = name
self.check_bytes = check_bytes or Bytes.random(4) * 2
self.a = a
self.h = h
self.host = host
def __repr__(self):
return f"<EdDSAPrivateKey: name={self.name}, a={self.a}, h={self.h}, host={self.host}>"
def __str__(self):
return self.__repr__()
@staticmethod
def pack(value: 'EdDSAPrivateKey', encryptor: FunctionType=None, padding_size: int=8) -> Bytes:
"""
Packs a private key into an OpenSSH-compliant encoding.
Parameters:
value (EdDSAPrivateKey): Value to encode.
encryptor (func): (Optional) Function to use as the encryptor.
padding_size (int): The block size to pad to. Usually 8 unless you're encrypting.
Returns:
Bytes: Packed bytes.
"""
check_bytes = Literal('check_bytes', length=8).pack(value.check_bytes)
encoded = check_bytes + PackedBytes('eddsa-header').pack(b'ssh-ed25519') + PackedBytes('a').pack(value.a) + PackedBytes('h').pack(value.h[::-1]) + PackedBytes('host').pack(value.host)
padder = IncrementalPadding(padding_size)
body = padder.pad(encoded)
if encryptor:
body = encryptor(body)
body = PackedBytes('private_key').pack(body)
return body
@staticmethod
def unpack(encoded_bytes: bytes, decryptor: FunctionType=None, already_unpacked: bool=False) -> ('EdDSAPrivateKey', bytes):
"""
Unpacks bytes into an EdDSAPrivateKey object.
Parameters:
encoded_bytes (bytes): Bytes to be (partially?) decoded.
already_unpacked (bool): Whether or not to do the initial length-decoding.
Returns:
(EdDSAPrivateKey, bytes): The decoded object and unused bytes.
"""
encoded_bytes = Bytes.wrap(encoded_bytes)
if already_unpacked:
params, encoded_bytes = encoded_bytes, None
else:
params, encoded_bytes = PackedBytes('private_key').unpack(encoded_bytes)
check_bytes, params = check_decrypt(params, decryptor)
_header, params = PackedBytes('eddsa-header').unpack(params)
a, params = PackedBytes('a').unpack(params)
h, params = PackedBytes('h').unpack(params)
host, params = PackedBytes('host').unpack(params)
return EdDSAPrivateKey('private_key', check_bytes=check_bytes, a=a.int(), h=h[::-1], host=host), encoded_bytes
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/encoding/openssh/core/eddsa_private_key.py
| 0.799716 | 0.205854 |
eddsa_private_key.py
|
pypi
|
from samson.encoding.openssh.core.packed_bytes import PackedBytes
from samson.utilities.bytes import Bytes
class DSAPublicKey(object):
"""
OpenSSH encoding for an DSA public key.
"""
def __init__(self, name: str, p: int=None, q: int=None, g: int=None, y: int=None):
"""
Parameters:
name (str): Name for bookkeeping purposes.
p (int): Prime modulus.
q (int): Prime modulus.
g (int): Generator.
y (int): Public key.
"""
self.name = name
self.p = p
self.q = q
self.g = g
self.y = y
def __repr__(self):
return f"<DSAPublicKey: name={self.name}, p={self.p}, q={self.q}, g={self.g}, y={self.y}>"
def __str__(self):
return self.__repr__()
@staticmethod
def pack(value: 'DSAPublicKey') -> Bytes:
"""
Packs a public key into an OpenSSH-compliant encoding.
Parameters:
value (DSAPublicKey): Value to encode.
Returns:
Bytes: Packed bytes.
"""
encoded = PackedBytes('dsa-header').pack(b'ssh-dss') + PackedBytes('p').pack(value.p) + PackedBytes('q').pack(value.q) + PackedBytes('g').pack(value.g) + PackedBytes('y').pack(value.y)
encoded = PackedBytes('public_key').pack(encoded)
return encoded
@staticmethod
def unpack(encoded_bytes: bytes, already_unpacked: bool=False) -> ('DSAPublicKey', bytes):
"""
Unpacks bytes into an DSAPublicKey object.
Parameters:
encoded_bytes (bytes): Bytes to be (partially?) decoded.
already_unpacked (bool): Whether or not to do the initial length-decoding.
Returns:
(DSAPublicKey, bytes): The decoded object and unused bytes.
"""
encoded_bytes = Bytes.wrap(encoded_bytes)
if already_unpacked:
params, encoded_bytes = encoded_bytes, None
else:
params, encoded_bytes = PackedBytes('public_key').unpack(encoded_bytes)
_header, params = PackedBytes('dsa-header').unpack(params)
p, params = PackedBytes('p').unpack(params)
q, params = PackedBytes('q').unpack(params)
g, params = PackedBytes('g').unpack(params)
y, params = PackedBytes('y').unpack(params)
if already_unpacked:
encoded_bytes = params
return DSAPublicKey('public_key', p=p.int(), q=q.int(), g=g.int(), y=y.int()), encoded_bytes
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/encoding/openssh/core/dsa_public_key.py
| 0.796767 | 0.195057 |
dsa_public_key.py
|
pypi
|
from samson.encoding.general import export_der, bytes_to_der_sequence
from pyasn1.type.univ import Integer, OctetString, ObjectIdentifier, BitString, tag
from pyasn1.codec.ber import decoder as ber_decoder, encoder as ber_encoder
from samson.encoding.pem import PEMEncodable
from samson.utilities.bytes import Bytes
from samson.math.algebra.curves.named import WS_OID_LOOKUP
import math
def parse_ec_params(items, curve_idx, pub_point_idx):
from samson.public_key.ecdsa import ECDSA
curve_oid = items[curve_idx].asTuple()
oid_bytes = ber_encoder.encode(ObjectIdentifier(curve_oid))[2:]
curve = WS_OID_LOOKUP[oid_bytes]
x_y_bytes = Bytes(int(items[pub_point_idx]))
x, y = ECDSA.decode_point(x_y_bytes)
return x, y, curve
class NamedCurve(ObjectIdentifier):
tagSet = baseTagSet = tag.initTagSet(
tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 6)
).tagExplicitly(tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0))
typeId = ObjectIdentifier.typeId
class PublicPoint(BitString):
tagSet = baseTagSet = tag.initTagSet(
tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 3)
).tagExplicitly(tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 1))
typeId = BitString.typeId
class PKCS1ECDSAPrivateKey(PEMEncodable):
"""
Not in the RFC spec, but OpenSSL supports it.
"""
DEFAULT_MARKER = 'EC PRIVATE KEY'
DEFAULT_PEM = True
USE_RFC_4716 = False
@staticmethod
def check(buffer: bytes, **kwargs) -> bool:
try:
items = bytes_to_der_sequence(buffer)
return len(items) == 4 and int(items[0]) == 1
except Exception:
return False
def encode(self, **kwargs) -> bytes:
zero_fill = math.ceil(self.key.G.curve.order().bit_length() / 8)
encoded = export_der([1, Bytes(self.key.d).zfill(zero_fill), ber_decoder.decode(b'\x06' + bytes([len(self.key.G.curve.oid)]) + self.key.G.curve.oid)[0].asTuple(), self.key.format_public_point()], item_types=[Integer, OctetString, NamedCurve, PublicPoint])
encoded = PKCS1ECDSAPrivateKey.transport_encode(encoded, **kwargs)
return encoded
@staticmethod
def decode(buffer: bytes, **kwargs) -> 'ECDSA':
from samson.public_key.ecdsa import ECDSA
items = bytes_to_der_sequence(buffer)
d = Bytes(items[1]).int()
x, y, curve = parse_ec_params(items, 2, 3)
ecdsa = ECDSA(G=curve.G, hash_obj=None, d=d)
ecdsa.Q = curve(x, y)
return PKCS1ECDSAPrivateKey(ecdsa)
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/encoding/pkcs1/pkcs1_ecdsa_private_key.py
| 0.648911 | 0.233717 |
pkcs1_ecdsa_private_key.py
|
pypi
|
from pyasn1.type.univ import ObjectIdentifier, Sequence, Integer, OctetString
from pyasn1.codec.ber import decoder as ber_decoder
from samson.utilities.bytes import Bytes
from samson.encoding.pkcs1.pkcs1_ecdsa_private_key import parse_ec_params
class X509ECDSAParams(object):
@staticmethod
def encode(ecdsa_key):
E = ecdsa_key.G.curve
if hasattr(E, 'oid') and E.oid:
return ObjectIdentifier(ber_decoder.decode(b'\x06' + bytes([len(E.oid)]) + E.oid)[0].asTuple())
else:
# X9.62 explicit params
# https://www.itu.int/wftp3/Public/t/fl/itu-t/x/x894/2018-cor1/ANSI-X9-62.html
from samson.public_key.ecdsa import ECDSA
dummy = ECDSA(ecdsa_key.G, d=1)
prime_seq = Sequence()
prime_seq.setComponentByPosition(0, ObjectIdentifier('1.2.840.10045.1.1'))
prime_seq.setComponentByPosition(1, Integer(E.p))
curve_seq = Sequence()
curve_seq.setComponentByPosition(0, OctetString(Bytes(int(E.a))))
curve_seq.setComponentByPosition(1, OctetString(Bytes(int(E.b))))
top_seq = Sequence()
top_seq.setComponentByPosition(0, Integer(1))
top_seq.setComponentByPosition(1, prime_seq)
top_seq.setComponentByPosition(2, curve_seq)
top_seq.setComponentByPosition(3, OctetString(Bytes(int(dummy.format_public_point(), 2))))
top_seq.setComponentByPosition(4, Integer(ecdsa_key.G.order()))
top_seq.setComponentByPosition(5, Integer(E.order() // ecdsa_key.G.order()))
return top_seq
@staticmethod
def decode(curve_spec, pub_params):
from samson.public_key.ecdsa import ECDSA
try:
x, y, curve = parse_ec_params([curve_spec, pub_params], 0, 1)
# If we're here, it's probably using explicit parameters
except Exception:
from samson.math.algebra.rings.integer_ring import ZZ
from samson.math.algebra.curves.weierstrass_curve import EllipticCurve
_version, prime_params, curve_params, encoded_base, g_order, cofactor = [curve_spec[i] for i in range(len(curve_spec))]
p = int(prime_params[1])
a, b = Bytes(curve_params[0]).int(), Bytes(curve_params[1]).int()
gx, gy = ECDSA.decode_point(Bytes(encoded_base))
g_order = int(g_order)
cofactor = int(cofactor)
R = ZZ/ZZ(p)
curve = EllipticCurve(R(a), R(b), cardinality=cofactor*g_order, base_tuple=(gx, gy))
x, y = ECDSA.decode_point(Bytes(int(pub_params)))
ecdsa = ECDSA(G=curve.G, hash_obj=None, d=1)
ecdsa.d = None
ecdsa.Q = curve(x, y)
return ecdsa
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/encoding/x509/x509_ecdsa_params.py
| 0.623377 | 0.183649 |
x509_ecdsa_params.py
|
pypi
|
from samson.utilities.bytes import Bytes
from samson.encoding.general import bytes_to_der_sequence
from samson.encoding.pkcs8.pkcs8_rsa_private_key import PKCS8RSAPrivateKey
from samson.encoding.x509.x509_rsa_subject_public_key import X509RSASubjectPublicKey
from samson.encoding.x509.x509_public_key_base import X509PublicKeyBase
from pyasn1.type.univ import ObjectIdentifier, BitString, Sequence, Null
from pyasn1.codec.der import encoder, decoder
class X509RSAPublicKey(X509PublicKeyBase):
@staticmethod
def check(buffer: bytes, **kwargs) -> bool:
try:
items = bytes_to_der_sequence(buffer)
return not PKCS8RSAPrivateKey.check(buffer) and len(items) == 2 and str(items[0][0]) == '1.2.840.113549.1.1.1'
except Exception:
return False
def encode(self, **kwargs) -> bytes:
seq = Sequence()
seq.setComponentByPosition(0, ObjectIdentifier([1, 2, 840, 113549, 1, 1, 1]))
seq.setComponentByPosition(1, Null())
param_bs = X509RSASubjectPublicKey.encode(self.key)
top_seq = Sequence()
top_seq.setComponentByPosition(0, seq)
top_seq.setComponentByPosition(1, param_bs)
encoded = encoder.encode(top_seq)
return X509RSAPublicKey.transport_encode(encoded, **kwargs)
@staticmethod
def decode(buffer: bytes, **kwargs) -> 'RSA':
from samson.public_key.rsa import RSA
items = bytes_to_der_sequence(buffer)
if type(items[1]) is BitString:
if str(items[0][0]) == '1.2.840.113549.1.1.1':
bitstring_seq = decoder.decode(Bytes(int(items[1])))[0]
items = list(bitstring_seq)
else:
raise ValueError('Unable to decode RSA key.')
n, e = [int(item) for item in items]
# TODO: uhh, pyasn1 sometimes returns a negative integer...
if n < 0:
# Align to byte
bit_length = ((-n).bit_length() + 7) // 8 * 8
n = range(2**bit_length)[n]
rsa = RSA(n=n, e=e)
return X509RSAPublicKey(rsa)
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/encoding/x509/x509_rsa_public_key.py
| 0.470737 | 0.155335 |
x509_rsa_public_key.py
|
pypi
|
from samson.utilities.bytes import Bytes
from samson.encoding.general import url_b64_decode, url_b64_encode
from samson.math.algebra.curves.named import P192, P224, P256, P384, P521, GOD521
from samson.encoding.jwk.jwk_base import JWKBase
import json
JWK_CURVE_NAME_LOOKUP = {
P192: 'P-192',
P224: 'P-224',
P256: 'P-256',
P384: 'P-384',
P521: 'P-521',
GOD521: 'P-521'
}
JWK_INVERSE_CURVE_LOOKUP = {v:k for k, v in JWK_CURVE_NAME_LOOKUP.items() if k != GOD521}
class JWKECPublicKey(JWKBase):
"""
JWK encoder for ECDSA public keys
"""
@staticmethod
def check(buffer: bytes, **kwargs) -> bool:
"""
Checks if `buffer` can be parsed with this encoder.
Parameters:
buffer (bytes): Buffer to check.
Returns:
bool: Whether or not `buffer` is the correct format.
"""
try:
if issubclass(type(buffer), (bytes, bytearray)):
buffer = buffer.decode()
jwk = json.loads(buffer)
return jwk['kty'] == 'EC' and not ('d' in jwk)
except (json.JSONDecodeError, UnicodeDecodeError):
return False
@staticmethod
def build_pub(ec_key: 'ECDSA') -> dict:
"""
Formats the public parameters of the key as a `dict`.
Parameters:
ec_key (ECDSA): Key to format.
Returns:
dict: JWK dict with public parameters.
"""
jwk = {
'kty': 'EC',
'crv': JWK_CURVE_NAME_LOOKUP[ec_key.G.curve],
'x': url_b64_encode(Bytes(int(ec_key.Q.x))).decode(),
'y': url_b64_encode(Bytes(int(ec_key.Q.y))).decode(),
}
return jwk
def encode(self, **kwargs) -> str:
"""
Encodes the key as a JWK JSON string.
Parameters:
ec_key (ECDSA): ECDSA key to encode.
Returns:
str: JWK JSON string.
"""
jwk = JWKECPublicKey.build_pub(self.key)
return Bytes(json.dumps(jwk).encode('utf-8'))
@staticmethod
def decode(buffer: bytes, **kwargs) -> 'ECDSA':
"""
Decodes a JWK JSON string into an ECDSA object.
Parameters:
buffer (bytes/str): JWK JSON string.
Returns:
ECDSA: ECDSA object.
"""
from samson.public_key.ecdsa import ECDSA
if issubclass(type(buffer), (bytes, bytearray)):
buffer = buffer.decode()
jwk = json.loads(buffer)
curve = JWK_INVERSE_CURVE_LOOKUP[jwk['crv']]
x = Bytes(url_b64_decode(jwk['x'].encode('utf-8'))).int()
y = Bytes(url_b64_decode(jwk['y'].encode('utf-8'))).int()
if 'd' in jwk:
d = Bytes(url_b64_decode(jwk['d'].encode('utf-8'))).int()
else:
d = 0
ecdsa = ECDSA(G=curve.G, hash_obj=None, d=d)
ecdsa.Q = curve(x, y)
return JWKECPublicKey(ecdsa)
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/encoding/jwk/jwk_ec_public_key.py
| 0.753104 | 0.213357 |
jwk_ec_public_key.py
|
pypi
|
from samson.utilities.bytes import Bytes
from samson.math.algebra.curves.named import EdwardsCurve25519, EdwardsCurve448, Curve25519, Curve448
from samson.encoding.general import url_b64_decode, url_b64_encode
from samson.encoding.jwk.jwk_base import JWKBase
import json
JWK_CURVE_NAME_LOOKUP = {
EdwardsCurve25519: 'Ed25519',
EdwardsCurve448: 'Ed448',
Curve25519: 'X25519',
Curve448: 'X448'
}
JWK_INVERSE_CURVE_LOOKUP = {v:k for k, v in JWK_CURVE_NAME_LOOKUP.items()}
class JWKEdDSAPublicKey(JWKBase):
"""
JWK encoder for EdDSA public keys
"""
@staticmethod
def check(buffer: bytes, **kwargs) -> bool:
"""
Checks if `buffer` can be parsed with this encoder.
Parameters:
buffer (bytes): Buffer to check.
Returns:
bool: Whether or not `buffer` is the correct format.
"""
try:
if issubclass(type(buffer), (bytes, bytearray)):
buffer = buffer.decode()
jwk = json.loads(buffer)
return jwk['kty'] == 'OKP' and jwk['crv'] in ['Ed25519', 'Ed448', 'X25519', 'X448'] and not 'd' in jwk
except (json.JSONDecodeError, UnicodeDecodeError):
return False
@staticmethod
def build_pub(eddsa_key: 'EdDSA') -> dict:
"""
Formats the public parameters of the key as a `dict`.
Parameters:
eddsa_key (EdDSA): Key to format.
Returns:
dict: JWK dict with public parameters.
"""
jwk = {
'kty': 'OKP',
'crv': JWK_CURVE_NAME_LOOKUP[eddsa_key.curve],
'x': url_b64_encode(eddsa_key.get_pub_bytes()).decode()
}
return jwk
def encode(self, **kwargs) -> str:
"""
Encodes the key as a JWK JSON string.
Parameters:
eddsa_key (EdDSA): EdDSA key to encode.
Returns:
str: JWK JSON string.
"""
jwk = JWKEdDSAPublicKey.build_pub(self.key)
return Bytes(json.dumps(jwk).encode('utf-8'))
@staticmethod
def decode(buffer: bytes, **kwargs) -> 'EdDSA':
"""
Decodes a JWK JSON string into EdDSA parameters.
Parameters:
buffer (bytes/str): JWK JSON string.
Returns:
EdDSA: EdDSA object.
"""
from samson.public_key.eddsa import EdDSA
from samson.protocols.dh25519 import DH25519
if issubclass(type(buffer), (bytes, bytearray)):
buffer = buffer.decode()
jwk = json.loads(buffer)
curve = JWK_INVERSE_CURVE_LOOKUP[jwk['crv']]
x = Bytes(url_b64_decode(jwk['x'].encode('utf-8')), 'little')
if 'd' in jwk:
d = Bytes(url_b64_decode(jwk['d'].encode('utf-8'))).int()
else:
d = 0
if jwk['crv'] in ['Ed25519', 'Ed448']:
eddsa = EdDSA(curve=curve, d=d)
eddsa.A = eddsa.decode_point(x)
else:
eddsa = DH25519(curve=curve, d=d, pub=x.int())
return JWKEdDSAPublicKey(eddsa)
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/encoding/jwk/jwk_eddsa_public_key.py
| 0.746509 | 0.239116 |
jwk_eddsa_public_key.py
|
pypi
|
from samson.utilities.bytes import Bytes
from samson.encoding.general import url_b64_decode, url_b64_encode
from samson.encoding.jwk.jwk_base import JWKBase
import json
class JWKRSAPublicKey(JWKBase):
"""
JWK encoder for RSA public keys
"""
@staticmethod
def check(buffer: bytes, **kwargs) -> bool:
"""
Checks if `buffer` can be parsed with this encoder.
Parameters:
buffer (bytes): Buffer to check.
Returns:
bool: Whether or not `buffer` is the correct format.
"""
try:
if issubclass(type(buffer), (bytes, bytearray)):
buffer = buffer.decode()
jwk = json.loads(buffer)
return jwk['kty'] == 'RSA' and not ('d' in jwk)
except (json.JSONDecodeError, UnicodeDecodeError):
return False
@staticmethod
def build_pub(rsa_key: 'RSA') -> dict:
"""
Formats the public parameters of the key as a `dict`.
Parameters:
rsa_key (RSA): Key to format.
Returns:
dict: JWK dict with public parameters.
"""
jwk = {
'kty': 'RSA',
'n': url_b64_encode(Bytes(rsa_key.n)).decode(),
'e': url_b64_encode(Bytes(rsa_key.e)).decode(),
}
return jwk
def encode(self, **kwargs) -> str:
"""
Encodes the key as a JWK JSON string.
Parameters:
rsa_key (RSA): RSA key to encode.
Returns:
str: JWK JSON string.
"""
jwk = JWKRSAPublicKey.build_pub(self.key)
return Bytes(json.dumps(jwk).encode('utf-8'))
@staticmethod
def decode(buffer: bytes, **kwargs) -> 'RSA':
"""
Decodes a JWK JSON string into an RSA object.
Parameters:
buffer (bytes/str): JWK JSON string.
Returns:
RSA: RSA object.
"""
from samson.public_key.rsa import RSA
if issubclass(type(buffer), (bytes, bytearray)):
buffer = buffer.decode()
jwk = json.loads(buffer)
n = Bytes(url_b64_decode(jwk['n'].encode('utf-8'))).int()
e = Bytes(url_b64_decode(jwk['e'].encode('utf-8'))).int()
if 'p' in jwk:
p = Bytes(url_b64_decode(jwk['p'].encode('utf-8'))).int()
q = Bytes(url_b64_decode(jwk['q'].encode('utf-8'))).int()
else:
p = None
q = None
rsa = RSA(n.bit_length(), n=n, p=p, q=q, e=e)
return JWKRSAPublicKey(rsa)
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/encoding/jwk/jwk_rsa_public_key.py
| 0.740362 | 0.24073 |
jwk_rsa_public_key.py
|
pypi
|
from samson.utilities.bytes import Bytes
from samson.encoding.pgp.core.constants import PGPPublicKeyAlgo
from enum import Enum
# https://tools.ietf.org/html/rfc4880#section-4.2.2
class PGPLength(object):
def __init__(self, length):
self.length = length
def __repr__(self):
return f"<PGPLength: length={self.length}>"
def __str__(self):
return self.__repr__()
def encode(self) -> bytes:
if self.length < 192:
return Bytes(self.length)
elif self.length < 8383:
# The constant was calculated algebraically from the respective two-byte decode function
return Bytes(self.length + 48960)
else:
return Bytes(0xFF) + Bytes(self.length).zfill(4)
@staticmethod
def decode(len_bytes: bytes) -> object:
encoding_len = len(len_bytes)
if encoding_len == 1:
length = Bytes.wrap(len_bytes).int()
elif encoding_len == 2:
length = ((len_bytes[0] - 192) << 8) + len_bytes[1] + 192
else:
length = (len_bytes[1] << 24) + (len_bytes[2] << 16) + (len_bytes[3] << 8) + len_bytes[4]
return PGPLength(length)
class PGPPacketTag(Enum):
PUBLIC_KEY_ENC_SESSION_KEY = 1
SIGNATURE = 2
SYMMETRIC_KEY_ENC_SESSION_KEY = 3
ONE_PASS_SIG = 4
SECRET_KEY = 5
PUBLIC_KEY = 6
SECRET_SUBKEY = 7
COMPRESSED_DATA = 8
SYMMETRICALLY_ENC_DATA = 9
MARKER = 10
LITERAL_DATA = 11
TRUST_PACKET = 12
USER_ID = 13
PUBLIC_SUBKEY = 14
USER_ATTRIB = 17
SYMMETRICALLY_ENC_AND_INTEGRITY_PROTECTED_DATA = 18
MODIFICATION_DETECTION_CODE = 19
# https://tools.ietf.org/html/rfc4880#section-4
class PGPPacket(object):
def __init__(self, tag):
self.tag = tag
class PGPPublicKeyPacket(object):
def __init__(self, version: int, timestamp: int, pub_key_algo: PGPPublicKeyAlgo):
self.version = version
self.timestamp = timestamp
self.pub_key_algo = pub_key_algo
def __repr__(self):
return f"<PGPPublicKeyPacket: version={self.version}, timestamp={self.timestamp}, pub_key_algo={self.pub_key_algo}>"
def __str__(self):
return self.__repr__()
class PGPRSAPublicKeyPacket(PGPPublicKeyPacket):
def __init__(self, version: int, timestamp: int, n: int, e: int):
super().__init__(version, timestamp, PGPPublicKeyAlgo.RSA_ENC)
self.n = n
self.e = e
def __repr__(self):
return f"<PGPRSAPublicKeyPacket: version={self.version}, timestamp={self.timestamp}, n={self.n}, e={self.e}>"
def __str__(self):
return self.__repr__()
def encode(self) -> bytes:
pass
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/encoding/pgp/core/packet.py
| 0.518059 | 0.154185 |
packet.py
|
pypi
|
from samson.utilities.bytes import Bytes
from samson.core.base_object import BaseObject
from types import FunctionType
class FeistelNetwork(BaseObject):
"""
Construction for building block ciphers. Operates on half of a plaintext or ciphertext at a time and
interleaves invocations of the Feistel function. If the Feistel function (`round_func`) is a cryptographically
secure pseudorandom function, then three rounds are sufficient to make the cipher a pseudorandom permutation.
Four rounds makes it a strong pseudorandom permutation.
"""
def __init__(self, round_func: FunctionType, key_schedule: FunctionType):
"""
Parameter:
round_func (func): The Feistel function that takes in a state and subkey and returns a new state. Does not need to be invertible.
key_schedule (func): Function that takes in a key and returns a list or generator of subkeys.
"""
self.round_func = round_func
self.key_schedule = key_schedule
def yield_encrypt(self, key: bytes, plaintext: bytes):
"""
Yields the intermediate, encrypted states of the `plaintext`.
Parameters:
key (bytes): Bytes-like object to key the cipher.
plaintext (bytes): Bytes-like object to be encrypted.
Returns:
generator: Resulting intermediate ciphertext.
"""
half = len(plaintext) // 2
plaintext = Bytes.wrap(plaintext)
L_i, R_i = plaintext[:half], plaintext[half:]
round_keys = list(self.key_schedule(key))
for subkey in round_keys:
L_i, R_i = R_i, (L_i ^ self.round_func(R_i, subkey))
yield R_i, L_i
def yield_decrypt(self, key: bytes, ciphertext: bytes):
"""
Yields the intermediate, decrypted states of the `ciphertext`.
Parameters:
key (bytes): Bytes-like object to key the cipher.
ciphertext (bytes): Bytes-like object to be decrypted.
Returns:
generator: Resulting intermediate plaintext.
"""
half = len(ciphertext) // 2
ciphertext = Bytes.wrap(ciphertext)
R_i, L_i = ciphertext[:half], ciphertext[half:]
round_keys = list(self.key_schedule(key))[::-1]
for subkey in round_keys:
R_i, L_i = L_i, (R_i ^ self.round_func(L_i, subkey))
yield L_i, R_i
def encrypt(self, key: bytes, plaintext: bytes) -> Bytes:
"""
Encrypts `plaintext` by yielding the final state of the Feistel network.
Parameters:
key (bytes): Bytes-like object to key the cipher.
plaintext (bytes): Bytes-like object to be encrypted.
Returns:
Bytes: Resulting ciphertext.
"""
return Bytes(b''.join(list(self.yield_encrypt(key, plaintext))[-1]))
def decrypt(self, key: bytes, ciphertext: bytes) -> Bytes:
"""
Decrypts `ciphertext` by yielding the final state of the Feistel network.
Parameters:
key (bytes): Bytes-like object to key the cipher.
ciphertext (bytes): Bytes-like object to be decrypted.
Returns:
Bytes: Resulting plaintext.
"""
return Bytes(b''.join(list(self.yield_decrypt(key, ciphertext))[-1]))
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/constructions/feistel_network.py
| 0.881977 | 0.539529 |
feistel_network.py
|
pypi
|
from samson.utilities.manipulation import get_blocks
from samson.utilities.bytes import Bytes
from samson.core.metadata import ConstructionType
from samson.core.primitives import Hash
from types import FunctionType
from copy import deepcopy
def md_pad(msg: bytes, fakeLen: int=None, byteorder: str='little', bit_size: int=64, encoded_size_length: int=None) -> bytes:
length = fakeLen or len(msg)
# Append the bit '1' to the message
padding = b'\x80'
byte_size = encoded_size_length or (bit_size // 8)
# Append 0 <= k < 512 bits '0', so that the resulting message length (in bytes)
# as congruent to 56 (mod 64)
padding += b'\x00' * (((bit_size - byte_size) - (length + 1) % bit_size) % bit_size)
# Append length of message (before pre-processing), in bits, as 64-bit big-endian integer
message_bit_length = length * 8
padding += message_bit_length.to_bytes(byte_size, byteorder=byteorder)
return msg + padding
class MerkleDamgardConstruction(Hash):
"""
An iterative construction for building collision-resistant cryptographic hash functions from collision-resistant
one-way compression functions. Used in MD4, MD5, SHA1, SHA2, RIPEMD, and more.
"""
CONSTRUCTION_TYPES = [ConstructionType.MERKLE_DAMGARD]
def __init__(self, initial_state: bytes, compression_func: FunctionType, digest_size: int, block_size: int=64, endianness: str='big', encoded_size_length: int=None):
"""
Parameters:
initial_state (bytes): Bytes-like initial state that is the correct size for the underlying compression function.
compression_func (func): One-way compression function. Takes in the state and returns the next.
digest_size (int): Resulting digest size. Should be the same size as the `initial_state`.
block_size (int): Size of the internal state.
endianness (str): Endianess of the internal state.
encoded_size_length (int): Size in bytes of encoded message length.
"""
if not type(initial_state) is Bytes:
initial_state = Bytes([_ for _ in initial_state])
self.initial_state = initial_state
# Allows for direct use of class and subclass overriding simultaneously
if compression_func:
self.compression_func = compression_func
self.digest_size = digest_size
self.block_size = block_size
self.endianness = endianness
self.encoded_size_length = encoded_size_length
def __reprdir__(self):
return ['initial_state', 'compression_func', 'block_size']
def pad_func(self, message: bytes) -> Bytes:
"""
Pads the message with Merkle-Damgard padding.
Parameters:
message (bytes): Message to be padded.
Returns:
Bytes: Padded message.
"""
return md_pad(message, None, self.endianness, bit_size=self.block_size, encoded_size_length=self.encoded_size_length)
def yield_state(self, message: bytes) -> Bytes:
"""
Yields the intermediate, hashed states of the `message`.
Parameters:
message (bytes): Message to be hashed.
Returns:
Bytes: Intermediate, hashed states.
"""
state = self.initial_state
message = Bytes.wrap(message)
for block in get_blocks(self.pad_func(message), self.block_size):
state = self.compression_func(block, state)
yield state
def hash(self, message: bytes) -> Bytes:
"""
Yields the final, hashed state of the `message`.
Parameters:
message (bytes): Message to be hashed.
Returns:
Bytes: Fully-hashed state.
"""
final_state = list(self.yield_state(message))[-1]
return final_state
def length_extension(self, observed_output: bytes, message: bytes, bytes_to_append: bytes, secret_len: int) -> (Bytes, Bytes):
"""
Performs a length-extension attack.
Unaware developers may create a keyed-MAC using a Merkle-Damgard construction and prepending a
secret key to the input. However, such schemes are susceptible to length-extension attacks where an
attacker can forge a valid HMAC with an arbitrary, appended message.
Parameters:
observed_output (bytes): The observed, valid, hash output.
message (bytes): Message originally hashed.
bytes_to_append (bytes): Bytes to append to the end.
secret_len (int): The length of the secret.
Returns:
(Bytes, Bytes): Result formatted as (crafted input, forged hash).
"""
glue = md_pad(message, len(message) + secret_len, self.endianness, bit_size=self.block_size)[len(message):]
fake_len = secret_len + len(message) + len(glue) + len(bytes_to_append)
new_hash_obj = deepcopy(self)
new_hash_obj.initial_state = observed_output
new_hash_obj.pad_func = lambda msg: md_pad(msg, fake_len, self.endianness, bit_size=self.block_size)
return Bytes(message + glue + bytes_to_append), new_hash_obj.hash(bytes_to_append)
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/constructions/merkle_damgard_construction.py
| 0.867289 | 0.425784 |
merkle_damgard_construction.py
|
pypi
|
from samson.utilities.bytes import Bytes
from samson.core.base_object import BaseObject
from types import FunctionType
# https://en.wikipedia.org/wiki/One-way_compression_function#Davies%E2%80%93Meyer
class DaviesMeyerConstruction(BaseObject):
"""
A Davies-Meyer construction is a one-way compression function built from a block cipher.
"""
def __init__(self, initial_state: bytes, encryptor: FunctionType):
"""
Parameters:
initial_state (bytes): Bytes-like initial state that is the correct size for the underlying cipher.
encryptor (func): Function that takes in a key and plaintext and returns a ciphertext.
"""
self.initial_state = Bytes.wrap(initial_state)
self.block_size = len(self.initial_state)
self.encryptor = encryptor
def yield_state(self, message: bytes):
"""
Yields the intermediate, hashed states of the `message`.
Parameters:
message (bytes): Message to be hashed.
Returns:
generator: Intermediate, hashed states.
"""
message = Bytes.wrap(message)
last_state = self.initial_state
for block in message.chunk(self.block_size):
last_state ^= self.encryptor(block, last_state)
yield last_state
def hash(self, message: bytes) -> Bytes:
"""
Yields the final, hashed state of the `message`.
Parameters:
message (bytes): Message to be hashed.
Returns:
Bytes: Fully-hashed state.
"""
final_state = [_ for _ in self.yield_state(message)][-1]
return final_state
@staticmethod
def generate_fixed_point(block_cipher: type, message: bytes, block_size: int) -> 'DaviesMeyerConstruction':
"""
Generates a Davies-Meyer fixed point. A fixed point is a state in which its output matches
its input, and, therefore, infinitely produces itself.
Parameters:
block_cipher (type): Block cipher type.
message (bytes): Message you want to be fixed point.
block_size (int): Block size of `block_cipher`.
Returns:
DaviesMeyerConstruction: A DaviesMeyerConstruction with the initial state set to the fixed point.
"""
message = Bytes.wrap(message)
first_block = message.chunk(block_size)[0]
initial_state = block_cipher(first_block).decrypt(Bytes(b'').zfill(block_size))
return DaviesMeyerConstruction(initial_state=initial_state, encryptor=lambda key, msg: block_cipher(key).encrypt(msg))
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/constructions/davies_meyer_construction.py
| 0.866881 | 0.520801 |
davies_meyer_construction.py
|
pypi
|
from math import ceil
from samson.utilities.bytes import Bytes
from samson.core.base_object import BaseObject
from types import FunctionType
class SpongeConstruction(BaseObject):
"""
"The sponge construction is a mode of operation, based on a fixed-length permutation (or transformation) and on a padding rule, which builds a function mapping variable-length input to variable-length output"
https://keccak.team/sponge_duplex.html
"""
def __init__(self, perm_func: FunctionType, pad_func: FunctionType, r: int, c: int):
"""
Parameters:
perm_func (func): Sponge permutation function.
pad_func (func): Function for padding messages. Takes in bytes and returns them with padding.
r (int): Bit-size of the sponge function.
c (int): Sponge capacity.
"""
self.perm_func = perm_func
self.pad_func = pad_func
self.r = r
self.c = c
self.block_size = (self.r + 7) // 8
self.S = [[0] * 5 for _ in range(5)]
def __reprdir__(self):
return ['r', 'c', 'block_size', 'S', 'pad_func']
def reset(self):
"""
Resets the sponge to its initial state.
"""
self.S = [[0] * 5 for _ in range(5)]
def absorb(self, in_bytes: bytes):
"""
Absorbs bytes into the sponge.
Parameters:
in_bytes (bytes): Bytes to absorb.
"""
padded = self.pad_func(in_bytes)
for block in padded.chunk(self.block_size):
curr = 0
for y in range(5):
for x in range(5):
self.S[x][y] ^= sum([byte << i * 8 for i, byte in enumerate(block[curr:curr + 8])])
curr += 8
self.S = self.perm_func(self.S)
def squeeze(self, amount: int) -> list:
"""
Squeezes bytes out of the sponge.
Parameters:
amount (int): Number of bytes to return.
Returns:
generator: Yields blocks of Bytes until at least request `amount` has been returned.
"""
for _ in range(ceil(amount / self.block_size)):
out = Bytes(b'')
for y in range(5):
for x in range(5):
out += Bytes(self.S[x][y]).zfill(8)[::-1]
yield out[:self.block_size]
self.S = self.perm_func(self.S)
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/constructions/sponge_construction.py
| 0.843766 | 0.426501 |
sponge_construction.py
|
pypi
|
from samson.utilities.runtime import RUNTIME
from samson.protocols.diffie_hellman import DiffieHellman
from samson.core.metadata import FrequencyType, EphemeralType, SizeType, UsageType
from samson.core.primitives import BlockCipher, BlockCipherMode, StreamingBlockCipherMode
from samson.core.base_object import BaseObject
from samson.oracles.chosen_plaintext_oracle import ChosenPlaintextOracle
from samson.analysis.integer_analysis import IntegerAnalysis
from itertools import groupby
from types import FunctionType
import logging
log = logging.getLogger(__name__)
WELL_KNOWN_GROUPS = {
DiffieHellman.MODP_1536: 'MODP_1536',
DiffieHellman.MODP_2048: 'MODP_2048',
DiffieHellman.MODP_3072: 'MODP_3072',
DiffieHellman.MODP_4096: 'MODP_4096',
DiffieHellman.MODP_6144: 'MODP_6144',
DiffieHellman.MODP_8192: 'MODP_8192'
}
class Fingerprint(BaseObject):
def __init__(self, candidates, modes, max_input_analysis, io_relation, block_size):
self.candidates = candidates
self.modes = modes
self.max_input_analysis = max_input_analysis
self.io_relation = io_relation
self.block_size = block_size
def __reprdir__(self):
return ['io_relation', 'block_size', 'candidates', 'modes', 'max_input_analysis']
def group_candidates(self) -> list:
"""
Sorts and groups candidates by their score.
Returns:
list: List of candidate groups with the highest scoring first.
"""
sorted_candidates = sorted(self.candidates.items(), key=lambda item: item[1], reverse=True)
groups = []
for _score, g in groupby(sorted_candidates, key=lambda item: item[1]):
groups.append(list(g))
return groups
class Fingerprinter(object):
NOOP_FILTER = lambda prim: True
BASIC_FILTER = lambda prim: prim.USAGE_FREQUENCY != FrequencyType.NEGLIGIBLE and prim.USAGE_TYPE == UsageType.GENERAL
def __init__(self, oracle: ChosenPlaintextOracle):
self.oracle = oracle
@RUNTIME.report
def execute(self, initial_filter: FunctionType=BASIC_FILTER, min_input_len: int=1) -> Fingerprint:
sample = self.oracle.request(b'a'*min_input_len)
base_len = len(sample)
filtered = RUNTIME.search_primitives(initial_filter)
io_rel_analysis = self.oracle.test_io_relation(min_input_len)
io_relation = io_rel_analysis['io_relation']
block_size = io_rel_analysis['block_size']
max_val_analysis = IntegerAnalysis.analyze(self.oracle.test_max_input())
modifiers = {}
if max_val_analysis.n != -1:
if max_val_analysis.prime_name:
log.debug(f'Max input size is a well-known modulus: {max_val_analysis.prime_name}')
# Add modifiers for matching primitives
if not max_val_analysis.is_prime and not max_val_analysis.byte_aligned and max_val_analysis.is_uniform:
from samson.public_key.rsa import RSA
modifiers[RSA] = 1
log.debug('Max input size looks like RSA modulus')
elif max_val_analysis.is_prime and max_val_analysis.is_uniform:
from samson.protocols.dragonfly import Dragonfly
from samson.public_key.elgamal import ElGamal
# Process Diffie-Hellman-like primitives
dh_modifier = 1 + max_val_analysis.is_safe_prime + bool(max_val_analysis.prime_name)
modifiers[DiffieHellman] = dh_modifier
modifiers[Dragonfly] = dh_modifier
modifiers[ElGamal] = dh_modifier
log.debug('Max input size looks like Diffie-Hellman modulus')
matching = [match for match in filtered if block_size*8 in match.BLOCK_SIZE and match.IO_RELATION_TYPE == io_relation]
bc_modes = []
# Punish IV/nonce/AEAD primitives if we can prove the output doesn't contain their ephemeral/tag
# This is only really possible if the output is smaller than their ephemeral/tag
def calculate_min_size(size):
min_size = 0
typical_size = 0
sizes = size.sizes
if type(sizes) is int:
min_size += sizes
typical_size += sizes
else:
if size.size_type not in [SizeType.ARBITRARY, SizeType.DEPENDENT]:
min_size += sizes[0]
if size.typical:
typical_size += size.typical[0]
return min_size, typical_size
# If the primitive is a block cipher mode and its ephemeral/tag is DEPENDENT, we'll want to check
# against known block ciphers.
block_ciphers = [prim for prim in filtered if issubclass(prim, BlockCipher) and block_size*8 in prim.BLOCK_SIZE]
minimum_bc = min([calculate_min_size(block_cipher.BLOCK_SIZE)[0] for block_cipher in block_ciphers]) if block_ciphers else 0
for match in matching:
min_size = 0
typical_size = 0
all_sizes = []
if hasattr(match, 'EPHEMERAL') and not match.EPHEMERAL.ephemeral_type == EphemeralType.KEY:
all_sizes.append(match.EPHEMERAL.size)
if hasattr(match, 'AUTH_TAG_SIZE'):
all_sizes.append(match.AUTH_TAG_SIZE)
for size in all_sizes:
component_min, component_typical = calculate_min_size(size)
min_size += component_min
typical_size += component_typical
if issubclass(match, BlockCipherMode) and size.size_type == SizeType.DEPENDENT:
min_size += minimum_bc
for size in [min_size, typical_size]:
if base_len*8 < size:
if not match in modifiers:
modifiers[match] = 0
modifiers[match] -= 1
# Find possible block cipher modes. We exclude StreamingBlockCipherModes because they're handled
# by their block size above.
if any([issubclass(match, BlockCipher) for match in matching]):
from samson.block_ciphers.modes.ecb import ECB
log.debug('Block ciphers in candidates. Attempting to find possible block cipher modes')
bc_modes = [prim for prim in filtered if issubclass(prim, BlockCipherMode) and not issubclass(prim, StreamingBlockCipherMode)]
# Check for ECB
if self.oracle.test_stateless_blocks(block_size):
log.info('Stateless blocks detected')
bc_modes = [ECB]
else:
if ECB in bc_modes:
bc_modes.remove(ECB)
# Score matches higher if they're more explicit
scored_matches = {}
for match in matching:
bitsize = block_size*8
base_freq = match.USAGE_FREQUENCY.value + (modifiers[match] if match in modifiers else 0)
scored_matches[match] = base_freq
# If it matches a SINGLE value, that's significant
if bitsize == match.BLOCK_SIZE.sizes:
scored_matches[match] += FrequencyType.PROLIFIC.value
# If it's in a RANGE, it's a bit less significant
elif bitsize in match.BLOCK_SIZE.sizes:
scored_matches[match] += FrequencyType.NORMAL.value
# Add a modifier for being in 'typical'
if bitsize in match.BLOCK_SIZE.typical:
scored_matches[match] += 1
return Fingerprint(candidates=scored_matches, modes=bc_modes, max_input_analysis=max_val_analysis, io_relation=io_relation, block_size=block_size)
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/ace/fingerprinter.py
| 0.529263 | 0.172642 |
fingerprinter.py
|
pypi
|
from samson.utilities.bytes import Bytes
from samson.hashes.sha1 import SHA1
from samson.padding.oaep import MGF1
from samson.core.base_object import BaseObject
from types import FunctionType
class PSS(BaseObject):
"""
Probabilistic Signature Scheme used for RSA signatures
RFC8017 (https://tools.ietf.org/html/rfc8017)
"""
def __init__(self, modulus_len: int, mgf: FunctionType=MGF1, hash_obj: object=SHA1(), salt_len: int=8):
"""
Parameters:
modulus_len (int): Length of the RSA modulus, i.e. RSA bit strength.
mgf (func): Mask generation function. Takes in `seed` and `length` and returns bytes.
hash_obj (object): Instantiated object with compatible hash interface.
salt_len (int): Length of salt to generate if salt is not explicitly provided.
"""
self.modulus_len = modulus_len
self.mgf = mgf
self.hash_obj = hash_obj
self.salt_len = salt_len
# https://tools.ietf.org/html/rfc8017#section-9.1.1
def sign(self, plaintext: bytes, salt: bytes=None) -> Bytes:
"""
Pads and hashes the `plaintext`.
Parameters:
plaintext (bytes): Plaintext to sign.
salt (bytes): (Optional) Random salt.
Returns:
Bytes: Probabilistic signature.
"""
plaintext = Bytes.wrap(plaintext)
mHash = self.hash_obj.hash(plaintext)
salt = salt or Bytes.random(self.salt_len)
m_prime = b'\x00' * 8 + mHash + salt
H = self.hash_obj.hash(m_prime)
em_bits = self.modulus_len - 1
em_len = (em_bits + 7) // 8
ps_len = em_len - self.hash_obj.digest_size - self.salt_len - 2
if ps_len < 0:
raise ValueError("Plaintext is too long")
PS = Bytes(b'').zfill(ps_len)
DB = PS + b'\x01' + salt
db_mask = self.mgf(H, em_len - self.hash_obj.digest_size - 1)
masked_db = DB ^ db_mask
# Set the leftmost 8emLen - emBits bits of the leftmost octet in maskedDB to zero.
masked_db &= (2**(len(masked_db) * 8) - 1) >> ((8 * em_len) - em_bits)
return masked_db + H + b'\xbc'
# https://tools.ietf.org/html/rfc8017#section-9.1.2
def verify(self, plaintext: bytes, signature: bytes) -> bool:
"""
Verifies the `plaintext` against the `signature`.
Parameters:
plaintext (bytes): Plaintext to verify.
signature (bytes): Signature to verify against plaintext.
Returns:
bool: Whether or not the plaintext is verified.
"""
from samson.utilities.runtime import RUNTIME
plaintext = Bytes.wrap(plaintext)
signature = Bytes.wrap(signature).zfill((self.modulus_len + 7) // 8)
mHash = self.hash_obj.hash(plaintext)
em_bits = self.modulus_len - 1
em_len = (em_bits + 7) // 8
if em_len < (self.hash_obj.digest_size + self.salt_len + 2):
return False
if bytes([signature[-1]]) != b'\xbc':
return False
# Let maskedDB be the leftmost emLen - hLen - 1 octets of EM,
# and let H be the next hLen octets.
mask_len = em_len - self.hash_obj.digest_size - 1
masked_db = signature[:mask_len]
H = signature[mask_len:mask_len + self.hash_obj.digest_size]
# If the leftmost 8emLen - emBits bits of the leftmost octet in
# maskedDB are not all equal to zero, output "inconsistent" and
# stop.
left_mask = (2**(len(masked_db) * 8) - 1) >> ((8 * em_len) - em_bits)
if masked_db & left_mask != masked_db:
return False
db_mask = self.mgf(H, mask_len)
DB = masked_db ^ db_mask
DB &= left_mask
# If the emLen - hLen - sLen - 2 leftmost octets of DB are not
# zero or if the octet at position emLen - hLen - sLen - 1 (the
# leftmost position is "position 1") does not have hexadecimal
# value 0x01, output "inconsistent" and stop.
if DB[:em_len - self.hash_obj.digest_size - self.salt_len - 1].int() != 1:
return False
salt = DB[-self.salt_len:] if self.salt_len else b''
m_prime = b'\x00' * 8 + mHash + salt
h_prime = self.hash_obj.hash(m_prime)
return RUNTIME.compare_bytes(h_prime, H)
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/padding/pss.py
| 0.854703 | 0.259157 |
pss.py
|
pypi
|
from samson.utilities.bytes import Bytes
from samson.utilities.exceptions import InvalidPaddingException
from samson.core.base_object import BaseObject
import math
# https://tools.ietf.org/html/rfc8017#section-7.2.1
class PKCS1v15Padding(BaseObject):
"""
PCKS#1 v1.5 RSA padding
"""
def __init__(self, key_bit_length: int, block_type: int=2):
"""
Parameters:
key_bit_length (int): Length of the RSA modulus in bits.
"""
self.key_byte_length = math.ceil(key_bit_length / 8)
self.block_type = block_type
def pad(self, plaintext: bytes) -> Bytes:
"""
Pads the plaintext.
Parameters:
plaintext (bytes): Plaintext to pad.
Returns:
Bytes: Padded plaintext.
"""
block_type = bytes([self.block_type])
pad_len = self.key_byte_length - 3 - len(plaintext)
assert pad_len >= 8
if self.block_type == 0:
padding = Bytes(b'').zfill(pad_len)
elif self.block_type == 1:
padding = Bytes(b'\xff').stretch(pad_len)
elif self.block_type == 2:
padding = Bytes.random(pad_len) | Bytes(0x01).stretch(pad_len)
return b'\x00' + block_type + padding + b'\x00' + plaintext
def unpad(self, plaintext: bytes, allow_padding_oracle: bool=False) -> Bytes:
"""
Unpads the plaintext.
Parameters:
plaintext (bytes): Plaintext to unpad.
allow_padding_oracle (bool): Whether or not to explicitly create a padding oracle.
Returns:
Bytes: Unpadded plaintext.
"""
if allow_padding_oracle and (plaintext[:2] != b'\x00\x02' or len(plaintext) != self.key_byte_length):
raise InvalidPaddingException('Invalid padding ;)')
header_removed = plaintext[2:]
first_zero = header_removed.index(b'\x00')
data_idx = first_zero
if self.block_type == 0:
while not header_removed[data_idx + 1]:
data_idx += 1
return header_removed[data_idx + 1:]
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/padding/pkcs1v15_padding.py
| 0.750827 | 0.307865 |
pkcs1v15_padding.py
|
pypi
|
from samson.utilities.bytes import Bytes
from samson.hashes.sha1 import SHA1
from samson.ace.decorators import has_exploit
from samson.attacks.mangers_attack import MangersAttack
from samson.core.base_object import BaseObject
from types import FunctionType
def MGF1(seed: bytes, length: int, hash_obj: object=SHA1()) -> Bytes:
"""
Peforms the mask generation function v1 from RFC3447 B.2.1.
Parameters:
seed (bytes): Initial value.
length (int): Length of mask to produce.
Returns:
Bytes: Mask.
"""
mask = b''
for i in range((length + hash_obj.digest_size - 1) // hash_obj.digest_size):
mask += hash_obj.hash(seed + Bytes(i).zfill(4))
return mask[:length]
# https://www.ietf.org/rfc/rfc3447.txt
@has_exploit(MangersAttack)
class OAEP(BaseObject):
"""
Optimal Asymmetric Encryption Padding
Probabilistic Feistel Network proven to be semantically secure under chosen plaintext attack.
"""
def __init__(self, modulus_len: int, mgf: FunctionType=MGF1, hash_obj: object=SHA1(), label: bytes=b''):
"""
Parameters:
modulus_len (int): Length of the RSA modulus, i.e. RSA bit strength.
mgf (func): Mask generation function. Takes in `seed` and `length` and returns bytes.
hash_obj (object): Instantiated object with compatible hash interface.
label (bytes): (Optional) Arbitrary and application-specific 'label.'
"""
self.mgf = mgf
self.hash_obj = hash_obj
self.label = label
self.modulus_len = modulus_len
def pad(self, plaintext: bytes, seed: bytes=None) -> Bytes:
"""
Pads the `plaintext`.
Parameters:
plaintext (bytes): Plaintext to pad.
seed (bytes): (Optional) Random seed for the MGF.
Returns:
Bytes: Padded plaintext.
"""
plaintext = Bytes.wrap(plaintext)
k = (self.modulus_len + 7) // 8
# Step 1: Length checking
h_len = self.hash_obj.digest_size
m_len = len(plaintext)
ps_len = k - m_len - (2 * h_len) - 2
if ps_len < 0:
raise ValueError("Plaintext is too long")
# Step 2: EME-OAEP encoding
l_hash = self.hash_obj.hash(self.label)
ps = Bytes(b'').zfill(ps_len)
db = l_hash + ps + b'\x01' + plaintext
seed = seed or Bytes.random(h_len)
db_mask = self.mgf(seed, k - h_len - 1)
masked_db = db ^ db_mask
seed_mask = self.mgf(masked_db, h_len)
masked_seed = seed ^ seed_mask
return b'\x00' + masked_seed + masked_db
def unpad(self, plaintext: bytes, allow_mangers: bool=False, skip_label_check: bool=False) -> Bytes:
"""
Unpads the `plaintext`.
Parameters:
plaintext (bytes): Plaintext to pad.
allow_mangers (bool): Whether or not to explicitly help Manger's attack.
skip_label_check (bool): Whether or not to skip checking the label.
Returns:
Bytes: Unpadded plaintext.
"""
k = (self.modulus_len + 7) // 8
h_len = self.hash_obj.digest_size
plaintext = Bytes.wrap(plaintext).zfill(k)
if allow_mangers:
if plaintext[0] != 0:
raise ValueError("First byte is not zero! ;)")
masked_seed, masked_db = plaintext[1:(h_len + 1)], plaintext[(h_len + 1):]
seed_mask = self.mgf(masked_db, h_len)
seed = masked_seed ^ seed_mask
db_mask = self.mgf(seed, k - h_len - 1)
db = masked_db ^ db_mask
l_hash, m = db[:h_len], db[h_len + db[h_len:].index(b'\x01') + 1:]
if not skip_label_check and l_hash != self.hash_obj.hash(self.label):
raise ValueError("Label hashes do not match")
return m
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/padding/oaep.py
| 0.880386 | 0.334793 |
oaep.py
|
pypi
|
from samson.utilities.exceptions import SearchspaceExhaustedException
from samson.core.base_object import BaseObject
from samson.core.metadata import CrackingDifficulty
from types import FunctionType
from copy import deepcopy
def _gen_mask_op(mask):
return lambda n: n & mask
class LFG(BaseObject):
"""
Lagged Fibonacci generator
"""
CRACKING_DIFFICULTY = CrackingDifficulty.TRIVIAL
ADD_OP = lambda a, b: a + b
SUB_OP = lambda a, b: a - b
GEN_MASK_OP = _gen_mask_op
@staticmethod
def C_SHARP_MASK_OP(n):
if n == 2147483647:
return n-1
elif n < 0:
return n + 2147483647
else:
return n
def __init__(self, state: list, tap: int, feed: int, operation: FunctionType=ADD_OP, increment: bool=False, mask_op: FunctionType=_gen_mask_op(0xFFFFFFFFFFFFFFFF), length: int=None):
"""
Parameters:
state (list): Initial state.
tap (int): Initial tap position.
feed (int): Initial feed position.
operation (int): The operation the LFG performs. Function that takes in an integer and returns an integer.
increment (bool): Whether to increment (True) or decrement (False) the feed and tap.
mask_op (func): Mask operation to use for integer operations.
length (int): Length of internal state.
"""
self.state = deepcopy(state)
self.tap = tap
self.feed = feed
self.operation = operation
self.increment = increment
self.shift_mod = -1 + 2 * increment
self.mask_op = mask_op
self.length = length or len(state)
def generate(self) -> int:
"""
Generates the next pseudorandom output.
Returns:
int: Next pseudorandom output.
"""
self.tap = (self.tap + self.shift_mod) % self.length
self.feed = (self.feed + self.shift_mod) % self.length
x = self.mask_op(self.operation(self.state[self.feed], self.state[self.tap]))
self.state[self.feed] = x
return x
def reverse_clock(self) -> int:
"""
Runs the algorithm backwards.
Returns:
int: Previous pseudorandom output.
"""
x = self.mask_op(self.operation(self.state[self.feed], -self.state[self.tap]))
self.state[self.feed] = x
self.tap = (self.tap - self.shift_mod) % self.length
self.feed = (self.feed - self.shift_mod) % self.length
return self.state[self.feed]
def crack(self, outputs: list, num_outputs_to_predict: int=2):
"""
Cracks the full state of the LFG. NOTE: this function is NOT guaranteed to find the exact state. Instead, it finds an equivalent state.
Parameters:
outputs (list): Observed outputs.
num_outputs_to_predict (int): Number of outputs we reserve for prediction. Taking too many compared to the state length can cause issues (i.e. taking 2 when the state length is 3 will not work).
"""
assert len(outputs) > self.length
# We don't need all of the outputs (it can actually cause problems). We just have to synchronize at the end.
orig_len = len(outputs)
outputs = outputs[:self.length + num_outputs_to_predict]
init_state = outputs[:self.length][::self.shift_mod]
next_states = outputs[self.length:][::self.shift_mod]
next_state_len = len(next_states)
lfg = deepcopy(self)
lfg.state = init_state
for i in range(lfg.length):
guessed_feed = (lfg.feed + lfg.shift_mod * i) % lfg.length
guessed_tap = (lfg.tap + lfg.shift_mod * i) % lfg.length
simulated_states = [lfg.mask_op(lfg.operation(lfg.state[(guessed_feed - lfg.shift_mod * j) % lfg.length], lfg.state[(guessed_tap - lfg.shift_mod * j) % lfg.length])) for j in range(next_state_len)][::-lfg.shift_mod]
if simulated_states == next_states:
# We've found working tap/feed positions. Run the clock difference to synchronize states.
clock_difference = orig_len - len(outputs)
lfg.feed = (guessed_feed - lfg.shift_mod * next_state_len) % lfg.length
lfg.tap = (guessed_tap - lfg.shift_mod * next_state_len) % lfg.length
[lfg.generate() for _ in range(next_state_len + clock_difference)]
return lfg
raise SearchspaceExhaustedException('Unable to find correct tap and feed values.')
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/prngs/lfg.py
| 0.770939 | 0.305911 |
lfg.py
|
pypi
|
from samson.utilities.manipulation import left_rotate, right_rotate, unxorshift_left
from samson.prngs.xorshift import DEFAULT_SHFT_R
from samson.core.iterative_prng import IterativePRNG, CrackingDifficulty
MASK32 = 0xFFFFFFFF
MASK64 = 0xFFFFFFFFFFFFFFFF
class Xoshiro128PlusPlus(IterativePRNG):
"""
References:
http://prng.di.unimi.it/xoshiro128plusplus.c
"""
NATIVE_BITS = 32
STATE_SIZE = 4
CRACKING_DIFFICULTY = CrackingDifficulty.EXTREME
@staticmethod
def gen_func(sym_s0, sym_s1, sym_s2, sym_s3, SHFT_L=lambda x, n: (x << n) & MASK32, SHFT_R=DEFAULT_SHFT_R, RotateLeft=lambda x, n: left_rotate(x, n, bits=32)) -> (list, int):
"""
Internal function compatible with Python and symbolic execution.
"""
s0, s1, s2, s3 = [s & MASK32 for s in [sym_s0, sym_s1, sym_s2, sym_s3]]
result = RotateLeft(s0 + s3, 7) + s0
t = SHFT_L(s1, 9)
s2 ^= s0
s3 ^= s1
s1 ^= s2
s0 ^= s3
s2 ^= t
s3 = RotateLeft(s3, 11)
return [s0, s1, s2, s3], result & MASK32
def reverse_clock(self) -> int:
"""
Generates the previous pseudorandom output.
Returns:
int: Next pseudorandom output.
"""
s0s, s1s, s2t, s3r = self.state
for _ in range(2):
s3s = right_rotate(s3r, 11, 32)
s0 = s0s ^ s3s
s1t = s2t ^ s1s
s1 = unxorshift_left(s1t, 9, 32)
s3 = s3s ^ s1
t = s1t ^ s1
s2 = s2t ^ s0 ^ t
s0s, s1s, s2t, s3r = s0, s1, s2, s3
self.state = [s0, s1, s2, s3]
return self.generate()
class Xoshiro256PlusPlus(IterativePRNG):
"""
References:
http://prng.di.unimi.it/xoshiro256plusplus.c
"""
NATIVE_BITS = 64
STATE_SIZE = 4
CRACKING_DIFFICULTY = CrackingDifficulty.EXTREME
@staticmethod
def gen_func(sym_s0, sym_s1, sym_s2, sym_s3, SHFT_L=lambda x, n: (x << n) & MASK64, SHFT_R=DEFAULT_SHFT_R, RotateLeft=lambda x, n: left_rotate(x, n, bits=64)) -> (list, int):
"""
Internal function compatible with Python and symbolic execution.
"""
s0, s1, s2, s3 = [s & MASK64 for s in [sym_s0, sym_s1, sym_s2, sym_s3]]
result = RotateLeft(s0 + s3, 23) + s0
t = SHFT_L(s1, 17)
s2 ^= s0
s3 ^= s1
s1 ^= s2
s0 ^= s3
s2 ^= t
s3 = RotateLeft(s3, 45)
return [s0, s1, s2, s3], result & MASK64
def reverse_clock(self) -> int:
"""
Generates the previous pseudorandom output.
Returns:
int: Next pseudorandom output.
"""
s0s, s1s, s2t, s3r = self.state
for _ in range(2):
s3s = right_rotate(s3r, 45, 64)
s0 = s0s ^ s3s
s1t = s2t ^ s1s
s1 = unxorshift_left(s1t, 17, 64)
s3 = s3s ^ s1
t = s1t ^ s1
s2 = s2t ^ s0 ^ t
s0s, s1s, s2t, s3r = s0, s1, s2, s3
self.state = [s0, s1, s2, s3]
return self.generate()
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/prngs/xoshiro.py
| 0.703549 | 0.292532 |
xoshiro.py
|
pypi
|
from samson.prngs.xorshift import DEFAULT_SHFT_R, MASK32, MASK64
from samson.core.iterative_prng import IterativePRNG, CrackingDifficulty
# https://github.com/XMPPwocky/nodebeefcl/blob/master/beef.py
# https://github.com/v8/v8/blob/ceade6cf239e0773213d53d55c36b19231c820b5/src/js/math.js#L143
# https://v8.dev/blog/math-random <-- Looks to be wrong
# http://www.helsbreth.org/random/rng_mwc1616.html
class MWC1616(IterativePRNG):
"""
Multyply-with-carry 1616
"""
NATIVE_BITS = 32
STATE_SIZE = 2
MASK = MASK32
HALF_SIZE = 16
HALF_MASK = 0xFFFF
CRACKING_DIFFICULTY = CrackingDifficulty.EXPENSIVE
def __init__(self, seed: (int, int), a: int=18030, b: int=30903):
"""
Parameters:
seed ((int, int)): An integer or two-tuple of integers. If just an integer, it will be split into two.
a (int): Multiplier for the state's first item.
b (int): Multiplier for the state's second item.
"""
if type(seed) == int:
seed = ((seed >> self.HALF_SIZE) & self.HALF_MASK, seed & self.HALF_MASK)
super().__init__(seed)
self.a = a
self.b = b
def gen_func(self, sym_s0, sym_s1, SHFT_L=lambda x, n: (x << n) & MASK32, SHFT_R=DEFAULT_SHFT_R, RotateLeft=lambda x:x) -> (list, int):
"""
Internal function compatible with Python and symbolic execution.
"""
sym_s0 = (self.a * (sym_s0 & self.HALF_MASK) + SHFT_R(sym_s0, self.HALF_SIZE)) & self.MASK
sym_s1 = (self.b * (sym_s1 & self.HALF_MASK) + SHFT_R(sym_s1, self.HALF_SIZE)) & self.MASK
return (sym_s0, sym_s1), (SHFT_L(sym_s0, self.HALF_SIZE) + (sym_s1 & self.HALF_MASK)) & self.MASK
def reverse_clock(self) -> int:
"""
Runs the algorithm backwards.
Returns:
int: Previous pseudorandom output.
"""
sym_s0, sym_s1 = self.state
for _ in range(2):
s0_r, s0_q = divmod(sym_s0, self.a)
s1_r, s1_q = divmod(sym_s1, self.b)
s0 = (s0_q << self.HALF_SIZE) + s0_r
s1 = (s1_q << self.HALF_SIZE) + s1_r
sym_s0, sym_s1 = s0, s1
self.state = [sym_s0, sym_s1]
return self.generate()
class MWC(IterativePRNG):
"""
Multyply-with-carry 1616
"""
NATIVE_BITS = 64
STATE_SIZE = 2
MASK = MASK64
HALF_SIZE = 32
HALF_MASK = MASK32
CRACKING_DIFFICULTY = CrackingDifficulty.EXPENSIVE
def __init__(self, seed: ((int, int)), a: int=0xFFFFDA61):
"""
Parameters:
seed ((int, int)): An integer or two-tuple of integers. If just an integer, it will be split into two.
a (int): Multiplier for the state's first item.
"""
if type(seed) == int:
seed = ((seed >> self.HALF_SIZE) & self.HALF_MASK, seed & self.HALF_MASK)
super().__init__(seed)
self.a = a
def gen_func(self, sym_s0, sym_s1, SHFT_L=lambda x, n: (x << n) & MASK32, SHFT_R=DEFAULT_SHFT_R, RotateLeft=lambda x:x) -> (list, int):
"""
Internal function compatible with Python and symbolic execution.
"""
S, carry = sym_s0, sym_s1
state = (self.a*S + carry) & self.MASK
S, carry = state & self.HALF_MASK, state >> self.HALF_SIZE
return (S, carry), S
def reverse_clock(self) -> int:
"""
Runs the algorithm backwards.
Returns:
int: Previous pseudorandom output.
"""
S, carry = self.state
for _ in range(2):
state = (carry << self.HALF_SIZE) + S
S, carry = divmod(state, self.a)
self.state = [S, carry]
return self.generate()
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/prngs/mwc1616.py
| 0.78345 | 0.28892 |
mwc1616.py
|
pypi
|
from samson.core.base_object import BaseObject
from samson.core.metadata import CrackingDifficulty
from samson.utilities.bytes import Bytes
w, n, m, r = (32, 624, 397, 31)
MAGIC = 0x9908b0df
f = 1812433253
u, d = (11, 0xFFFFFFFF)
s, b = (7, 0x9D2C5680)
t, c = (15, 0xEFC60000)
l = 18
def asint32(integer):
return integer & d
def temper(y):
y ^= (y >> u)
y ^= (y << s) & b
y ^= (y << t) & c
y ^= (y >> l)
return y
# We don't have to include a constant since 32-bit Mersenne Twister doesn't
# use non-idempotent constants on its right shifts.
def untemper_right(y, bits):
# Create a 32-bit mask with `bits` 1s at the beginning.
# We'll shift this over the iterations to invert the temper.
mask = (1 << bits) - 1 << 32 - bits
shift_mod = 0
while mask > 0:
y ^= shift_mod
# Get next `bits` bits of y
# Ex: bits = 3, mask = '00011100000000000'
# '100_010_00100100001' -> '000000_010_00000000'
shift_mod = (y & mask) >> bits
# Move mask right `bits` to select next bits to shift
# Ex: bits = 3
# 11100000000000000 -> 00011100000000000
mask >>= bits
return y
def untemper_left(y, bits, constant):
int32_mask = 0xFFFFFFFF
mask = (1 << bits) - 1
shift_mod = 0
while (mask & int32_mask) > 0:
y ^= shift_mod & constant
# Get next `bits` bits of y
shift_mod = (y & mask) << bits
# Move mask right `bits` to select next bits to shift
mask <<= bits
return y
def untemper(y):
y = untemper_right(y, l)
y = untemper_left(y, t, c)
y = untemper_left(y, s, b)
y = untemper_right(y, u)
return y & d
# Implementation of MT19937
class MT19937(BaseObject):
"""
Mersenne Twister 19937
References:
https://jazzy.id.au/2010/09/22/cracking_random_number_generators_part_3.html
"""
CRACKING_DIFFICULTY = CrackingDifficulty.TRIVIAL
def __init__(self, seed: int=0):
"""
Parameters:
seed (int): Initial value.
"""
self.state = [0] * n
self.seed = seed
# Seed the algo
self.index = n
self.state[0] = seed
for i in range(1, n):
self.state[i] = asint32(f * (self.state[i - 1] ^ self.state[i - 1] >> (w - 2)) + i)
def __reprdir__(self):
return ['seed', 'index', 'state']
def twist(self):
"""
Called internally. Performs the `twist` operation of the Mersenne Twister.
"""
for i in range(n):
y = asint32((self.state[i] & 0x80000000) + (self.state[(i + 1) % n] & 0x7fffffff))
self.state[i] = self.state[(i + m) % n] ^ y >> 1
if y & 1 == 1:
self.state[i] ^= MAGIC
self.index = 0
def generate(self) -> int:
"""
Generates the next pseudorandom output.
Returns:
int: Next pseudorandom output.
"""
if self.index >= n:
self.twist()
y = self.state[self.index]
y = temper(y)
self.index += 1
return asint32(y)
def untwist(self):
for i in reversed(range(n)):
tmp = self.state[i]
tmp ^= self.state[(i + m) % n]
if (tmp & 0x80000000) == 0x80000000:
tmp ^= MAGIC
result = (tmp << 1) & 0x80000000
tmp = self.state[(i - 1 + n) % n]
tmp ^= self.state[(i - 1 + m) % n]
if (tmp & 0x80000000) == 0x80000000:
tmp ^= MAGIC
result |= 1
result |= (tmp << 1) & 0x7fffffff
self.state[i] = result
self.index = n-1
def reverse_clock(self) -> int:
"""
Generates the previous pseudorandom output.
Returns:
int: Next pseudorandom output.
"""
self.index -= 1
if self.index < 0:
self.untwist()
y = self.state[self.index]
y = temper(y)
return asint32(y)
@staticmethod
def crack(observed_outputs: list) -> 'MT19937':
"""
Given 624 observed, consecutive outputs, cracks the internal state of the original and returns a replica.
Parameters:
observed_outputs (list): List of consecutive inputs (in order, obviously).
Returns:
MT19937: A replica of the original MT19937.
"""
if len(observed_outputs) < n:
raise ValueError("`observed_outputs` must contain at least 624 consecutive outputs.")
cloned = MT19937(0)
cloned.state = [untemper(output) for output in observed_outputs][-n:]
return cloned
@staticmethod
def init_by_array(init_key: list) -> 'MT19937':
prng = MT19937(19650218)
mt = prng.state
key_length = len(init_key)
i, j = 1, 0
for k in reversed(range(max(key_length, n))):
mt[i] = ((mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525)) + init_key[j] + j) % 2**32
i += 1
j += 1
if i >= n:
mt[0] = mt[n-1]
i = 1
if j >= key_length:
j = 0
for k in reversed(range(n-1)):
mt[i] = ((mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941)) - i) % 2**32
i += 1
if i >= n:
mt[0] = mt[n-1]
i = 1
mt[0] = 0x80000000
prng.state = mt
return prng
@staticmethod
def python_seed(seed: int) -> 'MT19937':
return MT19937.init_by_array([b.change_byteorder().int() for b in Bytes(seed, 'little').pad_congruent_left(4).chunk(4)])
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/prngs/mt19937.py
| 0.744563 | 0.401219 |
mt19937.py
|
pypi
|
from samson.math.algebra.curves.weierstrass_curve import WeierstrassCurve, WeierstrassPoint
from samson.utilities.bytes import Bytes
from samson.math.general import mod_inv
from samson.utilities.runtime import RUNTIME
from samson.core.base_object import BaseObject
import random
class DualEC(BaseObject):
"""
Implementation of the NSA's backdoored DRBG.
"""
def __init__(self, P: WeierstrassPoint, Q: WeierstrassPoint, seed: int):
"""
Parameters:
P (WeierstrassPoint): Elliptical curve point `P`.
Q (WeierstrassPoint): Elliptical curve point `Q`.
seed (int): Initial value.
"""
self.P = P
self.Q = Q
self.t = seed
self.r = None
def generate(self) -> Bytes:
"""
Generates the next pseudorandom output.
Returns:
int: Next pseudorandom output.
"""
s = int((self.t * self.P).x)
self.t = s
self.r = int((s * self.Q).x)
return Bytes(int.to_bytes(self.r, 32, 'big')).zfill(32)[2:]
@staticmethod
def generate_backdoor(curve: WeierstrassCurve) -> (WeierstrassPoint, WeierstrassPoint, int):
"""
Generates backdoored parameters.
Parameters:
curve (WeierstrassCurve): Curve to use.
Returns:
(WeierstrassPoint, WeierstrassPoint, int): Result formatted as (P, backdoored Q, backdoor d)
"""
P = curve.G
d = random.randint(2, curve.order())
e = mod_inv(d, curve.order())
Q = e * P
return P, Q, d
@classmethod
@RUNTIME.report
def derive_from_backdoor(cls: object, P: WeierstrassPoint, Q: WeierstrassPoint, d: int, observed_out: bytes) -> list:
"""
Recovers the internal state of a Dual EC generator and builds a replica.
Parameters:
P (WeierstrassPoint): Elliptical curve point `P`.
Q (WeierstrassPoint): Elliptical curve point `Q`.
d (int): Backdoor that relates Q to P.
observed_out (bytes): Observed output from the compromised Dual EC generator.
Returns:
list: List of possible internal states.
"""
assert len(observed_out) >= 30
curve = P.curve
r1 = observed_out[:30]
r2 = observed_out[30:]
possible_states = []
Q_cache = Q.cache_mul(curve.cardinality().bit_length())
for i in RUNTIME.report_progress(range(2**16), desc='Statespace searched', unit='states'):
test_r1 = int.to_bytes(i, 2, 'big') + r1
test_x = int.from_bytes(test_r1, 'big')
try:
R = curve(test_x)
dR = d * R
test_r2 = Q_cache * int(dR.x)
if int.to_bytes(int(test_r2.x), 32, 'big')[2:2 + len(r2)] == r2:
possible_states.append(DualEC(P, Q, int(dR.x)))
except AssertionError:
pass
return possible_states
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/prngs/dual_ec.py
| 0.882656 | 0.418667 |
dual_ec.py
|
pypi
|
from samson.core.iterative_prng import IterativePRNG, CrackingDifficulty
from samson.core.base_object import BaseObject
from samson.utilities.manipulation import unxorshift_left, unxorshift_right
from samson.utilities.exceptions import NoSolutionException
from samson.math.algebra.rings.integer_ring import ZZ
# https://en.wikipedia.org/wiki/Xorshift
MASK32 = 0xFFFFFFFF
MASK58 = 0x3FFFFFFFFFFFFFF
MASK64 = 0xFFFFFFFFFFFFFFFF
DEFAULT_SHFT_R = lambda x, n: x >> n
class Xorshift32(IterativePRNG):
NATIVE_BITS = 32
STATE_SIZE = 1
@staticmethod
def gen_func(sym_s0, SHFT_L=lambda x, n: (x << n) & MASK32, SHFT_R=DEFAULT_SHFT_R, RotateLeft=lambda x:x) -> (list, int):
"""
Internal function compatible with Python and symbolic execution.
"""
x = sym_s0
x ^= SHFT_L(x, 13)
x ^= SHFT_R(x, 17)
x ^= SHFT_L(x, 5)
sym_s0 = x
return [sym_s0], sym_s0
def reverse_clock(self) -> int:
"""
Runs the algorithm backwards.
Returns:
int: Previous pseudorandom output.
"""
x = self.state[0]
x = unxorshift_left(x, 5, self.NATIVE_BITS)
x = unxorshift_right(x, 17, self.NATIVE_BITS)
x = unxorshift_left(x, 13, self.NATIVE_BITS)
self.state = [x]
return x
class Xorshift64(IterativePRNG):
NATIVE_BITS = 64
STATE_SIZE = 1
@staticmethod
def gen_func(sym_s0, SHFT_L=lambda x, n: (x << n) & MASK64, SHFT_R=DEFAULT_SHFT_R, RotateLeft=lambda x:x) -> (list, int):
"""
Internal function compatible with Python and symbolic execution.
"""
x = sym_s0
x ^= SHFT_L(x, 13)
x ^= SHFT_R(x, 7)
x ^= SHFT_L(x, 17)
sym_s0 = x
return [sym_s0], sym_s0
def reverse_clock(self) -> int:
"""
Runs the algorithm backwards.
Returns:
int: Previous pseudorandom output.
"""
x = self.state[0]
x = unxorshift_left(x, 17, self.NATIVE_BITS)
x = unxorshift_right(x, 7, self.NATIVE_BITS)
x = unxorshift_left(x, 13, self.NATIVE_BITS)
self.state = [x]
return x
class Xorshift128(IterativePRNG):
NATIVE_BITS = 64
STATE_SIZE = 4
@staticmethod
def gen_func(sym_s0, sym_s1, sym_s2, sym_s3, SHFT_L=lambda x, n: (x << n) & MASK64, SHFT_R=DEFAULT_SHFT_R, RotateLeft=lambda x:x) -> (list, int):
"""
Internal function compatible with Python and symbolic execution.
"""
s = sym_s0
t = sym_s3
t ^= SHFT_L(t, 11)
t ^= SHFT_R(t, 8)
sym_s3 = sym_s2
sym_s2 = sym_s1
sym_s1 = sym_s0
t ^= SHFT_R(s, 19)
t ^= s
t &= MASK64
return [t, sym_s1, sym_s2, sym_s3], t
def reverse_clock(self) -> int:
"""
Runs the algorithm backwards.
Returns:
int: Previous pseudorandom output.
"""
t, s1, s2, s3 = self.state
t ^= s1 ^ DEFAULT_SHFT_R(s1, 19)
s0, s1, s2 = s1, s2, s3
t = unxorshift_right(t, 8, self.NATIVE_BITS)
t = unxorshift_left(t, 11, self.NATIVE_BITS)
self.state = [s0, s1, s2, t]
return s0
class Xorshift116Plus(IterativePRNG):
NATIVE_BITS = 58
STATE_SIZE = 2
@staticmethod
def gen_func(sym_s0, sym_s1, SHFT_L=lambda x, n: (x << n) & MASK58, SHFT_R=DEFAULT_SHFT_R, RotateLeft=lambda x:x) -> (list, int):
"""
Internal function compatible with Python and symbolic execution.
"""
s1, s0 = sym_s0, sym_s1
s1 ^= SHFT_L(s1, 24)
s1 ^= s0 ^ SHFT_R(s1, 11) ^ SHFT_R(s0, 41)
return [s0, s1], (s1 + s0) & MASK58
def reverse_clock(self) -> int:
"""
Runs the algorithm backwards.
Returns:
int: Previous pseudorandom output.
"""
s0, s1 = self.state
s1 ^= s0 ^ DEFAULT_SHFT_R(s0, 41)
s1 = unxorshift_right(s1, 11, self.NATIVE_BITS)
s1 = unxorshift_left(s1, 24, self.NATIVE_BITS)
self.state = [s0, s1]
return (s1 + s0) & MASK58
# Reference: https://github.com/TACIXAT/XorShift128Plus/blob/master/xs128p.py
class Xorshift128Plus(IterativePRNG):
NATIVE_BITS = 64
STATE_SIZE = 2
@staticmethod
def gen_func(sym_s0, sym_s1, SHFT_L=lambda x, n: (x << n) & MASK64, SHFT_R=DEFAULT_SHFT_R, RotateLeft=lambda x:x) -> (list, int):
"""
Internal function compatible with Python and symbolic execution.
"""
s1 = sym_s0
s0 = sym_s1
s1 ^= SHFT_L(s1, 23)
s1 ^= SHFT_R(s1, 17)
s1 ^= s0
s1 ^= SHFT_R(s0, 26)
sym_s0 = sym_s1
sym_s1 = s1
calc = (sym_s0 + sym_s1)
return [sym_s0, sym_s1], calc & MASK64
def reverse_clock(self) -> int:
"""
Runs the algorithm backwards.
Returns:
int: Previous pseudorandom output.
"""
s0, s1 = self.state
prev_state1 = s0
prev_state0 = s1 ^ (s0 >> 26)
prev_state0 = prev_state0 ^ s0
prev_state0 = unxorshift_right(prev_state0, 17, self.NATIVE_BITS)
prev_state0 = unxorshift_right(prev_state0, 23, self.NATIVE_BITS)
self.state = [prev_state0, prev_state1]
return sum(self.state) & MASK64
class Xorshift1024Star(BaseObject):
NATIVE_BITS = 64
STATE_SIZE = 16
CRACKING_DIFFICULTY = CrackingDifficulty.TRIVIAL
def __init__(self, seed: list, p: int=0):
"""
Parameters:
seed (list): Initial value.
p (int): Initial array pointer.
"""
self.state = [p, *seed]
def generate(self) -> int:
"""
Generates the next pseudorandom output.
Returns:
int: Next pseudorandom output.
"""
p = self.state[0]
s = self.state[1:]
s0 = s[p]
p = (p + 1) & 15
s1 = s[p]
s1 ^= (s1 << 31) & MASK64
s[p] = s1 ^ s0 ^ (s1 >> 11) ^ (s0 >> 30)
self.state = [p, *s]
return (s[p] * 1181783497276652981) & MASK64
def reverse_clock(self) -> int:
"""
Runs the algorithm backwards.
Returns:
int: Previous pseudorandom output.
"""
p = self.state[0]
s = self.state[1:]
p_1 = (p-1) & 15
s0 = s[p_1]
s1 = s[p] ^ s0 ^ (s0 >> 30)
s1 = unxorshift_right(s1, 11, self.NATIVE_BITS)
s1 = unxorshift_left(s1, 31, self.NATIVE_BITS)
s[p] = s1
self.state = [p_1, *s]
return (s0 * 1181783497276652981) & MASK64
def crack(self, outputs: list):
if len(outputs) < 17:
raise ValueError('Not enough samples')
samples = outputs[:16]
next_outs = outputs[16:]
R = ZZ/ZZ(2**64)
inv_a = ~R(1181783497276652981)
state = [int(R(o)*inv_a) for o in samples]
# Search for the correct offset
for offset in range(16):
prng = Xorshift1024Star(state[offset:] + state[:offset])
if [prng.generate() for _ in range(len(next_outs))] == next_outs:
return prng
raise NoSolutionException('No solution for samples')
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/prngs/xorshift.py
| 0.721449 | 0.390999 |
xorshift.py
|
pypi
|
from samson.utilities.bitstring import Bitstring
from samson.core.base_object import BaseObject
class BitslicedFLFSR(BaseObject):
"""
An implementation of an FLFSR using an internal bitstring rather than an integer.
"""
def __init__(self, length: int, clock_bit: int, taps: list, seed: int=0):
"""
Parameters:
length (int): Length of the internal, bitstring state.
clock_bit (int): Bit considered to be the 'clock' bit.
taps (list): Positional taps used to determine the next bit.
seed (int): Inital state represented as an integer.
"""
self.state = bin(seed)[2:].zfill(length)
self.length = length
self.clock_bit = clock_bit
self.taps = taps
def mix_state(self, in_val: bytes, size: int):
"""
Mixes state into the FLSFR by clocking in each bit.
Parameters:
in_val (bytes): Bytes-like value to clock in.
size (int): Size for the bitstring to be padded to.
"""
bit_val = Bitstring.wrap(in_val).zfill(size)
for bit in str(bit_val)[::-1]:
self.clock(int(bit))
def clock(self, bit: int=0):
"""
Clocks the FLSFR with an optional input value.
Parameters:
bit (int): (Optional) Value to XOR'd in with the next bit.
"""
for tap in self.taps:
position = self.length - tap - 1
bit ^= int(self.state[position])
self.state += '0'
self.state = self.state[1:]
self.state = (self.state[:self.length - 1] + str(bit))
def value(self) -> int:
"""
Retrives the current value in state[0].
Returns:
int: Current value.
"""
return int(self.state[0])
def clock_value(self) -> int:
"""
Retrives the value in state[clock_bit].
Returns:
int: Clock value.
"""
return int(self.state[self.clock_bit])
def generate(self) -> int:
"""
Calls self.clock(). Here for interface uniformity.
Returns:
int: Current value.
"""
self.clock()
return self.value()
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/prngs/bitsliced_flfsr.py
| 0.847179 | 0.426859 |
bitsliced_flfsr.py
|
pypi
|
from samson.math.general import gcd, mod_inv, is_power_of_two, is_prime, is_primitive_root
from samson.math.factorization.general import factor as factorint
from samson.math.matrix import Matrix
from samson.utilities.exceptions import SearchspaceExhaustedException
from samson.utilities.runtime import RUNTIME
from samson.core.base_object import BaseObject
from samson.core.metadata import CrackingDifficulty
import functools
class LCG(BaseObject):
"""
Linear congruential generator of the form `(a*X + c) mod m`.
"""
CRACKING_DIFFICULTY = CrackingDifficulty.TRIVIAL
def __init__(self, X: int, a: int, c: int, m: int, trunc: int=0):
"""
Parameters:
X (int): Initial state.
a (int): Multiplier.
c (int): Increment.
m (int): Modulus.
trunc (int): Number of bits to truncate on output
"""
self.a = a
self.c = c
self.m = m
self.trunc = trunc
self.X = X
def __reprdir__(self):
return ['X', 'a', 'c', 'm', 'trunc']
def generate(self) -> int:
"""
Generates the next pseudorandom output.
Returns:
int: Next pseudorandom output.
"""
self.X = (self.a * self.X + self.c) % self.m
return self.X >> self.trunc
def reverse_clock(self) -> int:
"""
Generates the previous pseudorandom output.
Returns:
int: Next pseudorandom output.
"""
self.X = (mod_inv(self.a, self.m) * (self.X - self.c)) % self.m
return self.X >> self.trunc
def check_full_period(self) -> bool:
"""
Checks whether the LCG will achieve a full period with its current parameters.
Returns:
bool: Whether or not it will acheive a full period.
References:
https://en.wikipedia.org/wiki/Linear_congruential_generator#Period_length
"""
# Technically, this achieves m-1
if is_prime(self.m) and self.c == 0 and is_primitive_root(self.a, self.m):
return True
# Maximially m/4
elif is_power_of_two(self.m) and self.c == 0:
return False
else:
# 1. m and c are relatively prime
relatively_prime = gcd(self.m, self.c) == 1
# 2. a-1 is divisible by all prime factors of m
factors = [factor for factor in factorint(self.m)]
divisible_by_all_factors = all([((self.a - 1) % factor) == 0 for factor in factors])
# 3. a-1 is divisible by 4 if m is divisible by 4
divisible_by_four = True
if self.m % 4 == 0:
divisible_by_four = (self.a - 1) % 4 == 0
return relatively_prime and divisible_by_all_factors and divisible_by_four
def __getattribute__(self, name):
from functools import partial
if name == "crack":
if self.trunc:
return partial(LCG.crack_truncated, outputs_to_predict=None, multiplier=self.a, increment=self.c, modulus=self.m, trunc_amount=self.trunc)
else:
return partial(LCG.crack, multiplier=self.a, increment=self.c, modulus=self.m)
else:
return object.__getattribute__(self, name)
@staticmethod
def crack(states: list, multiplier: int=None, increment: int=None, modulus: int=None, sanity_check: bool=True):
"""
Given a few full states (probably under ten) and any (or even none) of the parameters of an LCG, returns a replica LCG.
Parameters:
states (list): List of full-state outputs (in order).
multiplier (int): (Optional) The LCG's multiplier.
increment (int): (Optional) The LCG's increment.
modulus (int): (Optional) The LCG's modulus.
sanity_check (bool): Whether to tests the generated LCG against the provided states.
Returns:
LCG: Replica LCG that predicts all future outputs of the original.
References:
https://tailcall.net/blog/cracking-randomness-lcgs/
"""
if not modulus:
diffs = [state1 - state0 for state0, state1 in zip(states, states[1:])]
congruences = [t2*t0 - t1*t1 for t0, t1, t2 in zip(diffs, diffs[1:], diffs[2:])]
modulus = abs(functools.reduce(gcd, congruences))
if not multiplier:
multiplier = (states[2] - states[1]) * mod_inv(states[1] - states[0], modulus) % modulus
if not increment:
increment = (states[1] - states[0] * multiplier) % modulus
# Sanity test
lcg = LCG(states[0], multiplier, increment, modulus)
num_tests = min(3, len(states) - 1)
if sanity_check and [lcg.generate() for _ in range(num_tests)] != states[1:1 + num_tests]:
raise RuntimeError("Generated LCG does not match 'states'. Are you sure this came from an untruncated LCG?")
return LCG(states[-1], multiplier, increment, modulus)
@classmethod
@RUNTIME.report
def crack_truncated(cls: object, outputs: list, outputs_to_predict: list, multiplier: int, increment: int, modulus: int, trunc_amount: int) -> 'LCG':
"""
Given a decent number of truncated states (about 200 when there's only 3-bit outputs), returns a replica LCG.
Parameters:
outputs (list): List of truncated-state outputs (in order).
outputs_to_predict (list): Next few outputs to compare against. Accuracy/number of samples trade-off.
multiplier (int): The LCG's multiplier.
increment (int): The LCG's increment.
modulus (int): The LCG's modulus.
Returns:
LCG: Replica LCG that predicts all future outputs of the original.
References:
https://github.com/mariuslp/PCG_attack
"Reconstructing Truncated Integer Variables Satisfying Linear Congruences" (https://www.math.cmu.edu/~af1p/Texfiles/RECONTRUNC.pdf)
"""
if not outputs_to_predict:
outputs_to_predict = outputs[-2:]
outputs = outputs[:-2]
# Trivial case
if increment == 0:
computed_seed = LCG.solve_tlcg(outputs + outputs_to_predict, multiplier, modulus, trunc_amount)
# Here we take the second to last seed since our implementation edits the state BEFORE it returns
return LCG((multiplier * computed_seed[-2]) % modulus, multiplier, increment, modulus, trunc=trunc_amount)
else:
diffs = [o2 - o1 for o1, o2 in zip(outputs, outputs[1:])]
seed_diffs = LCG.solve_tlcg(diffs, multiplier, modulus, trunc_amount)
seed_diffs = [int(seed_diff) % modulus for row in seed_diffs for seed_diff in row]
# Bruteforce low bits
for z in RUNTIME.report_progress(range(2 ** trunc_amount), desc='Seedspace searched', unit='seeds'):
x_0 = (outputs[0] << trunc_amount) + z
x_1 = (seed_diffs[0] + x_0) % modulus
computed_c = (x_1 - multiplier * x_0) % modulus
computed_x_2 = (multiplier * x_1 + computed_c) % modulus
actual_x_2 = (seed_diffs[1] + x_1) % modulus
if computed_x_2 == actual_x_2:
computed_seeds = [x_0]
for diff in seed_diffs:
computed_seeds.append((diff + computed_seeds[-1]) % modulus)
# It's possible to find a spectrum of nearly-equivalent LCGs.
# The accuracy of `predicted_lcg` is dependent on the size of `outputs_to_predict` and the
# parameters of the LCG.
predicted_seed = (multiplier * computed_seeds[-2] + computed_c) % modulus
predicted_lcg = LCG(X=int(predicted_seed), a=multiplier, c=int(computed_c), m=modulus, trunc=trunc_amount)
if [predicted_lcg.generate() for _ in range(len(outputs_to_predict))] == outputs_to_predict:
return predicted_lcg
raise SearchspaceExhaustedException('Seedspace exhausted')
@staticmethod
def solve_tlcg(outputs: list, multiplier: int, modulus: int, trunc_amount: int) -> Matrix:
"""
Used internally by `crack_truncated`. Uses the LLL algorithm to find seed differentials.
Parameters:
outputs (list): List of truncated-state outputs (in order).
multiplier (int): The LCG's multiplier.
increment (int): The LCG's increment.
modulus (int): The LCG's modulus.
Returns:
Matrix: Seed differentials.
"""
from samson.math.all import QQ
# Initialize matrix `L`
l_matrix = [[0 for _ in range(len(outputs))] for _ in range(len(outputs))]
l_matrix[0][0] = modulus
for i in range(1, len(outputs)):
l_matrix[i][0] = multiplier ** i
l_matrix[i][i] = -1
l_matrix = Matrix(l_matrix)
reduced_basis = l_matrix.LLL()
# Construct and reduce
y = Matrix([[2**trunc_amount * x % modulus for x in outputs]], QQ).T
reduced_outputs = reduced_basis * y
# Solve system
c_prime = Matrix([[(round(float(x[0] / modulus)) * modulus) - x[0] for x in reduced_outputs]]).T
z = reduced_basis.LUsolve(c_prime)
return y + z
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/prngs/lcg.py
| 0.866444 | 0.341267 |
lcg.py
|
pypi
|
from samson.utilities.manipulation import left_rotate, right_rotate
from samson.prngs.xorshift import DEFAULT_SHFT_R
from samson.core.iterative_prng import IterativePRNG
MASK58 = 0x3FFFFFFFFFFFFFF
MASK64 = 0xFFFFFFFFFFFFFFFF
class Xoroshiro116Plus(IterativePRNG):
NATIVE_BITS = 58
STATE_SIZE = 2
@staticmethod
def gen_func(sym_s0, sym_s1, SHFT_L=lambda x, n: (x << n) & MASK58, SHFT_R=DEFAULT_SHFT_R, RotateLeft=lambda x, n: left_rotate(x, n, bits=58)) -> (list, int):
"""
Internal function compatible with Python and symbolic execution.
"""
s0, s1 = sym_s0 & MASK58, sym_s1 & MASK58
result = (s0 + s1) & MASK58
s1 ^= s0
sym_s0 = RotateLeft(s0, 24) ^ s1 ^ SHFT_L(s1, 2)
sym_s1 = RotateLeft(s1, 35)
return [sym_s0, sym_s1], result
def reverse_clock(self) -> int:
"""
Generates the previous pseudorandom output.
Returns:
int: Next pseudorandom output.
"""
sym_s0, sym_s1 = self.state
for _ in range(2):
s1 = right_rotate(sym_s1, 35, bits=self.NATIVE_BITS)
s0 = sym_s0 ^ s1 ^ ((s1 << 2) & MASK58)
s0 = right_rotate(s0, 24, bits=self.NATIVE_BITS)
s1 ^= s0
sym_s0, sym_s1 = s0, s1
self.state = [sym_s0, sym_s1]
return self.generate()
class Xoroshiro128Plus(IterativePRNG):
NATIVE_BITS = 64
STATE_SIZE = 2
@staticmethod
def gen_func(sym_s0, sym_s1, SHFT_L=lambda x, n: (x << n) & MASK64, SHFT_R=DEFAULT_SHFT_R, RotateLeft=lambda x, n: left_rotate(x, n, bits=64)) -> (list, int):
"""
Internal function compatible with Python and symbolic execution.
"""
s0, s1 = sym_s0, sym_s1
result = (s0 + s1) & MASK64
s1 ^= s0
sym_s0 = RotateLeft(s0, 24) ^ s1 ^ SHFT_L(s1, 16)
sym_s1 = RotateLeft(s1, 37)
return [sym_s0, sym_s1], result
def reverse_clock(self) -> int:
"""
Generates the previous pseudorandom output.
Returns:
int: Next pseudorandom output.
"""
sym_s0, sym_s1 = self.state
for _ in range(2):
s1 = right_rotate(sym_s1, 37, bits=self.NATIVE_BITS)
s0 = sym_s0 ^ s1 ^ ((s1 << 16) & MASK64)
s0 = right_rotate(s0, 24, bits=self.NATIVE_BITS)
s1 ^= s0
sym_s0, sym_s1 = s0, s1
self.state = [sym_s0, sym_s1]
return self.generate()
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/prngs/xoroshiro.py
| 0.578567 | 0.276532 |
xoroshiro.py
|
pypi
|
from samson.math.polynomial import Polynomial
from samson.math.general import berlekamp_massey
from samson.math.general import poly_to_int
from samson.core.base_object import BaseObject
from samson.core.metadata import CrackingDifficulty
class GLFSR(BaseObject):
"""
Galois linear-feedback shift register.
"""
CRACKING_DIFFICULTY = CrackingDifficulty.TRIVIAL
def __init__(self, seed: int, polynomial: Polynomial):
"""
Parameters:
seed (int): Initial value.
polynomial (Polynomial): Either a `Polynomial` or an integer that represents the polynomal.
"""
self.state = seed
if type(polynomial) is Polynomial:
polynomial = poly_to_int(polynomial)
self.polynomial = polynomial
self.mask = 1
self.wrap_around_mask = 2 ** polynomial.bit_length() - 1
self.state &= self.wrap_around_mask
poly_mask = polynomial
while poly_mask:
if poly_mask & self.mask:
poly_mask ^= self.mask
if not poly_mask:
break
self.mask <<= 1
def clock(self):
"""
Generates the next pseudorandom output.
Returns:
int: Next pseudorandom output.
"""
self.state <<= 1
self.state &= self.wrap_around_mask
if self.state & self.mask:
self.state ^= self.polynomial
return 1
else:
return 0
def generate(self) -> int:
"""
Calls self.clock(). Here for interface uniformity
Returns:
int: Next pseudorandom output.
"""
return self.clock()
def reverse_clock(self, output: int):
"""
Clocks the state in reverse given the previous output.
Parameters:
output (int): Previous output.
"""
for item in output:
if item:
self.state ^= self.polynomial
self.state >>=1
self.state &= self.wrap_around_mask
@staticmethod
def crack(outputs: list):
"""
Given a list of outputs, creates a GLFSR that generates the same sequence.
Parameters:
outputs (list): A list of outputs from the GLFSR (in order).
Returns:
GLFSR: GLFSR that generates the same sequence.
"""
# Find minimum polynomial that represents the output
poly = berlekamp_massey(outputs)
# Create new LFSR and clock in reverse
lfsr = GLFSR(0, poly)
lfsr.reverse_clock(outputs[::-1])
# Clock forward to synchronize with output
[(lfsr.clock(), lfsr.state) for i in range(len(outputs))]
return lfsr
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/prngs/glfsr.py
| 0.887571 | 0.413359 |
glfsr.py
|
pypi
|
from samson.auxiliary.console_colors import ConsoleColors, color_format
from types import FunctionType
from pygments.styles.monokai import MonokaiStyle
from pygments.lexers import Python3Lexer
from pygments.formatters import TerminalTrueColorFormatter
from pygments import highlight
import shutil
import re
UNDEFINED_PARAM_RE = re.compile(r'`[A-Za-z0-9() _+-]+`')
TERM_SIZE = shutil.get_terminal_size((80, 20))
LEXER = Python3Lexer()
FORMATTER = TerminalTrueColorFormatter(style=MonokaiStyle)
NEWLINE = '\n'
TAB = '\t'
QUOTE = '\"'
def type_format(cls):
return color_format(ConsoleColors.GREEN, cls)
def param_format(text):
return color_format(ConsoleColors.CYAN, text)
def undefined_param_format(text):
return color_format(ConsoleColors.YELLOW, text)
def code_format(code, bg_size):
lines = code.splitlines()
bg_size = max(TERM_SIZE.columns // 2 - 10, bg_size)
code = NEWLINE.join([line.ljust(bg_size) for line in lines])
highlighted = highlight(code, LEXER, FORMATTER).rstrip(NEWLINE)
return color_format(ConsoleColors.BG_GRAY, highlighted)
class DocParameter(object):
def __init__(self, name: str, cls: type, desc: str):
self.name = name
self.cls = cls
self.desc = desc
class ClassTuple(object):
def __init__(self, *items):
self.items = items
def __str__(self):
return f"({', '.join([item for item in self.items])})"
class DocReturns(object):
def __init__(self, cls: type, desc: str):
def strip_namespace(cls):
return type_format(str(cls).split('.')[-1].lstrip("<class '").rstrip("'>"))
if type(cls) is type:
cls = strip_namespace(cls)
elif type(cls) is tuple:
cls = ClassTuple(*[strip_namespace(item) for item in cls])
else:
cls = type_format(cls)
self.cls = cls
self.desc = desc
class DocReference(object):
def __init__(self, name: str, url: str):
self.name = name
self.url = url
class DocExample(object):
def __init__(self, code: str, result: str):
self.code = code
self.result = result
def __repr__(self):
lines = self.code.splitlines()
bg_size = max([len(l) for l in lines])+5
return NEWLINE.join([TAB + code_format(f'>>> {line}', bg_size=bg_size) for line in lines]) + NEWLINE + NEWLINE.join([TAB + code_format(line, bg_size=bg_size) for line in str(self.result).split('$N$')])
def __str__(self):
return self.__repr__()
def load(self):
from IPython import get_ipython
get_ipython().set_next_input(self.code)
def gen_doc(description: str=None, parameters: list=None, returns: DocReturns=None, examples: list=None, references: list=None):
def _doc(func):
parameters_str = ""
returns_str = ""
references_str = ""
examples_str = ""
if parameters:
largest_param = max([len(param.name) + len(param.cls) for param in parameters])
parameters_str = f"""
Parameters:
{NEWLINE.join([f'{TAB}{param_format(param.name)}{" " * (largest_param + 1 - (len(param.name) + len(param.cls)))}({type_format(param.cls)}): {param.desc}' for param in parameters])}"""
if returns:
returns_str = f"""
Returns{' (complexity ' + undefined_param_format(str(func.complexity)) + ')' if hasattr(func, 'complexity') else ''}:
{TAB}{returns.cls}: {returns.desc}"""
if examples:
examples_str = f"""
Examples:
{(NEWLINE + NEWLINE).join([f'{TAB}>>> # Example {idx}{NEWLINE}' + str(example) for idx, example in enumerate(examples)])}"""
if references:
references_str = f"""
References:
{NEWLINE.join([f'{TAB}{(QUOTE + ref.name + QUOTE + " ") if ref.name else ""}{"(" + ref.url + ")" if ref.name else ref.url}' for ref in references])}"""
# Color references to parameters
def parameterize(d_str):
for param in parameters:
d_str = d_str.replace(f'`{param.name}`', param_format(param.name))
return d_str
def undefined_parameterize(d_str):
return UNDEFINED_PARAM_RE.sub(lambda match: undefined_param_format(match.group()[1:-1]), d_str)
parameterized_desc = undefined_parameterize(parameterize(description))
parameterized_ret = undefined_parameterize(parameterize(returns_str))
param_params = undefined_parameterize(parameterize(parameters_str))
func.__doc__ = f"{parameterized_desc}{param_params}{parameterized_ret}{examples_str}{references_str}"
func.examples = examples
func.is_rich = True
return func
return _doc
def parse_doc(func):
doc = func.__doc__
lines = doc.splitlines()
def get_line_idx(text):
found = [idx for idx, line in enumerate(lines) if text in line]
return found[0] if found else -1
headers = ['Parameters', 'Returns', 'Examples', 'References']
indices = [('Description', 0)] + [(header, get_line_idx(header + ':')) for header in headers]
parsed = {}
# Parse out sections in order
for idx, (header, line_idx) in enumerate(indices):
if line_idx >= 0:
next_idx = [next_idx for _, next_idx in indices[idx+1:] if next_idx > 0]
if next_idx:
relevant_lines = lines[line_idx+1:next_idx[0]]
else:
relevant_lines = lines[line_idx+1:]
relevant_lines = [l.strip() for l in relevant_lines]
relevant_lines = [l for l in relevant_lines if l]
parsed[header] = relevant_lines
# Handle each case separately
description = ' '.join([line.strip() for line in parsed['Description']]).strip()
params = []
if 'Parameters' in parsed:
for param in parsed['Parameters']:
split = param.split(' ', 1)
p_name = split[0]
p_type, p_desc = split[1].split(':', 1)
params.append(DocParameter(p_name, p_type.strip('(): '), p_desc.strip()))
returns = None
if 'Returns' in parsed:
split = parsed['Returns'][0].split(':', 1)
r_type = split[0].rstrip(':')
r_desc = split[1].strip()
returns = DocReturns(r_type, r_desc)
_examples = []
examples = []
if 'Examples' in parsed:
exs = parsed['Examples']
output_idxs = [-1] + [idx for idx, ex in enumerate(exs) if ">>>" not in ex]
for idx, out_idx in enumerate(output_idxs[1:]):
code = NEWLINE.join([ex[ex.index(">>> ")+4:] for ex in exs[output_idxs[idx]+1:out_idx]])
_examples.append(DocExample(code, exs[out_idx]))
# Handle multiline output (adjacent indices/no code)
for idx, example in enumerate(_examples):
if example.code:
examples.append(example)
else:
examples[-1].result += '$N$' + example.result
references = []
if 'References' in parsed:
refs = parsed['References']
for ref in refs:
url_start = ref.index('http')
if url_start > -1:
name = ref[:url_start]
url = ref[url_start:]
url = url.strip(" \"\'")
if name and url[-1] == ')':
url = url[:-1]
else:
name = ref
url = ""
dref = DocReference(name.strip("\"\' ("), url)
references.append(dref)
return description, params, returns, examples, references
def richdoc(func):
if func.__doc__ and not hasattr(func, 'is_rich'):
return gen_doc(*parse_doc(func))(func)
else:
return func
def autodoc(g):
def process_func(name, func):
g[name] = richdoc(func)
for name, obj in g.items():
if hasattr(obj, '__module__') and 'samson' in obj.__module__:
t_o = type(obj)
if t_o is FunctionType:
process_func(name, obj)
elif issubclass(t_o, type):
for member in dir(obj):
try:
mem = getattr(obj, member)
if type(mem) is FunctionType and mem.__module__.split('.')[0] == 'samson':
richdoc(mem)
except AttributeError:
pass
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/auxiliary/autodoc.py
| 0.522933 | 0.182335 |
autodoc.py
|
pypi
|
import math
from types import FunctionType
import logging
log = logging.getLogger(__name__)
class NaiveMDCollider(object):
"""
Merkle-Damgard collider that (naively) uses bruteforce to find collisions. Do not use for cryptographic
strength algorithms.
"""
def __init__(self, construction_func: FunctionType, output_size: int):
"""
Parameters:
construction_func (func): Function that takes in two bytes-like arguments and returns the next Merkle-Damgard state.
output_size (int): Size in bytes of the hash output.
Examples:
>>> def construction_func(iv, message):
>>> return MerkleDamgardConstruction(iv, compressor, padder, output_size=hash_size).yield_state(message)
"""
self.construction_func = construction_func
self.output_size = output_size
@staticmethod
def initialize_with_known_prefixes(prefixes: list, iv: bytes, construction_func: FunctionType, output_size: int):
"""
Initializes a NaiveMDCollider using known prefixes. In Nostradamus-attack terms, the initial states
you're trying to find collisions for.
Parameters:
prefixes (list): List of bytes-like prefixes to build initial states from.
iv (bytes): Initial state of the Merkle-Damgard function (possibly None).
construction_func (func): Function that takes in two bytes-like arguments and returns the next Merkle-Damgard state.
output_size (int): Size in bytes of the hash output.
Returns:
NaiveMDCollider: NaiveMDCollider initialized with known prefixes.
"""
k = math.ceil(math.log(len(prefixes), 2))
# Find the maximum length of padded prefixes
padding_size = math.ceil(max([len(prefix) for prefix in prefixes]) / output_size) * output_size
prefixes = [(prefix + (b'\x00' * padding_size))[:padding_size] for prefix in prefixes]
hashed_prefixes = [list(construction_func(iv, prefix))[-1] for prefix in prefixes]
return NaiveMDCollider(construction_func, output_size), k, prefixes, hashed_prefixes
def find_collision(self, p1: bytes, p2: bytes) -> (bytes, bytes, bytes):
"""
Finds a collision using bruteforce.
Parameters:
p1 (bytes): First sample.
p2 (bytes): Second sample.
Returns:
(bytes, bytes, bytes): Tuple of bytes representing the collision as (p1_suffix, p2_suffix, self.hasher.hash(p1 + p1_suffix)).
"""
input_for_p1 = b'\x00' * self.output_size
state_to_collide = list(self.construction_func(p1, input_for_p1))[0]
# Try a lot of values...
for j in range(2**(self.output_size * 32)):
attempt = int.to_bytes(j, self.output_size * 4, 'little')
# We'll need to keep a state counter since we may not get a collision on the first chunk
state_ctr = 0
for state in self.construction_func(p2, attempt):
state_ctr += 1
if state == state_to_collide:
log.debug(f'Found collision for ({p1}, {p2})')
return input_for_p1, attempt[:state_ctr * self.output_size], state_to_collide
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/auxiliary/naive_collider.py
| 0.839273 | 0.623062 |
naive_collider.py
|
pypi
|
import math
from functools import lru_cache
from samson.auxiliary.lazy_loader import LazyLoader
@lru_cache()
def get_math_gen():
return LazyLoader('_math_gen', globals(), 'samson.math.general')
@lru_cache()
def get_factor_gen():
return LazyLoader('_factor_gen', globals(), 'samson.math.factorization.general')
class Complexity(object):
def __init__(self, repr, estimator):
self.repr = repr
self.estimate = estimator
def __repr__(self):
return self.repr
class LComplexity(Complexity):
def __init__(self, a, c):
self.repr = f'L_n[{a}, {c}]'
self.estimate = lambda n: int(get_math_gen().estimate_L_complexity(a, c, n))
def add_complexity(complexity):
def wrapper(func):
func.complexity = complexity
return func
return wrapper
def _ph_estimator(g: 'RingElement', n: int=None, factors: dict=None):
if not n:
n = g.order()
if not factors:
factors = get_factor_gen().factor(n)
total = 1
for p, e in factors.items():
total *= get_math_gen().kth_root(p, 2)*e
return total // 2
class KnownComplexities(object):
LOG = Complexity(repr='O(log n)', estimator=lambda n: n.bit_length())
LINEAR = Complexity(repr='O(n)', estimator=lambda n: n)
QUAD = Complexity(repr='O(n^2)', estimator=lambda n: n**2)
CUBIC = Complexity(repr='O(n^3)', estimator=lambda n: n**3)
GNFS = LComplexity(1/3, (64/9)**(1/3))
SNFS = LComplexity(1/3, (32/9)**(1/3))
IC = LComplexity(1/2, math.sqrt(2))
PH = Complexity(repr='O(e√p)', estimator=_ph_estimator)
LLL = Complexity(repr='O(n^4 log B)', estimator=lambda rows, columns: rows**4 * columns.bit_length()) # https://arxiv.org/abs/1006.1661#:~:text=Its%20average%20complexity%20is%20shown,approximations%20of%20LLL%20are%20proposed.
GRAM = Complexity(repr='O(2nk^2)', estimator=lambda rows, columns: 2*rows*columns**2) # https://stackoverflow.com/questions/27986225/computational-complexity-of-gram-schmidt-orthogonalization-algorithm
SIQS = Complexity(repr='O(exp(sqrt(log n log log n)))', estimator=lambda n: round(math.e**(math.sqrt(math.log(n) * math.log(math.log(n)))))) # https://www.rieselprime.de/ziki/Self-initializing_quadratic_sieve#Complexity
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/auxiliary/complexity.py
| 0.745213 | 0.301272 |
complexity.py
|
pypi
|
from math import log10
from samson.auxiliary.lazy_loader import LazyLoader
_eng_data = LazyLoader('_eng_data', globals(), 'samson.auxiliary.english_data')
# http://practicalcryptography.com/cryptanalysis/text-characterisation/word-statistics-fitness-measure/
class ViterbiDecoder(object):
"""
Statistical model that decodes non-delimited English text into tokens using maximum likelihood metrics.
"""
def __init__(self):
self.Pw = {}
self.N = 1024908267229 ## Number of tokens
# Calculate first order log probabilities
for key in _eng_data.ENGLISH_ONE_GRAMS.keys():
self.Pw[key.upper()] = log10(float(_eng_data.ENGLISH_ONE_GRAMS[key]) / self.N)
# Get second order word model
self.Pw2 = {}
# Calculate second order log probabilities
for key in _eng_data.ENGLISH_TWO_GRAMS.keys():
word1 = key.split()[0].upper()
if word1 not in self.Pw:
self.Pw2[key.upper()] = log10(float(_eng_data.ENGLISH_TWO_GRAMS[key]) / self.N)
else:
self.Pw2[key.upper()] = log10(float(_eng_data.ENGLISH_TWO_GRAMS[key]) / self.N) - self.Pw[word1]
# Precalculate the probabilities we assign to words not in our dict, L is length of word
self.unseen = [log10(10. / (self.N * 10**L)) for L in range(50)]
def cPw(self, word: str, prev: str='<UNK>') -> float:
"""
Calculates the conditional word probability.
Parameters:
word (str): Current word.
prev (str): Previous word.
Returns:
float: Log probability of `word` based on `prev`.
"""
second_order_word = (prev + ' ' + word)
if word not in self.Pw:
return self.unseen[len(word)]
elif second_order_word not in self.Pw2:
return self.Pw[word]
else:
return self.Pw2[second_order_word]
def score(self, text: str, max_word_len=20) -> (float, list):
"""
Scores and tokenizes the text according to the maximum likelihood.
Parameters:
text (str): Text to tokenize/decode.
max_word_len (int): Maximum token length.
Returns:
(float, list): Most probable decoding as (score, token_list).
"""
text = text.upper()
prob = [[-99e99] * max_word_len for _ in range(len(text))]
strs = [[''] * max_word_len for _ in range(len(text))]
for j in range(max_word_len):
prob[0][j] = self.cPw(text[:j+1])
strs[0][j] = [text[:j+1]]
for i in range(1,len(text)):
for j in range(max_word_len):
if i+j+1 > len(text): break
candidates = [(prob[i-k-1][k] + self.cPw(text[i: i+j+1], strs[i-k-1][k][-1]),
strs[i-k-1][k] + [text[i: i+j+1]]) for k in range(min(i, max_word_len))]
prob[i][j], strs[i][j] = max(candidates)
ends = [(prob[-i-1][i], strs[-i-1][i]) for i in range(min(len(text), max_word_len))]
return max(ends)
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/auxiliary/viterbi_decoder.py
| 0.856812 | 0.321953 |
viterbi_decoder.py
|
pypi
|
from enum import Enum
from types import FunctionType
from samson.utilities.runtime import RUNTIME
from samson.core.base_object import BaseObject
import random
class Chromosome(BaseObject):
"""
Represents a Chromosome. Used by GeneticAlgorithm to keep state.
"""
def __init__(self, state: object):
"""
Parameters:
state (object): The "DNA" of the organism. Can be anything.
"""
self.state = state
self.fitness = 0
class TerminationReason(Enum):
MAX_ITERATION_REACHED = 0
MINIMUM_CONVERGENCE_UNSATISFIED = 1
GLOBAL_OPTIMA_REACHED = 2
class OptimizationResult(BaseObject):
"""
Encapsulates finished-state information for optimization algorithms.
"""
def __init__(self, solution: object, iteration: int, termination_reason: TerminationReason):
"""
Parameters:
solution (object): Best solution from the optimization algorithm.
iteration (int): Iteration stopped at.
termination_reason (TerminationReason): Reason for execution termination.
"""
self.solution = solution
self.iteration = iteration
self.termination_reason = termination_reason
# https://en.wikipedia.org/wiki/Genetic_algorithm
class GeneticAlgorithm(BaseObject):
"""
Highly configurable genetic algorithm implementation. Bring-your-own functions.
"""
def __init__(self,
initialization_func: FunctionType,
obj_func: FunctionType,
crossover_func: FunctionType,
mutation_func: FunctionType,
population_size: int,
parent_pool_size: int,
num_parents: int,
maximize: bool=True,
elitism: bool=True,
num_immigrants: int=0,
minimum_convergence: float=1e-6,
min_conv_tolerance: int=5,
convergence_granularity: int=1000000):
"""
Parameters:
initialization_func (func): Takes in an int and initializes that many population members.
obj_func (func): Takes in a list of Chromosomes changes their `fitness` value.
crossover_func (func): Takes in a list of parents and possibly performs crossover. Returns a "child" state.
mutation_func (func): Takes in a Chromosome and possibly mutates it.
population_size (int): Size of the population.
parent_pool_size (int): Size of the parent pool to breed the next generation.
num_parents (int): Number of parents to produce a child (i.e. n-way crossover).
maximize (bool): True to maximize the objective function, False to minimize it.
elitism (bool): Whether or not to insert the best solutions of the last generation into the next.
num_immigrants (int): Number of "immigrants". Immigrants are additional parents created using `initialization_func`.
minimum_convergence (float): Minimum convergence differential between generations before ticking the `min_conv_counter`.
min_conv_tolerance (int): Number of generations not satisfying minimum convergence before terminating.
convergence_granularity (int): Granularity for comparing minimum convergence and fitness. Internally, `minimum_convergence` is discretized to allow for multi-precision integer fitness scores.
"""
self.initialization_func = initialization_func
self.obj_func = obj_func
self.crossover_func = crossover_func
self.mutation_func = mutation_func
self.parent_pool_size = parent_pool_size
self.num_parents = num_parents
self.population_size = population_size
self.population = [Chromosome(individual) for individual in self.initialization_func(self.population_size)]
self.maximize = maximize
self.elitism = elitism
self.num_immigrants = num_immigrants
self.minimum_convergence = minimum_convergence
self.min_conv_tolerance = min_conv_tolerance
self.convergence_granularity = convergence_granularity
def __hash__(self):
return object.__hash__(self)
@RUNTIME.report
def run(self, generations: int) -> OptimizationResult:
min_conv_counter = 0
current_best = (not self.maximize) * 2**8192
termination_reason = TerminationReason.MAX_ITERATION_REACHED
granularized_minimum_convergence = self.convergence_granularity * self.minimum_convergence
for iteration in RUNTIME.report_progress(range(generations), desc='Generations', unit='gens'):
# 1) Measure
self.obj_func(self.population)
# 2) Select
parent_pool = sorted(self.population, key=lambda chromo: chromo.fitness, reverse=self.maximize)[:self.parent_pool_size]
# Test for minimum convergence heuristic
if abs(parent_pool[0].fitness - current_best) // (current_best * self.convergence_granularity) < granularized_minimum_convergence:
if min_conv_counter < self.min_conv_tolerance:
min_conv_counter += 1
else:
termination_reason = TerminationReason.MINIMUM_CONVERGENCE_UNSATISFIED
break
else:
current_best = parent_pool[0].fitness
min_conv_counter = 0
if not self.maximize and not current_best:
termination_reason = TerminationReason.GLOBAL_OPTIMA_REACHED
break
next_population = []
# Elitism
if self.elitism:
next_population.extend(parent_pool)
# Immigration
parent_pool.extend([Chromosome(individual) for individual in self.initialization_func(self.num_immigrants)])
# Breeding
while len(next_population) < self.population_size:
parents = random.sample(parent_pool, k=self.num_parents)
# 3) Crossover
individual = Chromosome(self.crossover_func(parents))
# 4) Mutate
individual = self.mutation_func(individual)
next_population.append(individual)
self.population = next_population
self.obj_func(self.population)
return OptimizationResult(sorted(self.population, key=lambda chromo: chromo.fitness, reverse=self.maximize)[0], iteration, termination_reason)
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/auxiliary/genetic_algorithm.py
| 0.877267 | 0.436202 |
genetic_algorithm.py
|
pypi
|
from samson.math.general import next_prime, pohlig_hellman, is_prime, random_int_between
from samson.math.algebra.rings.integer_ring import ZZ
from samson.utilities.exceptions import SearchspaceExhaustedException
# "Optimization of the ROCA (CVE-2017-15361) Attack"
M_PRIME_TABLE = {
512: (0x1b3e6c9433a7735fa5fc479ffe4027e13bea, 5, 6, 0x80000),
1024: (0x24683144f41188c2b1d6a217f81f12888e4e6513c43f3f60e72af8bd9728807483425d1e, 4, 5, 0x40000000),
2048: (0x016928dc3e47b44daf289a60e80e1fc6bd7648d7ef60d1890f3e0a9455efe0abdb7a748131413cebd2e36a76a355c1b664be462e115ac330f9c13344f8f3d1034a02c23396e6, 7, 8, 0x400000000)
}
N_TABLE = {
range(512, 960+1): 39,
range(992, 1952+1): 71,
range(1984, 3936+1): 126,
range(3968, 4069+1): 225
}
def gen_M(bit_size):
for r in N_TABLE:
if bit_size in r:
n = N_TABLE[r]
p = 0
M = 1
for _ in range(n):
p = next_prime(p+1)
M *= p
return M
def get_params(bit_size):
if bit_size < 992:
return M_PRIME_TABLE[512]
elif bit_size < 1984:
return M_PRIME_TABLE[1024]
else:
return M_PRIME_TABLE[2048]
def get_roca_log(N):
Mp, _, _, _ = get_params(N.bit_length())
Zm = (ZZ/ZZ(Mp)).mul_group()
g = Zm(65537)
return pohlig_hellman(g, Zm(N))
def check_roca(N):
try:
get_roca_log(N)
return True
except SearchspaceExhaustedException:
return False
# LSB bias
def add_parity_bias(a: int):
lsb = random_int_between(0, 99) > 89
if a & 1 == lsb:
return a
else:
return a ^ 1
def gen_roca_prime(bit_size: int):
M = gen_M(bit_size*2)
M_size = M.bit_length()
p = 4
k_size = bit_size-M_size-1
# Here we're manually adding the MSB bias
Mp, _, _, c_a = get_params(bit_size*2)
Zm = (ZZ/ZZ(Mp)).mul_group()
max_a = Zm(65537).order()
while not is_prime(p):
k = random_int_between(2**k_size+1 , 2**(k_size+1))
a = random_int_between(c_a, max_a)
a = add_parity_bias(a)
p = k*M + pow(65537, a, M)
return p, k, a, M
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/auxiliary/roca.py
| 0.562657 | 0.276843 |
roca.py
|
pypi
|
from samson.block_ciphers.des import DES
from samson.utilities.bytes import Bytes
from samson.core.primitives import BlockCipher, Primitive
from samson.core.metadata import SizeType, SizeSpec, FrequencyType
from samson.ace.decorators import register_primitive
@register_primitive()
class TDES(BlockCipher):
"""
3DES in EDE mode.
Structure: Feistel Network
Key size: 64, 128, 192 bits (56, 80, 112 bits of security)
Block size: 64 bits
"""
KEY_SIZE = SizeSpec(size_type=SizeType.RANGE, sizes=[64, 128, 192], typical=[128, 192])
BLOCK_SIZE = SizeSpec(size_type=SizeType.SINGLE, sizes=64)
USAGE_FREQUENCY = FrequencyType.NORMAL
def __init__(self, key: bytes):
"""
Parameters:
key (bytes): Bytes-like object to key the cipher.
"""
Primitive.__init__(self)
key = Bytes.wrap(key)
if not len(key) in [8, 16, 24]:
raise ValueError('`key` size must be in [8, 16, 24]')
self.key = key
self.des_arr = [DES(subkey.zfill(8)) for subkey in key.chunk(8)]
self.block_size = 8
def __reprdir__(self):
return ['key', 'des_arr']
def encrypt(self, plaintext: bytes) -> Bytes:
"""
Encrypts `plaintext`.
Parameters:
plaintext (bytes): Bytes-like object to be encrypted.
Returns:
Bytes: Resulting ciphertext.
"""
plaintext = Bytes.wrap(plaintext)
pt_1 = self.des_arr[0].encrypt(plaintext)
pt_2 = self.des_arr[1].decrypt(pt_1)
ciphertext = self.des_arr[2].encrypt(pt_2)
return ciphertext
def decrypt(self, ciphertext: bytes) -> Bytes:
"""
Decrypts `ciphertext`.
Parameters:
ciphertext (bytes): Bytes-like object to be decrypted.
Returns:
Bytes: Resulting plaintext.
"""
ciphertext = Bytes.wrap(ciphertext)
ct_1 = self.des_arr[2].decrypt(ciphertext)
ct_2 = self.des_arr[1].encrypt(ct_1)
plaintext = self.des_arr[0].decrypt(ct_2)
return plaintext
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/block_ciphers/tdes.py
| 0.822082 | 0.222647 |
tdes.py
|
pypi
|
from samson.utilities.manipulation import left_rotate
from samson.utilities.bytes import Bytes
from samson.core.primitives import BlockCipher, Primitive
from samson.core.metadata import SizeType, SizeSpec, ConstructionType, FrequencyType
from samson.ace.decorators import register_primitive
def initialize_sbox():
p = 1
q = 1
sbox = [None] * 256
first_round = True
while first_round or p != 1:
# Multiply p by 3
p = p ^ (p << 1) ^ (0x1B if p & 0x80 else 0)
p &= 0xFF
# Divide q by 3
q ^= (q << 1) & 0xFF
q ^= (q << 2) & 0xFF
q ^= (q << 4) & 0xFF
q ^= 0x09 if q & 0x80 else 0
q &= 0xFF
# Compute the affine transformation
xformed = q ^ left_rotate(q, 1, 8) ^ left_rotate(q, 2, 8) ^ left_rotate(q, 3, 8) ^ left_rotate(q, 4, 8)
xformed &= 0xFF
sbox[p] = xformed ^ 0x63
first_round = False
# Zero has no inverse and must be set manually
sbox[0] = 0x63
return sbox
def invert_sbox(sbox):
inv_sbox = [None] * 256
for i in range(256):
inv_sbox[sbox[i]] = i
return inv_sbox
RCON = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36, 0x6C, 0xD8, 0xAB, 0x4D, 0x9A, 0x2F, 0x5E, 0xBC, 0x63, 0xC6, 0x97, 35, 0x6A, 0xD4, 0xB3, 0x7D, 0xFA, 0xEF, 0xC5]
SBOX = initialize_sbox()
INV_SBOX = invert_sbox(SBOX)
MIX_MATRIX = [2, 3, 1, 1, 1, 2, 3, 1, 1, 1, 2, 3, 3, 1, 1, 2]
INV_MIX_MATRIX = [14, 11, 13, 9, 9, 14, 11, 13, 13, 9, 14, 11, 11, 13, 9, 14]
SHIFT_ROW_OFFSETS = [
*[[0, 1, 2, 3]] * 3,
[0, 1, 2, 4],
[0, 1, 3, 4]
]
NUM_ROUNDS = [
[10, 12, 14],
[12, 12, 14],
[14, 14, 14]
]
# https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf
@register_primitive()
class Rijndael(BlockCipher):
"""
Underlying cipher of AES.
Structure: Substitution–permutation network
Key size: 128, 160, 192, 224, 256 bits
Block size: 128, 160, 192, 224, 256 bits
"""
KEY_SIZE = SizeSpec(size_type=SizeType.RANGE, sizes=[128, 160, 192, 224, 256], typical=[128, 256])
BLOCK_SIZE = SizeSpec(size_type=SizeType.RANGE, sizes=[128, 160, 192, 224, 256], typical=[128])
CONSTRUCTION_TYPES = [ConstructionType.SUBSTITUTION_PERMUTATION_NETWORK]
USAGE_FREQUENCY = FrequencyType.PROLIFIC
def __init__(self, key: bytes, block_size: int=16):
"""
Parameters:
key (bytes): Bytes-like object to key the cipher.
block_size (int): The desired block size in bytes.
"""
Primitive.__init__(self)
key = Bytes.wrap(key)
if not (len(key)) in range(16, 33, 4):
raise ValueError("Invalid key size! Must be between 128 bits (16 bytes) and 256 bits (32 bytes) and a multiple of 32 bits (4 bytes)")
if not block_size in range(16, 33, 4):
raise ValueError("Invalid block size! Must be between 128 bits (16 bytes) and 256 bits (32 bytes) and a multiple of 32 bits (4 bytes)")
self.key = key
self.block_size = block_size
self._chunk_size = self.block_size // 4
round_keys = self.key_schedule()
self.round_keys = [Bytes(b''.join(round_keys[i:i + self._chunk_size])) for i in range(0, len(round_keys), self._chunk_size)]
Nk = len(self.key) // 4
Nb = self._chunk_size
self.num_rounds = NUM_ROUNDS[(Nk - 4) // 2][(Nb - 4) // 2] + 1
def __reprdir__(self):
return ['key', 'block_size']
# https://en.wikipedia.org/wiki/Rijndael_key_schedule
def key_schedule(self):
N = len(self.key) // 4
K = self.key.chunk(4)
R = max(N, self._chunk_size) + 7
W = []
for i in range(self._chunk_size*R):
if i < N:
W_i = K[i]
elif i % N == 0:
W_i = W[i - N] ^ Bytes([SBOX[byte] for byte in W[i - 1].lrot(8)]) ^ bytes([RCON[i // N - 1], *[0] * 3])
elif N > 6 and i % N == 4:
W_i = W[i - N] ^ Bytes([SBOX[byte] for byte in W[i - 1]])
else:
W_i = W[i - N] ^ W[i - 1]
W.append(W_i)
return W
def yield_encrypt(self, plaintext):
state_matrix = Bytes.wrap(plaintext).transpose(4)
for i in range(self.num_rounds):
round_key = self.round_keys[i].transpose(4)
if i == 0:
state_matrix ^= round_key
elif i < (self.num_rounds - 1):
state_matrix = Bytes([SBOX[byte] for byte in state_matrix])
state_matrix = self.shift_rows(state_matrix)
state_matrix = Bytes(self.mix_columns(state_matrix, MIX_MATRIX))
state_matrix ^= round_key
else:
state_matrix = Bytes([SBOX[byte] for byte in state_matrix])
state_matrix = self.shift_rows(state_matrix)
state_matrix ^= round_key
yield state_matrix.transpose(self._chunk_size)
def encrypt(self, plaintext: bytes) -> Bytes:
"""
Encrypts `plaintext`.
Parameters:
plaintext (bytes): Bytes-like object to be encrypted.
Returns:
Bytes: Resulting ciphertext.
"""
return list(self.yield_encrypt(plaintext))[-1]
def yield_decrypt(self, ciphertext):
state_matrix = Bytes.wrap(ciphertext).transpose(4)
reversed_round_keys = self.round_keys[::-1]
for i in range(self.num_rounds):
round_key = reversed_round_keys[i].transpose(4)
if i == 0:
state_matrix ^= round_key
elif i < (self.num_rounds - 1):
state_matrix = self.inv_shift_rows(state_matrix)
state_matrix = Bytes([INV_SBOX[byte] for byte in state_matrix])
state_matrix ^= round_key
state_matrix = Bytes(self.mix_columns(state_matrix, INV_MIX_MATRIX))
else:
state_matrix = self.inv_shift_rows(state_matrix)
state_matrix = Bytes([INV_SBOX[byte] for byte in state_matrix])
state_matrix ^= round_key
yield state_matrix.transpose(self._chunk_size)
def decrypt(self, ciphertext: bytes) -> Bytes:
"""
Decrypts `ciphertext`.
Parameters:
ciphertext (bytes): Bytes-like object to be decrypted.
Returns:
Bytes: Resulting plaintext.
"""
return list(self.yield_decrypt(ciphertext))[-1]
def shift_rows(self, state_matrix):
offsets = SHIFT_ROW_OFFSETS[(self._chunk_size) - 4]
return b''.join([row.lrot(offsets[j] * 8) for j, row in enumerate(state_matrix.chunk(self._chunk_size))])
def inv_shift_rows(self, state_matrix):
offsets = SHIFT_ROW_OFFSETS[(self._chunk_size) - 4]
return b''.join([row.rrot(offsets[j] * 8) for j, row in enumerate(state_matrix.chunk(self._chunk_size))])
# https://en.wikipedia.org/wiki/Rijndael_MixColumns
def _gmul(self, a, b):
p = 0
for _ in range(8):
if (b & 1) != 0:
p ^= a
hi_bi_set = (a & 0x80) != 0
a <<=1
if hi_bi_set:
a ^= 0x1B
b >>= 1
return p
def mix_columns(self, state_matrix, mix_matrix):
new_state = [None] * len(state_matrix)
c0, c1, c2, c3 = [self._chunk_size * i for i in range(4)]
for i in range(self._chunk_size):
new_state[i + c0] = (self._gmul(mix_matrix[0], state_matrix[i + c0]) ^ self._gmul(mix_matrix[1], state_matrix[i + c1]) ^ self._gmul(mix_matrix[2], state_matrix[i + c2]) ^ self._gmul(mix_matrix[3], state_matrix[i + c3])) & 0xFF
new_state[i + c1] = (self._gmul(mix_matrix[4], state_matrix[i + c0]) ^ self._gmul(mix_matrix[5], state_matrix[i + c1]) ^ self._gmul(mix_matrix[6], state_matrix[i + c2]) ^ self._gmul(mix_matrix[7], state_matrix[i + c3])) & 0xFF
new_state[i + c2] = (self._gmul(mix_matrix[8], state_matrix[i + c0]) ^ self._gmul(mix_matrix[9], state_matrix[i + c1]) ^ self._gmul(mix_matrix[10], state_matrix[i + c2]) ^ self._gmul(mix_matrix[11], state_matrix[i + c3])) & 0xFF
new_state[i + c3] = (self._gmul(mix_matrix[12], state_matrix[i + c0]) ^ self._gmul(mix_matrix[13], state_matrix[i + c1]) ^ self._gmul(mix_matrix[14], state_matrix[i + c2]) ^ self._gmul(mix_matrix[15], state_matrix[i + c3])) & 0xFF
return new_state
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/block_ciphers/rijndael.py
| 0.73848 | 0.416381 |
rijndael.py
|
pypi
|
from samson.constructions.feistel_network import FeistelNetwork
from samson.utilities.bytes import Bytes
from samson.encoding.general import bytes_to_bitstring
from samson.utilities.manipulation import left_rotate
from samson.core.primitives import BlockCipher, PrimitiveType
from samson.core.metadata import SizeType, SizeSpec, FrequencyType
from samson.ace.decorators import register_primitive
# https://en.wikipedia.org/wiki/Data_Encryption_Standard
IP = [
58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
63, 55, 47, 39, 31, 23, 15, 7
]
FP = [
40, 8, 48, 16, 56, 24, 64, 32,
39, 7, 47, 15, 55, 23, 63, 31,
38, 6, 46, 14, 54, 22, 62, 30,
37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28,
35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26,
33, 1, 41, 9, 49, 17, 57, 25
]
S1 = [
[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7],
[0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8],
[4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0],
[15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13]
]
S2 = [
[15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10],
[3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5],
[0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15],
[13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9]
]
S3 = [
[10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8],
[13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1],
[13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7],
[1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12]
]
S4 = [
[7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15],
[13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9],
[10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4],
[3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14]
]
S5 = [
[2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9],
[14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6],
[4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14],
[11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3]
]
S6 = [
[12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11],
[10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8],
[9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6],
[4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13]
]
S7 = [
[4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1],
[13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6],
[1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2],
[6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12]
]
S8 = [
[13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7],
[1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2],
[7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8],
[2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11]
]
sboxes = [S1, S2, S3, S4, S5, S6, S7, S8]
pbox = [
16, 7, 20, 21, 29, 12, 28, 17,
1, 15, 23, 26, 5, 18, 31, 10,
2, 8, 24, 14, 32, 27, 3, 9,
19, 13, 30, 6, 22, 11, 4, 25
]
PC_1_left = [
57, 49, 41, 33, 25, 17, 9,
1, 58, 50, 42, 34, 26, 18,
10, 2, 59, 51, 43, 35, 27,
19, 11, 3, 60, 52, 44, 36,
]
PC_1_right = [
63, 55, 47, 39, 31, 23, 15,
7, 62, 54, 46, 38, 30, 22,
14, 6, 61, 53, 45, 37, 29,
21, 13, 5, 28, 20, 12, 4,
]
PC_2 = [
14, 17, 11, 24, 1, 5,
3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8,
16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55,
30, 40, 51, 45, 33, 48,
44, 49, 39, 56, 34, 53,
46, 42, 50, 36, 29, 32,
]
rotation_round_map = [*[1] * 2, *[2] * 6, 1, *[2] * 6, 1]
def key_schedule(key):
key_bits = bytes_to_bitstring(key)
left_key = ''.join([key_bits[PC_1_left[i] - 1] for i in range(28)])
right_key = ''.join([key_bits[PC_1_right[i] - 1] for i in range(28)])
for i in range(16):
# Rotate
rotation = rotation_round_map[i]
left_key = bin(left_rotate(int(left_key, 2), rotation, bits=28))[2:].zfill(28)
right_key = bin(left_rotate(int(right_key, 2), rotation, bits=28))[2:].zfill(28)
# Permutate
combined_keys = left_key + right_key
sub_key = int.to_bytes(int(''.join([combined_keys[PC_2[j] - 1] for j in range(48)]), 2), 7, 'big')
yield sub_key
# http://styere.xyz/JS-DES.html
def round_func(R_i, k_i):
# Need to pad with the first since the Feistel function requires 'adjacent' bits for the expanded blocks
R_i_bits = bytes_to_bitstring(R_i)
R_i_bits = R_i_bits[-1] + R_i_bits + R_i_bits[0]
# Expansion
expanded_pt = ''.join([R_i_bits[i*4:(i+1)*4 + 2] for i in range(8)])
# Key mixing
K_i_bits = bytes_to_bitstring(k_i)[8:]
mixed = [int(bitA) ^ int(bitB) for bitA, bitB in zip(expanded_pt, K_i_bits)]
# Substitution
blocks = [mixed[i*6:(i+1)*6] for i in range(8)]
substitutions = []
for i, block in enumerate(blocks):
row = (block[0]<<1) + block[-1]
column = sum([bit<<j for j,bit in enumerate(block[1:5][::-1])])
substitutions.append(sboxes[i][row][column])
# Permutation
full_sub_string = ''.join([bin(sub)[2:].zfill(4) for sub in substitutions])
permutations = ''.join([full_sub_string[pbox[i] - 1] for i in range(32)])
return int.to_bytes(int(permutations, 2), 4, 'big')
@register_primitive()
class DES(FeistelNetwork, BlockCipher):
"""
Structure: Feistel Network
Key size: 64 (56, actually)
Block size: 64
"""
KEY_SIZE = SizeSpec(size_type=SizeType.SINGLE, sizes=64)
BLOCK_SIZE = SizeSpec(size_type=SizeType.SINGLE, sizes=64)
USAGE_FREQUENCY = FrequencyType.UNUSUAL
def __init__(self, key: bytes):
"""
Parameters:
key (bytes): Bytes-like object to key the cipher.
"""
super().__init__(round_func, key_schedule)
PrimitiveType.__init__(self)
self.key = Bytes.wrap(key).zfill(8)
self.block_size = 8
def __reprdir__(self):
return ['key']
def process_plaintext(self, plaintext):
plaintext_bitstring = bytes_to_bitstring(plaintext)
return int.to_bytes(int(''.join([plaintext_bitstring[IP[i] - 1] for i in range(64)]), 2), 8, 'big')
def process_ciphertext(self, ciphertext):
ciphertext_bitstring = bytes_to_bitstring(ciphertext)
return int.to_bytes(int(''.join([ciphertext_bitstring[FP[i] - 1] for i in range(64)]), 2), 8, 'big')
def encrypt(self, plaintext: bytes) -> Bytes:
"""
Encrypts `plaintext`.
Parameters:
plaintext (bytes): Bytes-like object to be encrypted.
Returns:
Bytes: Resulting ciphertext.
"""
permuted_plaintext = self.process_plaintext(plaintext)
result = FeistelNetwork.encrypt(self, self.key, permuted_plaintext)
return Bytes(self.process_ciphertext(result))
def decrypt(self, ciphertext: bytes) -> Bytes:
"""
Decrypts `ciphertext`.
Parameters:
ciphertext (bytes): Bytes-like object to be decrypted.
Returns:
Bytes: Resulting plaintext.
"""
permuted_ciphertext = self.process_plaintext(ciphertext)
result = FeistelNetwork.decrypt(self, self.key, permuted_ciphertext)
return Bytes(self.process_ciphertext(result))
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/block_ciphers/des.py
| 0.794544 | 0.372534 |
des.py
|
pypi
|
from samson.utilities.bytes import Bytes
from samson.utilities.manipulation import left_rotate, right_rotate
from samson.core.primitives import BlockCipher, Primitive
from samson.core.metadata import SizeType, SizeSpec
from samson.ace.decorators import register_primitive
import math
P_w = [0xB7E1, 0xB7E15163, 0xB7E151628AED2A6B]
Q_w = [0x9E37, 0x9E3779B9, 0x9E3779B97F4A7C15]
# https://en.wikipedia.org/wiki/RC5#Algorithm
@register_primitive()
class RC5(BlockCipher):
"""
Structure: Feistel Network
Key size: 0-2040 bits
Block size: 32, 64, 128 bits
"""
KEY_SIZE = SizeSpec(size_type=SizeType.RANGE, sizes=range(0, 2041))
BLOCK_SIZE = SizeSpec(size_type=SizeType.RANGE, sizes=[32, 64, 128])
def __init__(self, key: bytes, num_rounds: int=12, block_size: int=128):
"""
Parameters:
key (bytes): Bytes-like object to key the cipher.
num_rounds (int): Number of rounds to perform.
block_size (int): The desired block size in bits.
"""
Primitive.__init__(self)
if not block_size in [32, 64, 128]:
raise ValueError("Invalid block size: must be 32, 64, or 128 bits")
self.key = Bytes.wrap(key)
self.num_rounds = num_rounds
self.block_size = block_size // 2
self.mod = 2 ** self.block_size
self.S = self._key_expansion()
def __reprdir__(self):
return ['key', 'num_rounds', 'block_size', 'S']
def _key_expansion(self):
b = len(self.key)
u = self.block_size // 8
t = 2 * (self.num_rounds + 1)
if b == 0:
c = 1
elif b % u:
self.key = self.key.zfill(u - b % u + b)
b = len(self.key)
c = b // u
else:
c = b // u
const_idx = int(math.log(self.block_size, 2) - 4)
if b == 0:
L = [0]
else:
L = self.key.chunk(b // c)
for i in range(b - 1, -1, -1):
L[i // u] = Bytes.wrap(L[i // u] << 8).int() + self.key[i]
S = [(P_w[const_idx] + (Q_w[const_idx] * i)) % self.mod for i in range(t)]
i = j = 0
A = B = 0
for _ in range(3 * max(t, c)):
A = S[i] = left_rotate((S[i] + A + B), 3, bits=self.block_size)
B = L[j] = left_rotate((L[j] + A + B), (A + B) % self.block_size, bits=self.block_size)
i = (i + 1) % t
j = (j + 1) % c
return S
def encrypt(self, plaintext: bytes) -> Bytes:
"""
Encrypts `plaintext`.
Parameters:
plaintext (bytes): Bytes-like object to be encrypted.
Returns:
Bytes: Resulting ciphertext.
"""
plaintext = Bytes.wrap(plaintext).zfill(self.block_size // 4)
A = plaintext[self.block_size // 8:].int()
B = plaintext[:self.block_size // 8].int()
A = (A + self.S[0]) % self.mod
B = (B + self.S[1]) % self.mod
for i in range(1, self.num_rounds + 1):
A = (left_rotate(A ^ B, B % self.block_size, bits=self.block_size) + self.S[2*i]) % self.mod
B = (left_rotate(B ^ A, A % self.block_size, bits=self.block_size) + self.S[2*i + 1]) % self.mod
return (Bytes(A, 'little').zfill(self.block_size // 8) + Bytes(B, 'little').zfill(self.block_size // 8))
def decrypt(self, ciphertext: bytes) -> Bytes:
"""
Decrypts `ciphertext`.
Parameters:
ciphertext (bytes): Bytes-like object to be decrypted.
Returns:
Bytes: Resulting plaintext.
"""
ciphertext = Bytes.wrap(ciphertext).zfill(self.block_size // 4)
A = ciphertext[:self.block_size // 8].int()
B = ciphertext[self.block_size // 8:].int()
for i in range(self.num_rounds, 0, -1):
B = right_rotate((B - self.S[2*i + 1]) % self.mod, A % self.block_size, bits=self.block_size) ^ A
A = right_rotate((A - self.S[2*i]) % self.mod, B % self.block_size, bits=self.block_size) ^ B
A = (A - self.S[0]) % self.mod
B = (B - self.S[1]) % self.mod
return Bytes((Bytes(A, 'little').zfill(self.block_size // 8) + Bytes(B, 'little').zfill(self.block_size // 8)).int()).zfill(self.block_size // 4)
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/block_ciphers/rc5.py
| 0.794664 | 0.351923 |
rc5.py
|
pypi
|
from samson.utilities.bytes import Bytes
from samson.utilities.manipulation import left_rotate
from samson.utilities.bitstring import Bitstring
from samson.core.primitives import BlockCipher, Primitive
from samson.core.metadata import ConstructionType
from samson.ace.decorators import register_primitive
# https://www.cl.cam.ac.uk/~rja14/Papers/serpent.pdf
# https://www.cl.cam.ac.uk/~fms27/serpent/serpent.py.html
IP_TABLE = [
0, 32, 64, 96, 1, 33, 65, 97, 2, 34, 66, 98, 3, 35, 67, 99,
4, 36, 68, 100, 5, 37, 69, 101, 6, 38, 70, 102, 7, 39, 71, 103,
8, 40, 72, 104, 9, 41, 73, 105, 10, 42, 74, 106, 11, 43, 75, 107,
12, 44, 76, 108, 13, 45, 77, 109, 14, 46, 78, 110, 15, 47, 79, 111,
16, 48, 80, 112, 17, 49, 81, 113, 18, 50, 82, 114, 19, 51, 83, 115,
20, 52, 84, 116, 21, 53, 85, 117, 22, 54, 86, 118, 23, 55, 87, 119,
24, 56, 88, 120, 25, 57, 89, 121, 26, 58, 90, 122, 27, 59, 91, 123,
28, 60, 92, 124, 29, 61, 93, 125, 30, 62, 94, 126, 31, 63, 95, 127,
]
FP_TABLE = [
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60,
64, 68, 72, 76, 80, 84, 88, 92, 96, 100, 104, 108, 112, 116, 120, 124,
1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53, 57, 61,
65, 69, 73, 77, 81, 85, 89, 93, 97, 101, 105, 109, 113, 117, 121, 125,
2, 6, 10, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50, 54, 58, 62,
66, 70, 74, 78, 82, 86, 90, 94, 98, 102, 106, 110, 114, 118, 122, 126,
3, 7, 11, 15, 19, 23, 27, 31, 35, 39, 43, 47, 51, 55, 59, 63,
67, 71, 75, 79, 83, 87, 91, 95, 99, 103, 107, 111, 115, 119, 123, 127,
]
LT_TABLE = [
[16, 52, 56, 70, 83, 94, 105],
[72, 114, 125],
[2, 9, 15, 30, 76, 84, 126],
[36, 90, 103],
[20, 56, 60, 74, 87, 98, 109],
[1, 76, 118],
[2, 6, 13, 19, 34, 80, 88],
[40, 94, 107],
[24, 60, 64, 78, 91, 102, 113],
[5, 80, 122],
[6, 10, 17, 23, 38, 84, 92],
[44, 98, 111],
[28, 64, 68, 82, 95, 106, 117],
[9, 84, 126],
[10, 14, 21, 27, 42, 88, 96],
[48, 102, 115],
[32, 68, 72, 86, 99, 110, 121],
[2, 13, 88],
[14, 18, 25, 31, 46, 92, 100],
[52, 106, 119],
[36, 72, 76, 90, 103, 114, 125],
[6, 17, 92],
[18, 22, 29, 35, 50, 96, 104],
[56, 110, 123],
[1, 40, 76, 80, 94, 107, 118],
[10, 21, 96],
[22, 26, 33, 39, 54, 100, 108],
[60, 114, 127],
[5, 44, 80, 84, 98, 111, 122],
[14, 25, 100],
[26, 30, 37, 43, 58, 104, 112],
[3, 118],
[9, 48, 84, 88, 102, 115, 126],
[18, 29, 104],
[30, 34, 41, 47, 62, 108, 116],
[7, 122],
[2, 13, 52, 88, 92, 106, 119],
[22, 33, 108],
[34, 38, 45, 51, 66, 112, 120],
[11, 126],
[6, 17, 56, 92, 96, 110, 123],
[26, 37, 112],
[38, 42, 49, 55, 70, 116, 124],
[2, 15, 76],
[10, 21, 60, 96, 100, 114, 127],
[30, 41, 116],
[0, 42, 46, 53, 59, 74, 120],
[6, 19, 80],
[3, 14, 25, 100, 104, 118],
[34, 45, 120],
[4, 46, 50, 57, 63, 78, 124],
[10, 23, 84],
[7, 18, 29, 104, 108, 122],
[38, 49, 124],
[0, 8, 50, 54, 61, 67, 82],
[14, 27, 88],
[11, 22, 33, 108, 112, 126],
[0, 42, 53],
[4, 12, 54, 58, 65, 71, 86],
[18, 31, 92],
[2, 15, 26, 37, 76, 112, 116],
[4, 46, 57],
[8, 16, 58, 62, 69, 75, 90],
[22, 35, 96],
[6, 19, 30, 41, 80, 116, 120],
[8, 50, 61],
[12, 20, 62, 66, 73, 79, 94],
[26, 39, 100],
[10, 23, 34, 45, 84, 120, 124],
[12, 54, 65],
[16, 24, 66, 70, 77, 83, 98],
[30, 43, 104],
[0, 14, 27, 38, 49, 88, 124],
[16, 58, 69],
[20, 28, 70, 74, 81, 87, 102],
[34, 47, 108],
[0, 4, 18, 31, 42, 53, 92],
[20, 62, 73],
[24, 32, 74, 78, 85, 91, 106],
[38, 51, 112],
[4, 8, 22, 35, 46, 57, 96],
[24, 66, 77],
[28, 36, 78, 82, 89, 95, 110],
[42, 55, 116],
[8, 12, 26, 39, 50, 61, 100],
[28, 70, 81],
[32, 40, 82, 86, 93, 99, 114],
[46, 59, 120],
[12, 16, 30, 43, 54, 65, 104],
[32, 74, 85],
[36, 90, 103, 118],
[50, 63, 124],
[16, 20, 34, 47, 58, 69, 108],
[36, 78, 89],
[40, 94, 107, 122],
[0, 54, 67],
[20, 24, 38, 51, 62, 73, 112],
[40, 82, 93],
[44, 98, 111, 126],
[4, 58, 71],
[24, 28, 42, 55, 66, 77, 116],
[44, 86, 97],
[2, 48, 102, 115],
[8, 62, 75],
[28, 32, 46, 59, 70, 81, 120],
[48, 90, 101],
[6, 52, 106, 119],
[12, 66, 79],
[32, 36, 50, 63, 74, 85, 124],
[52, 94, 105],
[10, 56, 110, 123],
[16, 70, 83],
[0, 36, 40, 54, 67, 78, 89],
[56, 98, 109],
[14, 60, 114, 127],
[20, 74, 87],
[4, 40, 44, 58, 71, 82, 93],
[60, 102, 113],
[3, 18, 72, 114, 118, 125],
[24, 78, 91],
[8, 44, 48, 62, 75, 86, 97],
[64, 106, 117],
[1, 7, 22, 76, 118, 122],
[28, 82, 95],
[12, 48, 52, 66, 79, 90, 101],
[68, 110, 121],
[5, 11, 26, 80, 122, 126],
[32, 86, 99],
]
# The following table is necessary for the non-bitslice decryption.
LT_TABLE_INV = [
[53, 55, 72],
[1, 5, 20, 90],
[15, 102],
[3, 31, 90],
[57, 59, 76],
[5, 9, 24, 94],
[19, 106],
[7, 35, 94],
[61, 63, 80],
[9, 13, 28, 98],
[23, 110],
[11, 39, 98],
[65, 67, 84],
[13, 17, 32, 102],
[27, 114],
[1, 3, 15, 20, 43, 102],
[69, 71, 88],
[17, 21, 36, 106],
[1, 31, 118],
[5, 7, 19, 24, 47, 106],
[73, 75, 92],
[21, 25, 40, 110],
[5, 35, 122],
[9, 11, 23, 28, 51, 110],
[77, 79, 96],
[25, 29, 44, 114],
[9, 39, 126],
[13, 15, 27, 32, 55, 114],
[81, 83, 100],
[1, 29, 33, 48, 118],
[2, 13, 43],
[1, 17, 19, 31, 36, 59, 118],
[85, 87, 104],
[5, 33, 37, 52, 122],
[6, 17, 47],
[5, 21, 23, 35, 40, 63, 122],
[89, 91, 108],
[9, 37, 41, 56, 126],
[10, 21, 51],
[9, 25, 27, 39, 44, 67, 126],
[93, 95, 112],
[2, 13, 41, 45, 60],
[14, 25, 55],
[2, 13, 29, 31, 43, 48, 71],
[97, 99, 116],
[6, 17, 45, 49, 64],
[18, 29, 59],
[6, 17, 33, 35, 47, 52, 75],
[101, 103, 120],
[10, 21, 49, 53, 68],
[22, 33, 63],
[10, 21, 37, 39, 51, 56, 79],
[105, 107, 124],
[14, 25, 53, 57, 72],
[26, 37, 67],
[14, 25, 41, 43, 55, 60, 83],
[0, 109, 111],
[18, 29, 57, 61, 76],
[30, 41, 71],
[18, 29, 45, 47, 59, 64, 87],
[4, 113, 115],
[22, 33, 61, 65, 80],
[34, 45, 75],
[22, 33, 49, 51, 63, 68, 91],
[8, 117, 119],
[26, 37, 65, 69, 84],
[38, 49, 79],
[26, 37, 53, 55, 67, 72, 95],
[12, 121, 123],
[30, 41, 69, 73, 88],
[42, 53, 83],
[30, 41, 57, 59, 71, 76, 99],
[16, 125, 127],
[34, 45, 73, 77, 92],
[46, 57, 87],
[34, 45, 61, 63, 75, 80, 103],
[1, 3, 20],
[38, 49, 77, 81, 96],
[50, 61, 91],
[38, 49, 65, 67, 79, 84, 107],
[5, 7, 24],
[42, 53, 81, 85, 100],
[54, 65, 95],
[42, 53, 69, 71, 83, 88, 111],
[9, 11, 28],
[46, 57, 85, 89, 104],
[58, 69, 99],
[46, 57, 73, 75, 87, 92, 115],
[13, 15, 32],
[50, 61, 89, 93, 108],
[62, 73, 103],
[50, 61, 77, 79, 91, 96, 119],
[17, 19, 36],
[54, 65, 93, 97, 112],
[66, 77, 107],
[54, 65, 81, 83, 95, 100, 123],
[21, 23, 40],
[58, 69, 97, 101, 116],
[70, 81, 111],
[58, 69, 85, 87, 99, 104, 127],
[25, 27, 44],
[62, 73, 101, 105, 120],
[74, 85, 115],
[3, 62, 73, 89, 91, 103, 108],
[29, 31, 48],
[66, 77, 105, 109, 124],
[78, 89, 119],
[7, 66, 77, 93, 95, 107, 112],
[33, 35, 52],
[0, 70, 81, 109, 113],
[82, 93, 123],
[11, 70, 81, 97, 99, 111, 116],
[37, 39, 56],
[4, 74, 85, 113, 117],
[86, 97, 127],
[15, 74, 85, 101, 103, 115, 120],
[41, 43, 60],
[8, 78, 89, 117, 121],
[3, 90],
[19, 78, 89, 105, 107, 119, 124],
[45, 47, 64],
[12, 82, 93, 121, 125],
[7, 94],
[0, 23, 82, 93, 109, 111, 123],
[49, 51, 68],
[1, 16, 86, 97, 125],
[11, 98],
[4, 27, 86, 97, 113, 115, 127],
]
SBOX = [{'0110': '1010', '0111': '1001', '0000': '1100', '0001': '0111', '0011': '1110', '0010': '0101', '0101': '0010', '0100': '1111', '1111': '0011', '1110': '1101', '1100': '1000', '1101': '0100', '1010': '0110', '1011': '0000', '1001': '1011', '1000': '0001'}, {'0110': '1010', '0111': '1100', '0000': '1111', '0001': '1000', '0011': '0110', '0010': '1001', '0101': '0111', '0100': '0100', '1111': '0010', '1110': '0101', '1100': '1110', '1101': '0001', '1010': '0000', '1011': '1011', '1001': '1101', '1000': '0011'}, {'0110': '0101', '0111': '1010', '0000': '0001', '0001': '1011', '0011': '0000', '0010': '1100', '0101': '0111', '0100': '1110', '1111': '0100', '1110': '1111', '1100': '1001', '1101': '0010', '1010': '0011', '1011': '1101', '1001': '1000', '1000': '0110'}, {'0110': '0110', '0111': '1010', '0000': '0000', '0001': '1011', '0011': '0101', '0010': '0011', '0101': '0100', '0100': '1101', '1111': '0111', '1110': '1100', '1100': '0001', '1101': '0010', '1010': '1001', '1011': '1110', '1001': '1000', '1000': '1111'}, {'0110': '1101', '0111': '1110', '0000': '1000', '0001': '0100', '0011': '1001', '0010': '0011', '0101': '0010', '0100': '0001', '1111': '1011', '1110': '0110', '1100': '1100', '1101': '0101', '1010': '0000', '1011': '0111', '1001': '1010', '1000': '1111'}, {'0110': '1001', '0111': '1110', '0000': '1111', '0001': '0000', '0011': '1011', '0010': '0010', '0101': '0111', '0100': '0100', '1111': '1000', '1110': '0011', '1100': '1101', '1101': '0001', '1010': '0101', '1011': '0110', '1001': '1100', '1000': '1010'}, {'0110': '0110', '0111': '0101', '0000': '1110', '0001': '0111', '0011': '1011', '0010': '0001', '0101': '1000', '0100': '0011', '1111': '0000', '1110': '1101', '1100': '1010', '1101': '1111', '1010': '0010', '1011': '1100', '1001': '1001', '1000': '0100'}, {'0110': '0100', '0111': '1010', '0000': '1000', '0001': '1110', '0011': '1001', '0010': '0111', '0101': '0011', '0100': '1111', '1111': '0110', '1110': '1101', '1100': '0000', '1101': '0101', '1010': '0001', '1011': '1100', '1001': '0010', '1000': '1011'}]
SBOX_INV = [{'0110': '1010', '0111': '0001', '0000': '1011', '0001': '1000', '0011': '1111', '0010': '0101', '0101': '0010', '0100': '1101', '1111': '0100', '1110': '0011', '1100': '0000', '1101': '1110', '1010': '0110', '1011': '1001', '1001': '0111', '1000': '1100'}, {'0110': '0011', '0111': '0101', '0000': '1010', '0001': '1101', '0011': '1000', '0010': '1111', '0101': '1110', '0100': '0100', '1111': '0000', '1110': '1100', '1100': '0111', '1101': '1001', '1010': '0110', '1011': '1011', '1001': '0010', '1000': '0001'}, {'0110': '1000', '0111': '0101', '0000': '0011', '0001': '0000', '0011': '1010', '0010': '1101', '0101': '0110', '0100': '1111', '1111': '1110', '1110': '0100', '1100': '0010', '1101': '1011', '1010': '0111', '1011': '0001', '1001': '1100', '1000': '1001'}, {'0110': '0110', '0111': '1111', '0000': '0000', '0001': '1100', '0011': '0010', '0010': '1101', '0101': '0011', '0100': '0101', '1111': '1000', '1110': '1011', '1100': '1110', '1101': '0100', '1010': '0111', '1011': '0001', '1001': '1010', '1000': '1001'}, {'0110': '1110', '0111': '1011', '0000': '1010', '0001': '0100', '0011': '0010', '0010': '0101', '0101': '1101', '0100': '0001', '1111': '1000', '1110': '0111', '1100': '1100', '1101': '0110', '1010': '1001', '1011': '1111', '1001': '0011', '1000': '0000'}, {'0110': '1011', '0111': '0101', '0000': '0001', '0001': '1101', '0011': '1110', '0010': '0010', '0101': '1010', '0100': '0100', '1111': '0000', '1110': '0111', '1100': '1001', '1101': '1100', '1010': '1000', '1011': '0011', '1001': '0110', '1000': '1111'}, {'0110': '0110', '0111': '0001', '0000': '1111', '0001': '0010', '0011': '0100', '0010': '1010', '0101': '0111', '0100': '1000', '1111': '1101', '1110': '0000', '1100': '1011', '1101': '1110', '1010': '1100', '1011': '0011', '1001': '1001', '1000': '0101'}, {'0110': '1111', '0111': '0010', '0000': '1100', '0001': '1010', '0011': '0101', '0010': '1001', '0101': '1101', '0100': '0110', '1111': '0100', '1110': '0001', '1100': '1011', '1101': '1110', '1010': '0111', '1011': '1000', '1001': '0011', '1000': '0000'}]
PHI = 0x9e3779b9
ROUNDS = 32
@register_primitive()
class Serpent(BlockCipher):
"""
Structure: Substitution–permutation network
Key size: 128, 192, 256 bits
Block size: 128 bits
"""
CONSTRUCTION_TYPES = [ConstructionType.SUBSTITUTION_PERMUTATION_NETWORK]
def __init__(self, key: bytes):
"""
Parameters:
key (bytes): Bytes-like object to key the cipher.
"""
Primitive.__init__(self)
self.key = Bytes(key, byteorder='big')
self._stretch_key()
self.key = Bytes(self.key.int(), 'little').zfill(32)
self.K, self.K_hat = self.make_subkeys()
def __reprdir__(self):
return ['key', 'K', 'K_hat']
def _stretch_key(self):
if len(self.key) != 32:
self.key = Bitstring('1', 'big', auto_fill=False).zfill((32 - len(self.key)) * 8).bytes() + self.key
def make_subkeys(self):
w = {}
for i, chunk in enumerate(self.key.chunk(4)[::-1]):
w[i - 8] = chunk[::-1].int()
for i in range(132):
w[i] = (left_rotate(w[i-8] ^ w[i-5] ^ w[i-3] ^ w[i-1] ^ PHI ^ i, 11))
w = {i: Bitstring(val, 'little', auto_fill=False)[::-1] for i, val in w.items()}
k = {}
for i in range(ROUNDS + 1):
sbox = (ROUNDS + 3 - i) % ROUNDS
for h in range(4):
k[h + 4 * i] = Bitstring("", 'little', auto_fill=False)
for j in range(ROUNDS):
s_in = ''.join([str(Bitstring(w[h+4*i], 'little', auto_fill=False).zfill(32)[j]) for h in range(4)])
s_out = Bitstring(SBOX[sbox % len(SBOX)][s_in], 'little', auto_fill=False)
for h in range(4):
k[h + 4 * i] += s_out[h]
K = []
for i in range(ROUNDS + 1):
K.append(k[4*i] + k[4*i+1] + k[4*i+2] + k[4*i+3])
K_hat = []
for i in range(ROUNDS + 1):
K_hat.append(self.IP(K[i]))
return K, K_hat
def _apply_sbox(self, box_num, bitstring, sbox_table):
result = ""
for i in range(32):
result += sbox_table[box_num % len(sbox_table)][bitstring[i*4:(i+1)*4]]
return result
def S_hat(self, box_num, bitstring):
return self._apply_sbox(box_num, bitstring, SBOX)
def S_hat_inv(self, box_num, bitstring):
return self._apply_sbox(box_num, bitstring, SBOX_INV)
def _apply_LT(self, bitstring, lt_table):
result = ""
for i in range(len(lt_table)):
outbit = Bitstring('0', 'little', auto_fill=False)
for j in lt_table[i]:
outbit ^= bitstring[j]
result += outbit
return result
def LT(self, bitstring):
return self._apply_LT(bitstring, LT_TABLE)
def LT_inv(self, bitstring):
return self._apply_LT(bitstring, LT_TABLE_INV)
def R(self, i, B_hat_i):
S_hat_i = self.S_hat(i, B_hat_i ^ self.K_hat[i])
if i <= (ROUNDS - 2):
B_hat_i_1 = self.LT(S_hat_i)
else:
B_hat_i_1 = S_hat_i ^ self.K_hat[ROUNDS]
return B_hat_i_1
def R_inv(self, i, B_hat_i_1):
if i <= (ROUNDS - 2):
S_hat_i = self.LT_inv(B_hat_i_1)
else:
S_hat_i = B_hat_i_1 ^ self.K_hat[ROUNDS]
B_hat_i = self.S_hat_inv(i, S_hat_i) ^ self.K_hat[i]
return B_hat_i
def _apply_permutation(self, perm_table, bitstring):
result = ""
for i in range(len(perm_table)):
result += bitstring[perm_table[i]]
return result
def IP(self, bitstring):
return self._apply_permutation(IP_TABLE, bitstring)
def FP(self, bitstring):
return self._apply_permutation(FP_TABLE, bitstring)
def encrypt(self, plaintext: bytes) -> Bytes:
"""
Encrypts `plaintext`.
Parameters:
plaintext (bytes): Bytes-like object to be encrypted.
Returns:
Bytes: Resulting ciphertext.
"""
plaintext_formatted = Bitstring.wrap(plaintext, 'little', auto_fill=False)[::-1].zfill(128)
B_hat = self.IP(plaintext_formatted)
for i in range(ROUNDS):
B_hat = self.R(i, B_hat)
# Attempt to preserve the user's sanity
little_endian_ct = self.FP(B_hat)[::-1]
return Bytes(little_endian_ct.int(), 'big').zfill(16)
def decrypt(self, ciphertext: bytes) -> Bytes:
"""
Decrypts `ciphertext`.
Parameters:
ciphertext (bytes): Bytes-like object to be decrypted.
Returns:
Bytes: Resulting plaintext.
"""
ciphertext_formatted = Bitstring.wrap(ciphertext, 'little', auto_fill=False)[::-1].zfill(128)
B_hat = self.IP(ciphertext_formatted)
for i in range(ROUNDS - 1, -1, -1):
B_hat = self.R_inv(i, B_hat)
# Attempt to preserve the user's sanity
little_endian_pt = Bitstring(self.FP(B_hat)[::-1], 'little', auto_fill=False)
return Bytes(little_endian_pt.int(), 'big').zfill(16)
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/block_ciphers/serpent.py
| 0.544438 | 0.181444 |
serpent.py
|
pypi
|
from samson.utilities.manipulation import get_blocks
from samson.utilities.bytes import Bytes
from samson.padding.pkcs7 import PKCS7
from samson.ace.decorators import has_exploit, register_primitive
from samson.attacks.cbc_padding_oracle_attack import CBCPaddingOracleAttack
from samson.core.primitives import EncryptionAlg, BlockCipherMode, Primitive
from samson.core.metadata import EphemeralType, EphemeralSpec, SizeType, SizeSpec, FrequencyType
@has_exploit(CBCPaddingOracleAttack)
@register_primitive()
class CBC(BlockCipherMode):
"""Cipherblock chaining block cipher mode."""
EPHEMERAL = EphemeralSpec(ephemeral_type=EphemeralType.IV, size=SizeSpec(size_type=SizeType.DEPENDENT, selector=lambda block_mode: block_mode.cipher.BLOCK_SIZE))
USAGE_FREQUENCY = FrequencyType.PROLIFIC
def __init__(self, cipher: EncryptionAlg, iv: bytes):
"""
Parameters:
cipher (EncryptionAlg): Instantiated encryption algorithm.
iv (bytes): Bytes-like initialization vector.
"""
Primitive.__init__(self)
self.cipher = cipher
self.iv = iv
self.padder = PKCS7(self.cipher.block_size)
def encrypt(self, plaintext: bytes, pad: bool=True) -> Bytes:
"""
Encrypts `plaintext`.
Parameters:
plaintext (bytes): Bytes-like object to be encrypted.
pad (bool): Pads the plaintext with PKCS7.
Returns:
Bytes: Resulting ciphertext.
"""
plaintext = Bytes.wrap(plaintext)
if pad:
plaintext = self.padder.pad(plaintext)
if len(plaintext) % self.cipher.block_size != 0:
raise ValueError("Plaintext is not a multiple of the block size")
ciphertext = Bytes(b'')
last_block = self.iv
for block in get_blocks(plaintext, self.cipher.block_size):
enc_block = self.cipher.encrypt(bytes(last_block ^ block))
ciphertext += enc_block
last_block = enc_block
return ciphertext
def decrypt(self, ciphertext: bytes, unpad: bool=True) -> Bytes:
"""
Decrypts `ciphertext`.
Parameters:
ciphertext (bytes): Bytes-like object to be decrypted.
unpad (bool): Unpads the plaintext with PKCS7.
Returns:
Bytes: Resulting plaintext.
"""
plaintext = b''
ciphertext = Bytes.wrap(ciphertext)
self.check_ciphertext_length(ciphertext)
last_block = self.iv
for block in get_blocks(ciphertext, self.cipher.block_size):
enc_block = last_block ^ Bytes.wrap(self.cipher.decrypt(block))
plaintext += enc_block
last_block = block
if unpad:
plaintext = self.padder.unpad(plaintext)
return plaintext
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/block_ciphers/modes/cbc.py
| 0.859295 | 0.176352 |
cbc.py
|
pypi
|
from samson.utilities.manipulation import get_blocks
from samson.utilities.bytes import Bytes
from samson.core.primitives import EncryptionAlg, StreamingBlockCipherMode, Primitive
from samson.core.metadata import EphemeralType, EphemeralSpec, SizeType, SizeSpec
from samson.ace.decorators import register_primitive
@register_primitive()
class CFB(StreamingBlockCipherMode):
"""Cipher feedback block cipher mode."""
EPHEMERAL = EphemeralSpec(ephemeral_type=EphemeralType.NONCE, size=SizeSpec(size_type=SizeType.DEPENDENT, selector=lambda block_mode: block_mode.cipher.BLOCK_SIZE, typical=[128]))
def __init__(self, cipher: EncryptionAlg, iv: bytes):
"""
Parameters:
cipher (EncryptionAlg): Instantiated encryption algorithm.
iv (bytes): Bytes-like initialization vector.
"""
Primitive.__init__(self)
self.cipher = cipher
self.iv = iv
def encrypt(self, plaintext: bytes) -> Bytes:
"""
Encrypts `plaintext`.
Parameters:
plaintext (bytes): Bytes-like object to be encrypted.
Returns:
Bytes: Resulting ciphertext.
"""
ciphertext = b''
plaintext = Bytes.wrap(plaintext)
last_block = self.iv
for block in get_blocks(plaintext, self.cipher.block_size, allow_partials=True):
enc_block = self.cipher.encrypt(bytes(last_block))[:len(block)] ^ block
ciphertext += enc_block
last_block = enc_block
return ciphertext
def decrypt(self, ciphertext: bytes) -> Bytes:
"""
Decrypts `ciphertext`.
Parameters:
ciphertext (bytes): Bytes-like object to be decrypted.
Returns:
Bytes: Resulting plaintext.
"""
plaintext = b''
ciphertext = Bytes.wrap(ciphertext)
last_block = self.iv
for block in get_blocks(ciphertext, self.cipher.block_size, allow_partials=True):
enc_block = self.cipher.encrypt(bytes(last_block))[:len(block)] ^ block
plaintext += enc_block
last_block = block
return plaintext
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/block_ciphers/modes/cfb.py
| 0.880919 | 0.233062 |
cfb.py
|
pypi
|
from samson.utilities.bytes import Bytes
from samson.kdfs.s2v import dbl
from samson.core.primitives import EncryptionAlg, StreamingBlockCipherMode, Primitive, AuthenticatedCipher
from samson.core.metadata import SizeType, SizeSpec, EphemeralType, EphemeralSpec
from samson.ace.decorators import register_primitive
def triple(bytestring):
return bytestring ^ dbl(bytestring)
@register_primitive()
class OCB2(StreamingBlockCipherMode, AuthenticatedCipher):
"""
Offset codebook version 2 block cipher mode.
http://web.cs.ucdavis.edu/~rogaway/papers/draft-krovetz-ocb-00.txt
"""
EPHEMERAL = EphemeralSpec(ephemeral_type=EphemeralType.NONCE, size=SizeSpec(size_type=SizeType.DEPENDENT, selector=lambda block_mode: block_mode.cipher.BLOCK_SIZE, typical=[128]))
AUTH_TAG_SIZE = SizeSpec(size_type=SizeType.DEPENDENT, selector=lambda block_mode: block_mode.cipher.BLOCK_SIZE, typical=[128])
def __init__(self, cipher: EncryptionAlg):
"""
Parameters:
cipher (EncryptionAlg): Instantiated encryption algorithm.
"""
Primitive.__init__(self)
self.cipher = cipher
# TODO: We already have a PMAC class, but it doesn't seem to produce
# the same results. Is there some trivial tweak we can do so we don't
# have to have two implementations?
def internal_pmac(self, data):
data = Bytes.wrap(data)
data_chunks = data.chunk(self.cipher.block_size, allow_partials=True)
offset = self.cipher.encrypt(Bytes(b'').zfill(self.cipher.block_size))
offset = triple(offset)
offset = triple(offset)
checksum = Bytes(b'').zfill(self.cipher.block_size)
for i in range(len(data_chunks) - 1):
offset = dbl(offset)
checksum ^= self.cipher.encrypt(offset ^ data_chunks[i])
offset = dbl(offset)
M_last = data_chunks[-1]
if len(M_last) % self.cipher.block_size == 0:
offset = triple(offset)
checksum ^= M_last
else:
M_last += b'\x80'
M_last = (M_last + (b'\x00' * (self.cipher.block_size - len(M_last))))
checksum ^= M_last
offset = triple(offset)
offset = triple(offset)
return self.cipher.encrypt(offset ^ checksum)
def encrypt(self, nonce: bytes, plaintext: bytes, auth_data: bytes=None) -> (Bytes, Bytes):
"""
Encrypts `plaintext`.
Parameters:
plaintext (bytes): Bytes-like object to be encrypted.
Returns:
Bytes: Resulting ciphertext.
"""
plaintext = Bytes.wrap(plaintext)
message_chunks = plaintext.chunk(self.cipher.block_size, allow_partials=True)
offset = self.cipher.encrypt(nonce)
checksum = Bytes(b'').zfill(self.cipher.block_size)
if not message_chunks:
message_chunks = [plaintext]
ciphertext = Bytes(b'')
for i in range(len(message_chunks) - 1):
offset = dbl(offset)
checksum ^= message_chunks[i]
xoffset = self.cipher.encrypt(offset ^ message_chunks[i])
ciphertext += offset ^ xoffset
offset = dbl(offset)
M_last = message_chunks[-1]
last_len = len(M_last)
padding = self.cipher.encrypt(Bytes(last_len * 8).zfill(self.cipher.block_size) ^ offset)
ciphertext += M_last ^ padding[:last_len]
checksum ^= M_last + padding[last_len:]
offset = triple(offset)
tag = self.cipher.encrypt(checksum ^ offset)
if auth_data:
tag ^= self.internal_pmac(auth_data)
return tag, ciphertext
def decrypt(self, nonce: bytes, ciphertext: bytes, auth_data: bytes=None, verify: bool=True) -> Bytes:
"""
Decrypts `ciphertext`.
Parameters:
ciphertext (bytes): Bytes-like object to be decrypted.
Returns:
Bytes: Resulting plaintext.
"""
given_tag, ciphertext = ciphertext
ciphertext = Bytes.wrap(ciphertext)
message_chunks = ciphertext.chunk(self.cipher.block_size, allow_partials=True)
offset = self.cipher.encrypt(nonce)
checksum = Bytes(b'').zfill(self.cipher.block_size)
if not message_chunks:
message_chunks = [ciphertext]
plaintext = Bytes(b'')
for i in range(len(message_chunks) - 1):
offset = dbl(offset)
pt_chunk = self.cipher.decrypt(offset ^ message_chunks[i]) ^ offset
checksum ^= pt_chunk
plaintext += pt_chunk
offset = dbl(offset)
M_last = message_chunks[-1]
last_len = len(M_last)
padding = self.cipher.encrypt(Bytes(last_len * 8).zfill(self.cipher.block_size) ^ offset)
M_last ^= padding[:last_len]
plaintext += M_last
checksum ^= M_last + padding[last_len:]
offset = triple(offset)
tag = self.cipher.encrypt(checksum ^ offset)
if auth_data:
tag ^= self.internal_pmac(auth_data)
if verify:
self.verify_tag(tag, given_tag)
return plaintext
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/block_ciphers/modes/ocb2.py
| 0.710729 | 0.353317 |
ocb2.py
|
pypi
|
from samson.utilities.bytes import Bytes
from samson.core.metadata import UsageType
from samson.core.primitives import EncryptionAlg, BlockCipherMode, Primitive
from samson.ace.decorators import register_primitive
from types import FunctionType
@register_primitive()
class XTS(BlockCipherMode):
"""
Xor-encrypt-xor-based tweaked-codebook mode with ciphertext stealing.
https://en.wikipedia.org/wiki/Disk_encryption_theory#XTS
This is basically XEX with conditional CTS. Padding the plaintext to the 16-byte boundary
should, therefore, result in a correct execution of XEX.
https://en.wikipedia.org/wiki/Disk_encryption_theory#Xor%E2%80%93encrypt%E2%80%93xor_(XEX)
"""
USAGE_TYPE = UsageType.OTHER
def __init__(self, cipher: EncryptionAlg, sector_encryptor: FunctionType):
"""
Parameters:
cipher (EncryptionAlg): Instantiated encryption algorithm.
sector_encryptor (func): Function that takes in a plaintext and returns a ciphertext.
"""
Primitive.__init__(self)
self.cipher = cipher
self.sector_encryptor = sector_encryptor
def __reprdir__(self):
return ['cipher', 'sector_encryptor']
def _xts(self, in_bytes: bytes, tweak: int, func: FunctionType, reverse_cts: bool=False) -> Bytes:
in_bytes = Bytes.wrap(in_bytes)
tweak_bytes = Bytes(tweak)
X = self.sector_encryptor(tweak_bytes + b'\x00' * (16 - len(tweak_bytes)))[::-1].int()
out_bytes = Bytes(b'')
byte_chunks = in_bytes.chunk(16, allow_partials=True)
for block in byte_chunks:
if len(block) == 16:
if X >> 128:
X ^= 0x100000000000000000000000000000087
X = Bytes(X, 'little').zfill(16)
out_bytes += func(block ^ X) ^ X
X = X.int()
X <<= 1
else:
curr_X = X
if X >> 128:
X ^= 0x100000000000000000000000000000087
# Decryption needs to reverse the ordering of the X's.
# Here I just throw out the last block, use the most recent X,
# and then backpedal X.
if reverse_cts:
out_bytes = out_bytes[:-16]
X = Bytes(X, 'little').zfill(16)
last_chunk = func(byte_chunks[-2] ^ X) ^ X
X = curr_X >> 1
else:
out_bytes, last_chunk = out_bytes[:-16], out_bytes[-16:]
stolen, left_over = last_chunk[len(block):], last_chunk[:len(block)]
padded_block = block + stolen
X = Bytes(X, 'little').zfill(16)
out_bytes += (func(padded_block ^ X) ^ X) + left_over
return out_bytes
def encrypt(self, plaintext: bytes, tweak: int) -> Bytes:
"""
Encrypts `plaintext`.
Parameters:
plaintext (bytes): Bytes-like object to be encrypted.
tweak (int): Number that 'tweaks' the permutation.
Returns:
Bytes: Resulting ciphertext.
"""
return self._xts(plaintext, tweak, self.cipher.encrypt, reverse_cts=False)
def decrypt(self, ciphertext: bytes, tweak: int) -> Bytes:
"""
Decrypts `ciphertext`.
Parameters:
plaintext (bytes): Bytes-like object to be decrypted.
tweak (int): Number that 'tweaks' the permutation.
Returns:
Bytes: Resulting plaintext.
"""
return self._xts(ciphertext, tweak, self.cipher.decrypt, reverse_cts=True)
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/block_ciphers/modes/xts.py
| 0.809201 | 0.40204 |
xts.py
|
pypi
|
from samson.block_ciphers.modes.ctr import CTR
from samson.kdfs.s2v import S2V
from samson.utilities.bytes import Bytes
from samson.core.primitives import EncryptionAlg, StreamingBlockCipherMode, Primitive, AuthenticatedCipher
from samson.ace.decorators import register_primitive
@register_primitive()
class SIV(StreamingBlockCipherMode, AuthenticatedCipher):
"""
SIV cipher mode, RFC5297 (https://tools.ietf.org/html/rfc5297)
"""
def __init__(self, s2v_key: bytes, cipher: EncryptionAlg):
"""
Parameters:
s2v_key (bytes): Key used for generating/verifying S2V IV (i.e. `k2` in RFC5297).
cipher (EncryptionAlg): Instantiated encryption algorithm.
"""
Primitive.__init__(self)
self.s2v_key = s2v_key
self.cipher = cipher
def encrypt(self, plaintext: bytes, additional_data: list=[]) -> Bytes:
"""
Encrypts `plaintext`.
Parameters:
plaintext (bytes): Bytes-like object to be encrypted.
additional_data (list): Additional data to be authenticated (e.g. headers).
Returns:
Bytes: Resulting IV + ciphertext.
"""
iv = S2V(self.cipher.__class__(self.s2v_key)).derive(*additional_data, plaintext)
ctr = CTR(self.cipher, Bytes(b''))
ctr.counter = iv.int() & 340282366920938463454151235392765951999
return iv + ctr.encrypt(plaintext)
def decrypt(self, ciphertext: bytes, additional_data: list=[], verify: bool=True) -> Bytes:
"""
Decrypts `ciphertext`.
Parameters:
ciphertext (bytes): Bytes-like object to be decrypted.
additional_data (list): Additional data to be authenticated (e.g. headers).
verify (bool): Whether or not to verify the authentication tag.
Returns:
Bytes: Resulting plaintext.
"""
ciphertext = Bytes.wrap(ciphertext)
iv, ct = ciphertext[:16], ciphertext[16:]
ctr = CTR(self.cipher, Bytes(b''))
ctr.counter = iv.int() & 340282366920938463454151235392765951999
plaintext = ctr.decrypt(ct)
if verify:
tag = S2V(self.cipher.__class__(self.s2v_key)).derive(*additional_data, plaintext)
self.verify_tag(iv, tag)
return plaintext
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/block_ciphers/modes/siv.py
| 0.875707 | 0.277957 |
siv.py
|
pypi
|
from samson.utilities.bytes import Bytes
from samson.core.primitives import EncryptionAlg, StreamingBlockCipherMode, Primitive
from samson.core.metadata import EphemeralType, EphemeralSpec, SizeType, SizeSpec, FrequencyType
from samson.ace.decorators import register_primitive
from math import ceil
@register_primitive()
class CTR(StreamingBlockCipherMode):
"""Counter block cipher mode."""
# TODO: This nonce is a RANGE that is DEPENDENT on BLOCK_SIZE
EPHEMERAL = EphemeralSpec(ephemeral_type=EphemeralType.NONCE, size=SizeSpec(size_type=SizeType.DEPENDENT, selector=lambda block_mode: block_mode.cipher.BLOCK_SIZE, typical=[96]))
USAGE_FREQUENCY = FrequencyType.PROLIFIC
def __init__(self, cipher: EncryptionAlg, nonce: bytes):
"""
Parameters:
cipher (EncryptionAlg): Instantiated encryption algorithm.
nonce (bytes): Bytes-like nonce.
"""
Primitive.__init__(self)
self.cipher = cipher
self.nonce = Bytes.wrap(nonce)
self.counter = 0
self.byteorder = self.nonce.byteorder
def encrypt(self, plaintext: bytes) -> Bytes:
"""
Encrypts `plaintext`.
Parameters:
plaintext (bytes): Bytes-like object to be encrypted.
Returns:
Bytes: Resulting ciphertext.
"""
keystream = Bytes(b'')
plaintext = Bytes.wrap(plaintext)
num_blocks = ceil(len(plaintext) / self.cipher.block_size)
for _ in range(num_blocks):
keystream += self.cipher.encrypt(self.nonce + self.counter.to_bytes(self.cipher.block_size - len(self.nonce), self.byteorder))
self.counter += 1
return keystream[:len(plaintext)] ^ plaintext
def decrypt(self, ciphertext: bytes) -> Bytes:
"""
Decrypts `ciphertext`.
Parameters:
ciphertext (bytes): Bytes-like object to be decrypted.
Returns:
Bytes: Resulting plaintext.
"""
return self.encrypt(ciphertext)
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/block_ciphers/modes/ctr.py
| 0.680879 | 0.217234 |
ctr.py
|
pypi
|
from samson.utilities.bytes import Bytes
from samson.utilities.exceptions import InvalidMACException
from samson.utilities.runtime import RUNTIME
from samson.core.primitives import EncryptionAlg, BlockCipherMode, Primitive
from samson.ace.decorators import register_primitive
@register_primitive()
class KW(BlockCipherMode):
"""Key wrap cipher mode."""
# TODO: Err, how does this fit into PSL? These are already defined.
RFC3394_IV = Bytes(0xA6A6A6A6A6A6A6A6)
RFC5649_IV = Bytes(0xA65959A6)
def __init__(self, cipher: EncryptionAlg, iv: bytes=RFC3394_IV):
"""
Parameters:
cipher (EncryptionAlg): Instantiated encryption algorithm.
iv (bytes): Bytes-like initialization vector.
"""
Primitive.__init__(self)
self.cipher = cipher
self.iv = iv
def encrypt(self, plaintext: bytes, pad: bool=False) -> Bytes:
"""
Encrypts `plaintext`.
Parameters:
plaintext (bytes): Bytes-like object to be encrypted.
pad (bool): Whether or not to use RFC5649 padding.
Returns:
Bytes: Resulting ciphertext.
"""
iv = self.iv
length = len(plaintext)
plaintext = Bytes.wrap(plaintext)
if pad:
r = ((length) + 7) // 8
plaintext = plaintext + ((r * 8) - length) * b'\x00'
iv = self.iv + Bytes(length).zfill(4)
A = iv
R = plaintext.chunk(8)
n = len(R)
# RFC5649 specific
if n == 1:
return self.cipher.encrypt(iv + plaintext)
for j in range(6):
for i in range(n):
ct = self.cipher.encrypt(A + R[i])
A, R[i] = ct[:8], ct[8:]
A ^= Bytes(n * j + i + 1).zfill(len(A))
return A + b''.join(R)
def decrypt(self, ciphertext: bytes, unpad: bool=False, verify: bool=True) -> Bytes:
"""
Decrypts `ciphertext`.
Parameters:
ciphertext (bytes): Bytes-like object to be decrypted.
unpad (bool): Whether or not to unpad with RFC5649 padding.
verify (bool): Whether or not to check if the IV is correct.
Returns:
Bytes: Resulting plaintext.
"""
ciphertext = Bytes.wrap(ciphertext)
A = ciphertext[:8]
R = ciphertext[8:].chunk(8)
n = len(R)
if n == 1:
pt = self.cipher.decrypt(ciphertext)
A, plaintext = pt[:8], pt[8:]
else:
for j in reversed(range(6)):
for i in reversed(range(n)):
A ^= Bytes(n * j + i + 1).zfill(len(A))
ct = self.cipher.decrypt(A + R[i])
A, R[i] = ct[:8], ct[8:]
plaintext = b''.join(R)
if verify:
if not RUNTIME.compare_bytes(A[:len(self.iv)], self.iv):
raise InvalidMACException
if unpad:
plaintext = plaintext[:A[len(self.iv):].int()]
return Bytes.wrap(plaintext)
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/block_ciphers/modes/kw.py
| 0.604165 | 0.304171 |
kw.py
|
pypi
|
from samson.utilities.bytes import Bytes
from samson.block_ciphers.modes.ecb import ECB
from samson.core.primitives import EncryptionAlg, BlockCipherMode, Primitive
from samson.ace.decorators import register_primitive
# https://en.wikipedia.org/wiki/Ciphertext_stealing
# CTS-3
@register_primitive()
class ECBCTS(BlockCipherMode):
"""Electronic codebook with ciphertext stealing block cipher mode."""
def __init__(self, cipher: EncryptionAlg):
"""
Parameters:
cipher (EncryptionAlg): Instantiated encryption algorithm.
"""
Primitive.__init__(self)
self.underlying_mode = ECB(cipher)
def encrypt(self, plaintext: bytes) -> Bytes:
"""
Encrypts `plaintext`.
Parameters:
plaintext (bytes): Bytes-like object to be encrypted.
Returns:
Bytes: Resulting ciphertext.
"""
plaintext = Bytes.wrap(plaintext)
block_size = self.underlying_mode.cipher.block_size
pt_len = len(plaintext)
assert pt_len > block_size
pt_chunks = plaintext.chunk(block_size, allow_partials=True)
padding_len = (block_size - (pt_len % block_size)) % block_size
ciphertext_chunks = self.underlying_mode.encrypt(sum(pt_chunks[:-1]), pad=False).chunk(block_size)
padding = ciphertext_chunks[-1][-padding_len:][:padding_len]
last_block = self.underlying_mode.encrypt(pt_chunks[-1] + padding, pad=False)
return (sum(ciphertext_chunks[:-1]) + last_block + ciphertext_chunks[-1])[:pt_len]
def decrypt(self, ciphertext: bytes) -> Bytes:
"""
Decrypts `ciphertext`.
Parameters:
ciphertext (bytes): Bytes-like object to be decrypted.
Returns:
Bytes: Resulting plaintext.
"""
ciphertext = Bytes.wrap(ciphertext)
block_size = self.underlying_mode.cipher.block_size
ct_len = len(ciphertext)
ct_chunks = ciphertext.chunk(block_size, allow_partials=True)
padding_len = (block_size - (ct_len % block_size)) % block_size
D_n = self.underlying_mode.decrypt(ct_chunks[-2], unpad=False)
padding = D_n[-padding_len:][:padding_len]
return self.underlying_mode.decrypt(sum(ct_chunks[:-2]) + ct_chunks[-1] + padding + ct_chunks[-2], unpad=False)[:ct_len]
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/block_ciphers/modes/ecb_cts.py
| 0.863536 | 0.307815 |
ecb_cts.py
|
pypi
|
from samson.utilities.bytes import Bytes
from samson.block_ciphers.modes.cbc import CBC
from samson.core.primitives import EncryptionAlg, BlockCipherMode, Primitive
from samson.core.metadata import EphemeralType, EphemeralSpec, SizeType, SizeSpec
from samson.ace.decorators import register_primitive
# https://en.wikipedia.org/wiki/Ciphertext_stealing
# CTS-3
@register_primitive()
class CBCCTS(BlockCipherMode):
"""Cipherblock chaining with ciphertext stealing block cipher mode."""
EPHEMERAL = EphemeralSpec(ephemeral_type=EphemeralType.IV, size=SizeSpec(size_type=SizeType.DEPENDENT, selector=lambda block_mode: block_mode.cipher.BLOCK_SIZE))
def __init__(self, cipher: EncryptionAlg, iv: bytes):
"""
Parameters:
cipher (EncryptionAlg): Instantiated encryption algorithm.
iv (bytes): Bytes-like initialization vector.
"""
Primitive.__init__(self)
self.underlying_mode = CBC(cipher, iv)
def encrypt(self, plaintext: bytes) -> Bytes:
"""
Encrypts `plaintext`.
Parameters:
plaintext (bytes): Bytes-like object to be encrypted.
Returns:
Bytes: Resulting ciphertext.
"""
plaintext = Bytes.wrap(plaintext)
block_size = self.underlying_mode.cipher.block_size
pt_len = len(plaintext)
assert pt_len > block_size
padding_len = (block_size - (pt_len % block_size)) % block_size
ciphertext_chunks = self.underlying_mode.encrypt(plaintext + b'\x00' * (padding_len), pad=False).chunk(block_size)
return (sum(ciphertext_chunks[:-2]) + ciphertext_chunks[-1] + ciphertext_chunks[-2])[:pt_len]
def decrypt(self, ciphertext: bytes) -> Bytes:
"""
Decrypts `ciphertext`.
Parameters:
ciphertext (bytes): Bytes-like object to be decrypted.
Returns:
Bytes: Resulting plaintext.
"""
ciphertext = Bytes.wrap(ciphertext)
block_size = self.underlying_mode.cipher.block_size
ct_chunks = ciphertext.chunk(block_size, allow_partials=True)
ct_len = len(ciphertext)
padding_len = (block_size - (ct_len % block_size)) % block_size
D_n = self.underlying_mode.cipher.decrypt(ct_chunks[-2])
C_n = sum(ct_chunks[:-2]) + ct_chunks[-1] + D_n[-padding_len:][:padding_len] + ct_chunks[-2]
return self.underlying_mode.decrypt(C_n, unpad=False)[:ct_len]
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/block_ciphers/modes/cbc_cts.py
| 0.818701 | 0.24344 |
cbc_cts.py
|
pypi
|
from samson.utilities.bytes import Bytes
from samson.block_ciphers.modes.ctr import CTR
from samson.macs.cmac import CMAC
from samson.core.primitives import EncryptionAlg, StreamingBlockCipherMode, Primitive, AuthenticatedCipher
from samson.core.metadata import EphemeralType, EphemeralSpec, SizeType, SizeSpec
from samson.ace.decorators import register_primitive
@register_primitive()
class EAX(StreamingBlockCipherMode, AuthenticatedCipher):
"""
EAX block cipher mode
http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf
"""
EPHEMERAL = EphemeralSpec(ephemeral_type=EphemeralType.NONCE, size=SizeSpec(size_type=SizeType.DEPENDENT, selector=lambda block_mode: block_mode.cipher.BLOCK_SIZE))
AUTH_TAG_SIZE = SizeSpec(size_type=SizeType.DEPENDENT, selector=lambda block_mode: block_mode.cipher.BLOCK_SIZE)
def __init__(self, cipher: EncryptionAlg, nonce: bytes):
"""
Parameters:
cipher (EncryptionAlg): Instantiated encryption algorithm.
nonce (bytes): Bytes-like nonce.
"""
Primitive.__init__(self)
self.cipher = cipher
self.nonce = nonce
self.ctr = CTR(self.cipher, b'')
self.cmac = CMAC(self.cipher)
def generate_tag(self, ciphertext: bytes, auth_data: bytes) -> Bytes:
"""
Internal function. Generates a valid tag for the `ciphertext` and `auth_data`.
"""
cipher_mac = self.cmac.generate(Bytes(2).zfill(self.cipher.block_size) + ciphertext)
tag = cipher_mac ^ self.cmac.generate(Bytes(0).zfill(self.cipher.block_size) + self.nonce) ^ self.cmac.generate(Bytes(1).zfill(self.cipher.block_size) + Bytes.wrap(auth_data))
return tag
def encrypt(self, plaintext: bytes, auth_data: bytes) -> Bytes:
"""
Encrypts `plaintext`.
Parameters:
plaintext (bytes): Bytes-like object to be encrypted.
auth_data (bytes): Bytes-like additional data to be authenticated but not encrypted.
Returns:
Bytes: Resulting ciphertext.
"""
self.ctr.counter = self.cmac.generate(Bytes(0).zfill(self.cipher.block_size) + self.nonce).int()
ciphertext = self.ctr.encrypt(plaintext)
tag = self.generate_tag(ciphertext, auth_data)
return ciphertext + tag[:self.cipher.block_size]
def decrypt(self, ciphertext: bytes, auth_data: bytes, verify: bool=True) -> Bytes:
"""
Decrypts `ciphertext`.
Parameters:
ciphertext (bytes): Bytes-like object to be decrypted.
auth_data (bytes): Bytes-like additional data to be authenticated but not encrypted.
verify (bool): Whether or not to verify the authentication tag.
Returns:
Bytes: Resulting plaintext.
"""
ciphertext, given_tag = ciphertext[:-16], ciphertext[-16:]
tag = self.generate_tag(ciphertext, auth_data)
if verify:
self.verify_tag(tag, given_tag)
self.ctr.counter = self.cmac.generate(Bytes(0).zfill(self.cipher.block_size) + self.nonce).int()
plaintext = self.ctr.decrypt(ciphertext)
return plaintext
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/block_ciphers/modes/eax.py
| 0.853699 | 0.235526 |
eax.py
|
pypi
|
from samson.block_ciphers.modes.ctr import CTR
from samson.utilities.bytes import Bytes
from samson.macs.cbc_mac import CBCMAC
from samson.core.primitives import EncryptionAlg, StreamingBlockCipherMode, Primitive, AuthenticatedCipher
from samson.core.metadata import FrequencyType, SizeType, SizeSpec, EphemeralType, EphemeralSpec
from samson.ace.decorators import register_primitive
@register_primitive()
class CCM(StreamingBlockCipherMode, AuthenticatedCipher):
"""
Counter with CBC-MAC block cipher mode.
CCM is only defined for ciphers with 128 bit block size.
"""
USAGE_FREQUENCY = FrequencyType.UNUSUAL
AUTH_TAG_SIZE = SizeSpec(size_type=SizeType.RANGE, sizes=range(32, 129, 16), typical=[128])
EPHEMERAL = EphemeralSpec(ephemeral_type=EphemeralType.NONCE, size=SizeSpec(size_type=SizeType.RANGE, sizes=range(8, 97, 8), typical=[96]))
def __init__(self, cipher: EncryptionAlg, mac_len: int):
"""
Parameters:
cipher (EncryptionAlg): Instantiated encryption algorithm.
mac_len (int): Length of MAC to generate.
"""
Primitive.__init__(self)
self.cipher = cipher
self.cmac = CBCMAC(self.cipher)
self.mac_len = mac_len
self.ctr = CTR(self.cipher, b'\x00' * 16)
def _calculate_formatting_params(self, nonce: bytes, plaintext: bytes, data: bytes):
data_len = len(data)
q = 15 - len(nonce)
flags = (64 * (data_len > 0)) + 8 * (((self.mac_len) - 2) // 2) + (q - 1)
b_0 = Bytes(flags) + nonce + int.to_bytes(len(plaintext), q, 'big')
return data_len, q, flags, b_0
# https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38c.pdf
def _generate_mac(self, nonce: bytes, plaintext: bytes, data: bytes) -> bytes:
data_len, _q, _flags, b_0 = self._calculate_formatting_params(nonce, plaintext, data)
data_len_encoded = b''
if data_len > 0:
if data_len < ((2 ** 16) - (2 ** 8)):
size = 2
elif data_len < (2 ** 32):
data_len_encoded = b'\xFF\xFE'
size = 4
else:
data_len_encoded = b'\xFF\xFF'
size = 8
data_len_encoded += int.to_bytes(data_len, size, 'big')
padded_data = Bytes.wrap(data_len_encoded + data).pad_congruent_right(16)
padded_plaintext = Bytes.wrap(plaintext).pad_congruent_right(16)
T = self.cmac.generate(b_0 + padded_data + padded_plaintext, pad=False)
return T
def _generate_keystream(self, nonce: bytes, q: int, length: int) -> Bytes:
formatted_nonce = Bytes(q - 1) + nonce
self.ctr.nonce = formatted_nonce
self.ctr.counter = 0
keystream = self.ctr.encrypt(Bytes(b'').zfill(length))
return keystream
def encrypt(self, nonce: bytes, plaintext: bytes, data: bytes) -> Bytes:
"""
Encrypts `plaintext`.
Parameters:
nonce (bytes): Bytes-like nonce.
plaintext (bytes): Bytes-like object to be encrypted.
data (bytes): Bytes-like additional data to be authenticated but not encrypted.
Returns:
Bytes: Resulting ciphertext.
"""
T = self._generate_mac(nonce, plaintext, data)
_data_len, q, _flags, _b_0 = self._calculate_formatting_params(nonce, plaintext, data)
keystream = self._generate_keystream(nonce, q, len(plaintext) + 16)
return (keystream[len(T):] ^ (plaintext)) + (T ^ keystream[:len(T)])[:self.mac_len]
def decrypt(self, nonce: bytes, ciphertext: bytes, data: bytes) -> Bytes:
"""
Decrypts `ciphertext`.
Parameters:
nonce (bytes): Bytes-like nonce.
plaintext (bytes): Bytes-like object to be decrypted.
data (bytes): Bytes-like additional data to be authenticated.
Returns:
Bytes: Resulting plaintext.
"""
_data_len, q, _flags, _b_0 = self._calculate_formatting_params(nonce, ciphertext, data)
keystream = self._generate_keystream(nonce, q, len(ciphertext) + (16 - self.mac_len))
total_plaintext = (keystream[16:] + keystream[:self.mac_len]) ^ ciphertext
plaintext, mac = total_plaintext[:-self.mac_len], total_plaintext[-self.mac_len:]
T = self._generate_mac(nonce, plaintext, data)[:self.mac_len]
self.verify_tag(T, mac)
return plaintext
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/block_ciphers/modes/ccm.py
| 0.807461 | 0.321487 |
ccm.py
|
pypi
|
from samson.block_ciphers.modes.ctr import CTR
from samson.utilities.bytes import Bytes
from samson.core.primitives import EncryptionAlg, StreamingBlockCipherMode, Primitive, AuthenticatedCipher
from samson.core.metadata import EphemeralType, EphemeralSpec, SizeType, SizeSpec, FrequencyType
from samson.ace.decorators import register_primitive
# Reference
# https://github.com/tomato42/tlslite-ng/blob/master/tlslite/utils/aesgcm.py
GCM_REDUCTION_TABLE = [
0x0000, 0x1c20, 0x3840, 0x2460, 0x7080, 0x6ca0, 0x48c0, 0x54e0,
0xe100, 0xfd20, 0xd940, 0xc560, 0x9180, 0x8da0, 0xa9c0, 0xb5e0,
]
def reverse_bits(int32: int) -> int:
return int(bin(int32)[2:].zfill(4)[::-1], 2)
@register_primitive()
class GCM(StreamingBlockCipherMode, AuthenticatedCipher):
"""Galois counter mode (GCM) block cipher mode"""
EPHEMERAL = EphemeralSpec(ephemeral_type=EphemeralType.NONCE, size=SizeSpec(size_type=SizeType.SINGLE, sizes=96))
AUTH_TAG_SIZE = SizeSpec(size_type=SizeType.SINGLE, sizes=128)
USAGE_FREQUENCY = FrequencyType.PROLIFIC
def __init__(self, cipher: EncryptionAlg, H: int=None):
"""
Parameters:
cipher (EncryptionAlg): Instantiated encryption algorithm.
"""
Primitive.__init__(self)
self.cipher = cipher
self.H = H or self.cipher.encrypt(b'\x00' * 16).int()
self.ctr = CTR(self.cipher, b'\x00' * 8)
# Precompute the product table
self.product_table = [0] * 16
self.product_table[reverse_bits(1)] = self.H
for i in range(2, 16, 2):
self.product_table[reverse_bits(i)] = self.gcm_shift(self.product_table[reverse_bits(i // 2)])
self.product_table[reverse_bits(i + 1)] = self.product_table[reverse_bits(i)] ^ self.H
def __reprdir__(self):
return ['cipher', 'H', 'ctr']
def clock_ctr(self, nonce: bytes) -> Bytes:
nonce = Bytes.wrap(nonce)
if len(nonce) == 12:
self.ctr.nonce = nonce
self.ctr.counter = 1
else:
payload = nonce.pad_congruent_right(16) + (b'\x00' * 8) + Bytes(len(nonce) * 8).zfill(8)
J_0 = Bytes(self.update(0, payload)).zfill(16)
self.ctr.nonce = J_0[:15]
self.ctr.counter = J_0[-1]
return self.ctr.encrypt(Bytes(b'').zfill(16))
def encrypt(self, nonce: bytes, plaintext: bytes, data: bytes=b'') -> Bytes:
"""
Encrypts `plaintext`.
Parameters:
nonce (bytes): Bytes-like nonce.
plaintext (bytes): Bytes-like object to be encrypted.
data (bytes): Bytes-like additional data to be authenticated but not encrypted.
Returns:
Bytes: Resulting ciphertext.
"""
tag_mask = self.clock_ctr(nonce)
data = Bytes.wrap(data)
ciphertext = self.ctr.encrypt(plaintext)
tag = self.auth(ciphertext, data, tag_mask)
return ciphertext + tag
def decrypt(self, nonce: bytes, authed_ciphertext: bytes, data: bytes=b'') -> Bytes:
"""
Decrypts `ciphertext`.
Parameters:
nonce (bytes): Bytes-like nonce.
authed_ciphertext (bytes): Bytes-like object to be decrypted.
data (bytes): Bytes-like additional data to be authenticated.
Returns:
Bytes: Resulting plaintext.
"""
authed_ciphertext = Bytes.wrap(authed_ciphertext)
ciphertext, orig_tag = authed_ciphertext[:-16], authed_ciphertext[-16:]
tag_mask = self.clock_ctr(nonce)
data = Bytes.wrap(data)
tag = self.auth(ciphertext, data, tag_mask)
self.verify_tag(tag, orig_tag)
return self.ctr.decrypt(ciphertext)
def gcm_shift(self, x: int) -> int:
high_bit_set = x & 1
x >>= 1
if high_bit_set:
x ^= 0xe1 << (128 - 8)
return x
def mul(self, y):
ret = 0
for _ in range(0, 128, 4):
high_bit = ret & 0xF
ret >>= 4
ret ^= GCM_REDUCTION_TABLE[high_bit] << (128 - 16)
ret ^= self.product_table[y & 0xF]
y >>= 4
return ret
def auth(self, ciphertext: Bytes, ad: Bytes, tag_mask: Bytes) -> Bytes:
y = 0
y = self.update(y, ad)
y = self.update(y, ciphertext)
y ^= (len(ad) << (3 + 64)) | (len(ciphertext) << 3)
y = self.mul(y)
y ^= tag_mask.int()
return Bytes(int.to_bytes(y, 16, 'big'))
def update(self, y: int, data: Bytes) -> int:
for chunk in data.chunk(16):
y ^= chunk.int()
y = self.mul(y)
extra = len(data) % 16
if extra != 0:
block = bytearray(16)
block[:extra] = data[-extra:]
y ^= int.from_bytes(block, 'big')
y = self.mul(y)
return y
@staticmethod
def nonce_reuse_attack(auth_data_a: bytes, ciphertext_a: bytes, tag_a: bytes, auth_data_b: bytes, ciphertext_b: bytes, tag_b: bytes) -> list:
"""
Given two message-signature pairs generated by GCM using the same key/nonce,
returns candidates for the `auth key` and the `tag mask`.
Parameters:
auth_data_a (bytes): First authenticated data.
ciphertext_a (bytes): First ciphertext.
tag_a (bytes): First tag.
auth_data_b (bytes): Second authenticated data.
ciphertext_b (bytes): Second ciphertext.
tag_b (bytes): Second tag.
Returns:
list: List with entries formatted as (`H` "auth key", `t` "tag mask").
"""
from samson.math.algebra.all import FF, ZZ
from samson.math.polynomial import Polynomial
from samson.math.symbols import Symbol
from samson.block_ciphers.rijndael import Rijndael
x = Symbol('x')
_ = (ZZ/ZZ(2))[x]
F = FF(2, 128, reducing_poly=x**128 + x**7 + x**2 + x + 1)
def int_to_elem(a):
return F([int(bit) for bit in bin(a)[2:].zfill(128)])
def elem_to_int(a):
return int(bin(int(a))[2:].zfill(128)[::-1], 2)
def gcm_to_poly(ad, ciphertext, tag):
l = (len(ad) << (3 + 64)) | (len(ciphertext) << 3)
ct_ints = [chunk.int() for chunk in ciphertext.pad_congruent_right(16).chunk(16)[::-1]]
ad_ints = [chunk.int() for chunk in ad.pad_congruent_right(16).chunk(16)[::-1]]
return Polynomial([int_to_elem(coeff) for coeff in [tag.int(), l, *ct_ints, *ad_ints]])
auth_data_a, ciphertext_a, tag_a, auth_data_b, ciphertext_b, tag_b = [Bytes.wrap(item) for item in [auth_data_a, ciphertext_a, tag_a, auth_data_b, ciphertext_b, tag_b]]
poly_a = gcm_to_poly(auth_data_a, ciphertext_a, tag_a)
poly_b = gcm_to_poly(auth_data_b, ciphertext_b, tag_b)
# 3 is the smallest factor of (2**128) - 1
roots = (poly_a + poly_b).roots(subgroup_divisor=3)
candidates = [elem_to_int(r) for r in roots]
rij = Rijndael(Bytes.random(16))
# Compile results
results = []
for candidate in candidates:
gcm = GCM(rij, H=candidate)
no_tag_a = gcm.auth(ciphertext_a, auth_data_a, Bytes(0))
no_tag_b = gcm.auth(ciphertext_b, auth_data_b, Bytes(0))
# Just to make sure
if no_tag_a ^ tag_a == no_tag_b ^ tag_b:
results.append((candidate, no_tag_a ^ tag_a))
return results
forbidden_attack = nonce_reuse_attack
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/block_ciphers/modes/gcm.py
| 0.872116 | 0.278413 |
gcm.py
|
pypi
|
from samson.block_ciphers.blowfish import Blowfish
from samson.block_ciphers.modes.ecb import ECB
from samson.encoding.general import bcrypt_b64_encode
from samson.utilities.bytes import Bytes
from samson.core.primitives import KDF, Primitive
from samson.core.metadata import SizeSpec, SizeType
from samson.ace.decorators import register_primitive
CONSTANT = b"OrpheanBeholderScryDoubt"
# https://en.wikipedia.org/wiki/Bcrypt
# Tested against https://github.com/fwenzel/python-bcrypt
@register_primitive()
class Bcrypt(KDF):
"""
Blowfish based password-hashing algorithm
"""
BLOCK_SIZE = SizeSpec(size_type=SizeType.SINGLE, sizes=8)
OUTPUT_SIZE = SizeSpec(size_type=SizeType.ARBITRARY)
def __init__(self, cost: int, constant: bytes=CONSTANT, output_size: int=23, version: str='2a', use_specs_eks: bool=False):
"""
Parameters:
cost (int): Cost factor.
constant (bytes): (Optional) The constant or magic to use for bcrypt.
output_size (int): (Optional) Size to limit output to.
version (str): Version of bcrypt to use. Only supports '2a' for now (pads with a NUL byte if '2a').
use_specs_eks (bool): Use the original specification's order for processing salt and password.
"""
self.version = version
self.cost = cost
self.constant = Bytes.wrap(constant)
self.output_size = output_size
self.use_specs_eks = use_specs_eks
Primitive.__init__(self)
def eks_blowfish_setup(self, salt: bytes, password: bytes) -> Blowfish:
"""
Internal function. Creates a Blowfish instance using the expensive key schedule.
Parameters:
salt (bytes): Salt.
password (bytes): Password.
Returns:
Blowfish: Blowfish instance set-up using the expensive key schedule
"""
bf = Blowfish(b'', run_key_schedule=False)
key_len = len(password)
if self.version == '2a':
key_len += 1
self.expand_key(bf, salt, password, key_len=key_len)
salt_len = len(salt)
for _ in range(2**self.cost):
if self.use_specs_eks:
self.expand_key(bf, Bytes(b'').zfill(salt_len), salt)
self.expand_key(bf, Bytes(b'').zfill(salt_len), password, key_len=key_len)
else:
self.expand_key(bf, Bytes(b'').zfill(salt_len), password, key_len=key_len)
self.expand_key(bf, Bytes(b'').zfill(salt_len), salt)
return bf
def expand_key(self, bf: Blowfish, salt: bytes, password: bytes, key_len: int=None) -> Blowfish:
"""
Internal function. Performs a round of key expansion for the expensive key schedule.
Parameters:
bf (Blowfish): Blowfish instance to tweak.
salt (bytes): Salt.
password (bytes): Password.
key_len (int): Desired length of key. Will zero pad right.
Returns:
Blowfish: Blowfish instance undergone a round of key expansion.
"""
if not key_len:
key_len = len(password)
stretched = (password + b'\x00' * (key_len - len(password))).stretch(key_len*4)
password_chunks = stretched.chunk(4)
for n in range(18):
bf.P[n] ^= password_chunks[n % len(password_chunks)].int()
salt_chunks = salt.chunk(4)
salt_idx = 0
L = R = 0
for box in [bf.P] + bf.S:
for i in range(0, len(box), 2):
L ^= salt_chunks[salt_idx ].int()
R ^= salt_chunks[salt_idx+1].int()
salt_idx = (salt_idx + 2) % (len(salt) // 4)
R, L = bf.enc_L_R(L, R)
box[i], box[i + 1] = L, R
return bf
def derive(self, password: bytes, salt: bytes=None, format_output: bool=True) -> Bytes:
"""
Derives the bcrypt hash.
Parameters:
password (bytes): Password.
salt (bytes): Salt.
format_output (bool): Whether or not to use bcrypt formatting or just output the hash.
Returns:
Bytes: Derived key/hash.
"""
if not salt:
salt = Bytes.random(16)
salt = Bytes.wrap(salt)
password = Bytes.wrap(password)
bf = self.eks_blowfish_setup(salt, password)
ciphertext = self.constant
ecb = ECB(bf)
for _ in range(64):
ciphertext = ecb.encrypt(ciphertext)
to_return = ciphertext[:self.output_size]
if format_output:
to_return = Bytes(f'${self.version}$'.encode('utf-8') + str(self.cost).zfill(2).encode('utf-8') + b'$' + bcrypt_b64_encode(salt) + bcrypt_b64_encode(ciphertext[:self.output_size]))
return to_return
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/kdfs/bcrypt.py
| 0.739705 | 0.289512 |
bcrypt.py
|
pypi
|
from samson.hashes.sha2 import SHA512
from samson.kdfs.bcrypt import Bcrypt
from samson.utilities.bytes import Bytes
from samson.core.primitives import KDF, Primitive
from samson.ace.decorators import register_primitive
# OpenSSH's custom PBKDF2
# https://github.com/openssh/openssh-portable/blob/90e51d672711c19a36573be1785caf35019ae7a8/openbsd-compat/bcrypt_pbkdf.c
@register_primitive()
class BcryptPBKDF(KDF):
"""
The 'bcrypt_pbkdf' function in OpenSSH.
"""
def __init__(self, rounds: int=16, hash_obj: object=SHA512()):
"""
Parameters:
rounds (int): Number of rounds to perform.
hash_obj (object): Instantiated object with compatible hash interface. Normally SHA512.
"""
self.rounds = rounds
self.hash_obj = hash_obj
Primitive.__init__(self)
def derive(self, password: bytes, salt: bytes, key_len: int=48) -> Bytes:
"""
Derives the key.
Parameters:
password (bytes): Password.
salt (bytes): Salt.
key_len (int): Length of key to generate.
Returns:
Bytes: Derived key.
"""
orig_key_len = key_len
salt_len = len(salt)
salt = Bytes.wrap(salt)
sha_pass = self.hash_obj.hash(password)
stride = (key_len + 32 - 1) // 32
amt = (key_len + stride - 1) // stride
count_salt = salt + b'\x00' * 4
key = Bytes(b'').zfill(key_len)
bcrypt = Bcrypt(cost=6, constant=b'OxychromaticBlowfishSwatDynamite', output_size=32, version=None, use_specs_eks=True)
count = 1
while key_len > 1:
count_salt[salt_len + 0] = (count >> 24) & 0xFF
count_salt[salt_len + 1] = (count >> 16) & 0xFF
count_salt[salt_len + 2] = (count >> 8) & 0xFF
count_salt[salt_len + 3] = (count >> 0) & 0xFF
sha_salt = self.hash_obj.hash(count_salt)
out = bcrypt.derive(sha_pass, sha_salt, format_output=False)
out = sum([chunk[::-1] for chunk in out.chunk(4)])
tmp_out = out
for _ in range(1, self.rounds):
sha_salt = self.hash_obj.hash(tmp_out)
tmp_out = bcrypt.derive(sha_pass, sha_salt, format_output=False)
tmp_out = sum([chunk[::-1] for chunk in tmp_out.chunk(4)])
out ^= tmp_out
amt = min(amt, key_len)
for i in range(amt):
dest = i * stride + (count - 1)
if dest >= orig_key_len:
break
key[dest] = out[i]
key_len -= (i + 1)
count += 1
return key
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/kdfs/bcrypt_pbkdf.py
| 0.748536 | 0.179836 |
bcrypt_pbkdf.py
|
pypi
|
from samson.utilities.bytes import Bytes
from samson.kdfs.pbkdf2 import PBKDF2
from samson.macs.hmac import HMAC
from samson.hashes.sha2 import SHA256
from samson.stream_ciphers.salsa import Salsa
from samson.core.primitives import KDF, Primitive
from samson.ace.decorators import register_primitive
from types import FunctionType
NULL_SALSA = Salsa(key=Bytes(b'').zfill(8), nonce=Bytes(b'').zfill(8), rounds=8)
def BlockMix(B):
r = len(B) // 128
B_arr = B.chunk(64)
X = B_arr[-1]
Y = []
for i in range(2*r):
T = X ^ B_arr[i]
T.byteorder = 'little'
X = NULL_SALSA.full_round(0, state=[x.int() for x in T.chunk(4)])
Y.append(X)
Y_ret = b''.join([_ for _ in Y[::2]]) + b''.join([_ for _ in Y[1::2]])
return Bytes(Y_ret)
def ROMix(block, iterations):
X = block
V = []
for _ in range(iterations):
X.byteorder = 'little'
V.append(X)
X = BlockMix(X)
for _ in range(iterations):
X.byteorder = 'little'
j = X[-64:].int() % iterations
X = BlockMix(X ^ V[j])
return X
_sha256 = SHA256()
@register_primitive()
class Scrypt(KDF):
"""
scrypt KDF described in RFC7914
https://en.wikipedia.org/wiki/Scrypt
https://tools.ietf.org/html/rfc7914
"""
def __init__(self, desired_len: int, cost: int, parallelization_factor: int, block_size_factor: int=8, hash_fn: FunctionType=lambda passwd, msg: HMAC(passwd, _sha256).generate(msg)):
"""
Parameters:
desired_len (int): Desired output length.
cost (int): Cost (usually a power of two).
block_size_factor (int): `r` from the RFC.
hash_fn (func): Function that takes in bytes and returns them hashed.
"""
self.block_size = block_size_factor * 128
self.hash_fn = hash_fn
self.pbkdf2 = PBKDF2(hash_fn, self.block_size * parallelization_factor, 1)
self.desired_len = desired_len
self.cost = cost
self.block_size_factor = block_size_factor
self.parallelization_factor = parallelization_factor
Primitive.__init__(self)
def __reprdir__(self):
return ['pbkdf2', 'desired_len', 'cost', 'block_size']
def derive(self, password: bytes, salt: bytes) -> Bytes:
"""
Derives a key.
Parameters:
password (bytes): Bytes-like object to key the internal state.
salt (bytes): Salt to tweak the output.
Returns:
Bytes: Derived key.
"""
B = self.pbkdf2.derive(password, salt).chunk(self.block_size)
for i in range(self.parallelization_factor):
B[i] = ROMix(B[i], self.cost)
expensive_salt = b''.join(B)
return PBKDF2(self.hash_fn, self.desired_len, 1).derive(password, expensive_salt)
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/kdfs/scrypt.py
| 0.58439 | 0.270035 |
scrypt.py
|
pypi
|
from samson.macs.cmac import CMAC
from samson.utilities.bytes import Bytes
from samson.block_ciphers.rijndael import Rijndael
from samson.core.primitives import EncryptionAlg, KDF, Primitive
from samson.core.metadata import SizeType, SizeSpec
from samson.ace.decorators import register_primitive
from copy import deepcopy
def dbl(bytestring):
if bytestring.int() & 0x80000000000000000000000000000000:
bytestring = (bytestring << 1) ^ 0x00000000000000000000000000000087
else:
bytestring = bytestring << 1
return bytestring
@register_primitive()
class S2V(KDF):
"""
S2V KDF described in RFC5297 (https://tools.ietf.org/html/rfc5297)
"""
BLOCK_SIZE = SizeSpec(size_type=SizeType.DEPENDENT, selector=lambda s2v: s2v.cipher.BLOCK_SIZE)
def __init__(self, cipher: EncryptionAlg=None, iv: bytes=b'\x00'*16):
"""
Parameters:
cipher (EncryptionAlg): Instantiated encryption algorithm.
iv (bytes): Initialization vector.
"""
self.cmac = CMAC(cipher or Rijndael(Bytes.random(32)))
self.iv = iv
Primitive.__init__(self)
def __reprdir__(self):
return ['cmac', 'iv']
def derive(self, *strings: bytes) -> Bytes:
"""
Derives a key.
Parameters:
*strings (*args, bytes): Variadic args of bytestrings.
Returns:
Bytes: Derived key.
"""
if len(strings) == 0:
return self.cmac.generate(0x01)
derived_iv = self.cmac.generate(self.iv)
for bytestring in strings[:-1]:
derived_iv = dbl(derived_iv)
derived_iv ^= self.cmac.generate(bytestring)
last_str = deepcopy(strings[-1])
if len(last_str) < 16:
derived_iv = dbl(derived_iv)
last_str += b'\x80'
last_str = last_str + (b'\x00' * (16 - len(last_str)))
derived_iv = derived_iv.zfill(len(last_str)) ^ last_str
return self.cmac.generate(derived_iv)
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/kdfs/s2v.py
| 0.710025 | 0.204958 |
s2v.py
|
pypi
|
from samson.core.attack_model import AttackModel
from samson.oracles.known_plaintext_oracle import KnownPlaintextOracle
from samson.oracles.oracle import Oracle
from samson.utilities.exceptions import *
from samson.core.metadata import IORelationType
from samson.utilities.bytes import Bytes
from types import FunctionType
import logging
log = logging.getLogger(__name__)
class ChosenCiphertextOracle(Oracle):
"""
Simple oracle that provides a `request` function.
"""
ATTACK_MODEL = AttackModel.CHOSEN_CIPHERTEXT
def __init__(self, request_func: FunctionType):
"""
Parameters:
request_func (func): Function that provides the oracle.
"""
self.request = request_func
def downconvert(self, attack_model: AttackModel, generator: FunctionType=lambda: Bytes.random(8)):
if attack_model == self.ATTACK_MODEL:
return self
else:
def oracle_func():
pt = generator()
ct = self.request(pt)
return pt, ct
return KnownPlaintextOracle(oracle_func).downconvert(attack_model, generator)
def test_io_relation(self) -> int:
for i in range(512):
try:
self.request(b'a'*i)
except CiphertextLengthException:
continue
except DecryptionException:
pass
break
min_size = i
max_size = self.test_max_input()
# Public key crypto is FIXED but will take in anything between zero and `n`
# It will almost always be 2**0 (1), so we take the max as the block size instead.
# This still works for stream ciphers because they won't have a max and will iterate back to zero.
block_size = min_size if min_size else max_size
for size_mod in range(block_size, -1, -1):
try:
self.request(b'a' * (block_size + size_mod))
break
except CiphertextLengthException:
continue
except DecryptionException:
break
# Determine IO relation
if size_mod:
io_relation = IORelationType.EQUAL
else:
io_relation = IORelationType.FIXED
return {"io_relation": io_relation, "block_size": block_size}
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/oracles/chosen_ciphertext_oracle.py
| 0.57093 | 0.173884 |
chosen_ciphertext_oracle.py
|
pypi
|
from samson.utilities.exceptions import CiphertextLengthException, DecryptionException
from samson.utilities.bytes import Bytes
from samson.utilities.general import binary_search
from samson.math.general import kth_root
from types import FunctionType
import math
import logging
log = logging.getLogger(__name__)
class Oracle(object):
"""
Simple oracle that provides a `request` function.
"""
def __init__(self, request_func: FunctionType):
"""
Parameters:
request_func (func): Function that provides the oracle.
"""
self.request = request_func
def test_max_input(self, max_int: int=2**16383) -> int:
# Use 'max_int' as a canary. If the primitive will take 'max_int', then
# it's most likely going to take anything. Only run this test if we know the primitive
# has a fixed output size (e.g. hashes and number-theoretical crypto).
should_test_max = False
while True:
try:
self.request(Bytes(max_int))
except CiphertextLengthException:
should_test_max = True
break
except DecryptionException:
pass
except ValueError:
max_int = kth_root(max_int, 2)
log.warning(f'Oracle returned ValueError. Reducing MAX_TEST_INPUT to 2^{int(math.log(max_int, 2))}')
continue
log.info('Oracle seems to take in arbitrary-sized inputs')
break
# Use binary search to find max input size. This is both the most efficient method of finding
# the max size and the most precise. For example, if the primitive is RSA and rejects inputs
# larger than its modulus, then "end_idx" will be the modulus.
max_val = -1
if should_test_max:
log.debug('Starting max input testing')
def search_func(n):
try:
self.request(Bytes(n))
except CiphertextLengthException:
return False
except DecryptionException:
pass
return True
max_val = binary_search(search_func, max_int)
log.info(f'Max input size: {round(math.log(max_val, 2), 1)} bits')
else:
log.debug('Skipping max input testing')
return max_val
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/oracles/oracle.py
| 0.715623 | 0.269118 |
oracle.py
|
pypi
|
from samson.encoding.general import PKIEncoding
from samson.encoding.pem import pem_decode
ORDER = [PKIEncoding.DNS_KEY, PKIEncoding.JWK, PKIEncoding.OpenSSH, PKIEncoding.SSH2, PKIEncoding.X509_CSR, PKIEncoding.X509_CERT, PKIEncoding.X509, PKIEncoding.PKCS8, PKIEncoding.PKCS1]
class EncodablePKI(object):
PUB_ENCODINGS = {}
PRIV_ENCODINGS = {}
@classmethod
def import_key(cls, buffer: bytes, passphrase: bytes=None) -> 'EncodablePKI':
"""
Builds a PKI instance from DER and/or PEM-encoded bytes.
Parameters:
buffer (bytes): DER and/or PEM-encoded bytes.
passphrase (bytes): Passphrase to decrypt DER-bytes (if applicable).
Returns:
object: PKI instance.
"""
if buffer.strip().startswith(b'----'):
buffer = pem_decode(buffer, passphrase)
for encoding in ORDER:
for encoding_type in [cls.PRIV_ENCODINGS, cls.PUB_ENCODINGS]:
if encoding in encoding_type:
encoder = encoding_type[encoding]
if encoder.check(buffer, passphrase=passphrase):
return encoder.decode(buffer, passphrase=passphrase)
raise ValueError(f"Unable to parse provided {cls} key.")
def export_public_key(self, encoding: PKIEncoding=PKIEncoding.X509, **kwargs) -> bytes:
"""
Exports the only the public parameters of the PKI instance into encoded bytes.
Parameters:
encoding (PKIEncoding): Encoding scheme to use. Support dependent on PKI type.
Returns:
object: Encoding of PKI instance.
"""
if encoding not in self.PUB_ENCODINGS:
raise ValueError(f'Unsupported public encoding "{encoding}" for "{self.__class__}"')
return self.PUB_ENCODINGS[encoding](self, **kwargs)
def export_private_key(self, encoding: PKIEncoding=PKIEncoding.PKCS8, encode_pem: bool=True, marker: str=None, encryption: str=None, passphrase: bytes=None, iv: bytes=None, **kwargs) -> bytes:
"""
Exports the full PKI instance into encoded bytes.
Parameters:
encoding (PKIEncoding): Encoding scheme to use. Support dependent on PKI type.
encode_pem (bool): Whether or not to PEM-encode as well.
marker (str): Marker to use in PEM formatting (if applicable).
encryption (str): (Optional) RFC1423 encryption algorithm (e.g. 'DES-EDE3-CBC').
passphrase (bytes): (Optional) Passphrase to encrypt DER-bytes (if applicable).
iv (bytes): (Optional) IV to use for CBC encryption.
Returns:
bytes: Bytes-encoded PKI instance.
"""
if encoding not in self.PRIV_ENCODINGS:
raise ValueError(f'Unsupported private encoding "{encoding}" for "{self.__class__}"')
return self.PRIV_ENCODINGS[encoding](self, **kwargs)
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/core/encodable_pki.py
| 0.736211 | 0.154631 |
encodable_pki.py
|
pypi
|
from z3 import BitVecs, Solver, LShR, Bool, Implies, sat, RotateLeft
from samson.utilities.exceptions import NoSolutionException
from samson.core.base_object import BaseObject
from samson.core.metadata import CrackingDifficulty
from inspect import isclass
import random
class IterativePRNG(BaseObject):
"""
Base class for PRNGs that iterate over fixed-size state.
"""
CRACKING_DIFFICULTY = CrackingDifficulty.NORMAL
def __init__(self, seed: list):
"""
Parameters:
seed (list): Initial value.
"""
self.state = [s & (2**self.NATIVE_BITS-1) for s in seed]
def generate(self) -> int:
"""
Generates the next pseudorandom output.
Returns:
int: Next pseudorandom output.
"""
state, result = self.gen_func(*self.state)
self.state = state
return result
def crack(self, outputs: list) -> 'IterativePRNG':
"""
Cracks the PRNG's internal state using `outputs`.
Parameters:
outputs (list): Observed, sequential outputs.
Returns:
IterativePRNG: Cracked IterativePRNG of the subclass' class.
"""
state_vecs = BitVecs(' '.join([f'ostate{i}' for i in range(self.STATE_SIZE)]), self.NATIVE_BITS)
sym_states = state_vecs
solver = Solver()
conditions = []
for output in outputs:
sym_states, calc = self.gen_func(*sym_states, SHFT_L=lambda x, n: x << n, SHFT_R=LShR, RotateLeft=RotateLeft)
condition = Bool('c%d' % int(random.random()))
solver.add(Implies(condition, calc == int(output)))
conditions += [condition]
if solver.check(conditions) == sat:
model = solver.model()
params = [model[vec].as_long() for vec in state_vecs]
if isclass(self):
prng = self(params)
else:
prng = self.__class__(params)
[prng.generate() for _ in outputs]
return prng
else:
raise NoSolutionException('Model not satisfiable.')
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/core/iterative_prng.py
| 0.805326 | 0.233444 |
iterative_prng.py
|
pypi
|
from enum import Enum
from types import FunctionType
class PrimitiveType(Enum):
CIPHER = 0
HASH = 1
MAC = 2
KDF = 3
KEY_EXCHANGE = 4
SIGNING = 5
class CipherType(Enum):
NONE = 0
NUMBER_THEORETICAL_CIPHER = 1
STREAM_CIPHER = 2
BLOCK_CIPHER = 3
class SymmetryType(Enum):
NONE = 0
SYMMETRIC = 1
ASYMMETRIC = 2
class ConstructionType(Enum):
MERKLE_DAMGARD = 0
EVEN_MANSOUR = 1
FEISTEL_NETWORK = 2
MATYAS_MEYER_OSEAS = 3
MIYAGUCHI_PRENEEL = 4
SPONGE = 5
SUBSTITUTION_PERMUTATION_NETWORK = 6
ADD_ROTATE_XOR = 7
LFSR = 8
HASH_ITERATIVE_FRAMEWORK = 9
DAVIES_MEYER = 10
WEGMAN_CARTER = 11
class SecurityProofType(Enum):
NONE = 0
DISCRETE_LOGARITHM = 1
SHORTEST_VECTOR = 2
INTEGER_FACTORIZATION = 3
INFORMATION_THEORETIC = 4
class UsageType(Enum):
GENERAL = 0
CELLULAR = 1
WIRELESS = 2
ACADEMIC = 3
OTHER = 4
class SizeType(Enum):
"""
SizeTypes determine the behavior of the SizeSpec.
SINGLE - only accept one value. Sets "sizes" to an integer.
RANGE - accept any value in "sizes". "sizes" is iterable. Can use "typical" to denote typical values.
ARBITRARY - accept any size. "sizes" is unused. Can use "typical" to denote typical values.
DEPENDENT - size is dependent on another value that can only be resolved on instantiation.
"""
NONE = 0
SINGLE = 1
RANGE = 2
ARBITRARY = 3
DEPENDENT = 4
class EphemeralType(Enum):
"""
EphemeralTypes determine the usage and consequences of ephemeral values.
IV - reuse may result in distinguishing attacks (e.g. block A has the same plaintext as block B).
NONCE - reuse may result in plaintext recovery attacks or potentially worse.
KEY - ephemeral is secret and reuse may result in key recovery attacks.
"""
IV = 0
NONCE = 1
KEY = 2
class IORelationType(Enum):
"""
IORelationTypes determine the relation between input and output sizes.
EQUAL - input and output size are always equal.
FIXED - output size is fixed.
ARBITRARY - input and output size can be arbitrarily picked.
"""
EQUAL = 0
FIXED = 1
ARBITRARY = 2
class MalleabilityType(Enum):
"""
MalleabilityTypes determine the malleability properties of the output.
NONE - the output is not malleable.
BITWISE - the output can be manipulated at a bit level.
ADDITION - the output is homomorphic under addition.
MULTIPLICATION - the output is homomorphic under multiplication.
"""
NONE = 0
BITWISE = 1
ADDITION = 2
MULTIPLICATION = 3
class FrequencyType(Enum):
"""
FrequencyTypes determine the frequency of the value of a property.
NEGLIGIBLE - value is almost never seen.
UNUSUAL - value occurs less than average.
NORMAL - value occurs with average frequency.
OFTEN - value occurs more than average.
PROLIFIC - value is almost always seen.
"""
NEGLIGIBLE = 0
UNUSUAL = 1
NORMAL = 2
OFTEN = 3
PROLIFIC = 4
class SizeSpec(object):
def __init__(self, size_type: SizeType, sizes: list=None, typical: list=None, selector: FunctionType=None):
self.size_type = size_type
self.sizes = sizes or []
self.typical = typical or []
self.selector = selector
self.parent = None
def __repr__(self):
return f"<SizeSpec: size_type={self.size_type}, sizes={self.sizes}, typical={self.typical}, parent={self.parent}>"
def __str__(self):
return self.__repr__()
def __contains__(self, item):
if self.size_type == SizeType.ARBITRARY:
result = True
elif self.size_type == SizeType.RANGE:
if type(item) is list:
result = all([i in self.sizes for i in item])
else:
result = item in self.sizes
elif self.size_type == SizeType.SINGLE:
result = item == self.sizes
elif self.size_type == SizeType.DEPENDENT:
if self.parent is None:
return False
size = self.selector(self.parent)
if type(size) is SizeSpec:
result = item in size
else:
result = item == size
else:
raise ValueError("This shouldn't be possible. Is 'size_type' not SizeType?")
return result
def __eq__(self, other):
return type(other) == type(self) and self.size_type == other.size_type and self.sizes == other.sizes
def __lt__(self, other):
if type(other) is int:
if self.size_type == SizeType.ARBITRARY:
result = False
elif self.size_type == SizeType.RANGE:
result = other > sorted(self.sizes)[-1]
elif self.size_type == SizeType.SINGLE:
result = other > self.sizes
elif self.size_type == SizeType.DEPENDENT:
if self.parent is None:
return False
size = self.selector(self.parent)
result = other > size
return result
else:
raise NotImplementedError()
class EphemeralSpec(object):
def __init__(self, ephemeral_type: EphemeralType, size: SizeSpec):
self.ephemeral_type = ephemeral_type
self.size = size
def __repr__(self):
return f"<EphemeralSpec: ephemeral_type={self.ephemeral_type}, size={self.size}>"
def __str__(self):
return self.__repr__()
def __eq__(self, other):
return type(other) == type(self) and self.ephemeral_type == other.ephemeral_type and self.size == other.size
class FrequencySpec(object):
def __init__(self, frequency_type: FrequencyType, value: object=None):
self.frequency_type = frequency_type
self.value = value
def __repr__(self):
return f"<FrequencySpec: frequency_type={self.frequency_type}, value={self.value}>"
def __str__(self):
return self.__repr__()
def __eq__(self, other):
return type(other) == type(self) and self.frequency_type == other.frequency_type and self.value == other.value
class CrackingDifficulty(Enum):
TRIVIAL = 0 # Cracks instantly (~ 1 millisecond)
NORMAL = 1 # Requires some work (~1 second)
EXPENSIVE = 2 # Cost a lot (~100 second)
EXTREME = 3 # Generally too expensive to try
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/core/metadata.py
| 0.719088 | 0.410225 |
metadata.py
|
pypi
|
from samson.core.metadata import SizeSpec, SizeType, SymmetryType, EphemeralType, EphemeralSpec, SecurityProofType, UsageType, ConstructionType, PrimitiveType, CipherType, IORelationType, FrequencyType
from samson.ace.decorators import has_exploit, creates_constraint
from samson.ace.exploit import KeyPossession, PlaintextPossession
from samson.ace.constraints import EncryptedConstraint
from samson.utilities.bytes import Bytes
from samson.utilities.exceptions import CiphertextLengthException, InvalidMACException
from samson.core.base_object import BaseObject
from copy import deepcopy
from abc import abstractmethod
"""
This module's purpose is to create a unified, concise, and machine-readable description of samson's primitives.
Each class provides:
* A uniform interface based on the usage of the primitive type
* A generic description of primitive types by mapping their properties to samson's Primitive Specification Language (PSL)
* A best effort description of non-uniform properties that can be overriden
"""
# https://stackoverflow.com/questions/128573/using-property-on-classmethods
class classproperty(object):
def __init__(self, fget):
self.fget = fget
def __get__(self, owner_self, owner_cls):
return self.fget(owner_cls)
class Primitive(BaseObject):
CONSTRUCTION_TYPES = []
USAGE_TYPE = UsageType.GENERAL
USAGE_FREQUENCY = FrequencyType.NEGLIGIBLE
SECURITY_PROOF = SecurityProofType.NONE
SYMMETRY_TYPE = SymmetryType.NONE
CIPHER_TYPE = CipherType.NONE
IO_RELATION_TYPE = IORelationType.FIXED
def __init__(self):
for attr in [attr for attr in dir(self) if attr in ['KEY_SIZE', 'OUTPUT_SIZE', 'INPUT_SIZE', 'BLOCK_SIZE']]:
if getattr(self, attr).size_type == SizeType.DEPENDENT:
setattr(self, attr, deepcopy(getattr(self, attr)))
getattr(self, attr).parent = self
@has_exploit(KeyPossession)
@creates_constraint(EncryptedConstraint())
class EncryptionAlg(Primitive):
PRIMITIVE_TYPE = PrimitiveType.CIPHER
@abstractmethod
def encrypt(self, *args, **kwargs):
pass
@abstractmethod
def decrypt(self, *args, **kwargs):
pass
@has_exploit(PlaintextPossession)
@has_exploit(KeyPossession)
class MAC(Primitive):
PRIMITIVE_TYPE = PrimitiveType.MAC
KEY_SIZE = SizeSpec(size_type=SizeType.DEPENDENT, selector=lambda cipher: cipher.KEY_SIZE)
SYMMETRY_TYPE = SymmetryType.SYMMETRIC
INPUT_SIZE = SizeSpec(size_type=SizeType.ARBITRARY)
BLOCK_SIZE = SizeSpec(size_type=SizeType.DEPENDENT, selector=lambda cipher: cipher.BLOCK_SIZE)
OUTPUT_SIZE = SizeSpec(size_type=SizeType.DEPENDENT, selector=lambda cipher: cipher.OUTPUT_SIZE)
@abstractmethod
def generate(self, *args, **kwargs):
pass
def verify(self, message: bytes, signature: bytes) -> bool:
"""
Verifies `message` and `signature` by regenerating the signature.
Parameters:
message (bytes): Message to verify.
signature (bytes): Alleged signature of `message`.
Returns:
bool: Whether or not the signature matched.
"""
from samson.utilities.runtime import RUNTIME
return RUNTIME.compare_bytes(self.generate(message), signature)
class KDF(Primitive):
PRIMITIVE_TYPE = PrimitiveType.KDF
INPUT_SIZE = SizeSpec(size_type=SizeType.ARBITRARY)
BLOCK_SIZE = SizeSpec(size_type=SizeType.DEPENDENT, selector=lambda cipher: cipher.hash_obj.BLOCK_SIZE)
OUTPUT_SIZE = SizeSpec(size_type=SizeType.ARBITRARY)
@abstractmethod
def derive(self, *args, **kwargs):
pass
class Hash(Primitive):
PRIMITIVE_TYPE = PrimitiveType.HASH
INPUT_SIZE = SizeSpec(size_type=SizeType.ARBITRARY)
CONSTRUCTION_TYPES = [ConstructionType.MERKLE_DAMGARD]
@classproperty
def BLOCK_SIZE(cls):
return cls.OUTPUT_SIZE
@abstractmethod
def hash(self, *args, **kwargs):
pass
class NumberTheoreticalAlg(Primitive):
SYMMETRY_TYPE = SymmetryType.ASYMMETRIC
PRIMITIVE_TYPE = PrimitiveType.CIPHER
CIPHER_TYPE = CipherType.NUMBER_THEORETICAL_CIPHER
KEY_SIZE = SizeSpec(size_type=SizeType.ARBITRARY, typical=[1024, 2048, 4096])
SECURITY_PROOF = SecurityProofType.DISCRETE_LOGARITHM
@classproperty
def INPUT_SIZE(cls):
return cls.KEY_SIZE
@classproperty
def OUTPUT_SIZE(cls):
return cls.KEY_SIZE
@classproperty
def BLOCK_SIZE(cls):
return cls.OUTPUT_SIZE
class SignatureAlg(NumberTheoreticalAlg):
PRIMITIVE_TYPE = PrimitiveType.SIGNING
KEY_SIZE = SizeSpec(size_type=SizeType.ARBITRARY, typical=[160, 224, 256])
OUTPUT_SIZE = SizeSpec(size_type=SizeType.ARBITRARY, typical=[320, 448, 512])
CIPHER_TYPE = CipherType.NONE
EPHEMERAL = EphemeralSpec(ephemeral_type=EphemeralType.KEY, size=SizeSpec(size_type=SizeType.DEPENDENT, selector=lambda signer: signer.KEY_SIZE))
class KeyExchangeAlg(Primitive):
PRIMITIVE_TYPE = PrimitiveType.KEY_EXCHANGE
SYMMETRY_TYPE = SymmetryType.ASYMMETRIC
SECURITY_PROOF = SecurityProofType.DISCRETE_LOGARITHM
KEY_SIZE = SizeSpec(size_type=SizeType.ARBITRARY, typical=[1024, 2048, 4096])
@classproperty
def INPUT_SIZE(cls):
return cls.KEY_SIZE
@classproperty
def OUTPUT_SIZE(cls):
return cls.KEY_SIZE
@classproperty
def BLOCK_SIZE(cls):
return cls.KEY_SIZE
class StreamCipher(EncryptionAlg):
SYMMETRY_TYPE = SymmetryType.SYMMETRIC
CIPHER_TYPE = CipherType.STREAM_CIPHER
KEY_SIZE = SizeSpec(size_type=SizeType.RANGE, sizes=[128, 256])
INPUT_SIZE = SizeSpec(size_type=SizeType.ARBITRARY)
OUTPUT_SIZE = SizeSpec(size_type=SizeType.ARBITRARY)
BLOCK_SIZE = SizeSpec(size_type=SizeType.SINGLE, sizes=8)
IO_RELATION_TYPE = IORelationType.EQUAL
def encrypt(self, plaintext: bytes) -> Bytes:
return self.generate(len(plaintext)) ^ plaintext
def decrypt(self, ciphertext: bytes) -> Bytes:
return self.encrypt(ciphertext)
class BlockCipher(EncryptionAlg):
SYMMETRY_TYPE = SymmetryType.SYMMETRIC
CIPHER_TYPE = CipherType.BLOCK_CIPHER
CONSTRUCTION_TYPES = [ConstructionType.FEISTEL_NETWORK]
KEY_SIZE = SizeSpec(size_type=SizeType.RANGE, sizes=[128, 192, 256], typical=[128, 256])
BLOCK_SIZE = SizeSpec(size_type=SizeType.SINGLE, sizes=128)
IO_RELATION_TYPE = IORelationType.EQUAL
@classproperty
def INPUT_SIZE(cls):
return cls.BLOCK_SIZE
@classproperty
def OUTPUT_SIZE(cls):
return cls.BLOCK_SIZE
_bcm_attr_set = {'underlying_mode', 'cipher', 'H', 'sector_encryptor', 'nonce', 'iv', 'counter', 'byteorder'}
class BlockCipherMode(EncryptionAlg):
SYMMETRY_TYPE = SymmetryType.SYMMETRIC
KEY_SIZE = SizeSpec(size_type=SizeType.DEPENDENT, selector=lambda mode: mode.cipher.KEY_SIZE)
INPUT_SIZE = SizeSpec(size_type=SizeType.ARBITRARY)
OUTPUT_SIZE = SizeSpec(size_type=SizeType.ARBITRARY)
BLOCK_SIZE = SizeSpec(size_type=SizeType.DEPENDENT, selector=lambda mode: mode.cipher.BLOCK_SIZE)
IO_RELATION_TYPE = IORelationType.EQUAL
def __reprdir__(self):
return [k for k in self.__dict__ if k in _bcm_attr_set]
def check_ciphertext_length(self, ciphertext: bytes):
if not len(ciphertext) or len(ciphertext) % self.cipher.block_size != 0:
raise CiphertextLengthException("Ciphertext is not a multiple of the block size")
class StreamingBlockCipherMode(BlockCipherMode):
CIPHER_TYPE = CipherType.STREAM_CIPHER
BLOCK_SIZE = SizeSpec(size_type=SizeType.SINGLE, sizes=8)
class AuthenticatedCipher(EncryptionAlg):
def verify_tag(self, tag: bytes, given_tag: bytes):
from samson.utilities.runtime import RUNTIME
if not RUNTIME.compare_bytes(tag, given_tag):
raise InvalidMACException('Tag mismatch: authentication failed!')
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/core/primitives.py
| 0.853501 | 0.197174 |
primitives.py
|
pypi
|
import string
from samson.core.base_object import BaseObject
# http://practicalcryptography.com/ciphers/playfair-cipher/
class Playfair(BaseObject):
"""
Bigram substituion cipher.
"""
def __init__(self, key: str):
"""
Parameters:
key (str): Keyphrase containing no duplicate letters and not the letter 'j'.
"""
if len(list(set(list(key)))) < len(key):
raise ValueError("Key cannot have duplicate characters")
# Playfair combines 'i' and 'j'
assert 'j' not in key
for letter in string.ascii_lowercase:
if letter not in key and letter != 'j':
key += letter
self.key = key
def encrypt(self, plaintext: str) -> str:
"""
Encrypts `plaintext`.
Parameters:
plaintext (str): String to be encrypted.
Returns:
str: Resulting ciphertext.
"""
plaintext = plaintext.replace("j", "i")
# Remove characters not in key
for char in plaintext:
if char not in self.key:
plaintext = plaintext.replace(char, "")
# If plaintext has an odd number of characters, add an 'x' to the end
if len(plaintext) % 2 == 1:
plaintext += 'x'
# Substitute duplicate letters with x
for i in range(0, len(plaintext), 2):
if plaintext[i] == plaintext[i + 1]:
plaintext = plaintext[:i + 1] + 'x' + plaintext[i + 2:]
ciphertext = ''
for i in range(0, len(plaintext), 2):
a, b = plaintext[i], plaintext[i + 1]
a_loc, b_loc = self.key.index(a), self.key.index(b)
a_row, a_col = a_loc // 5, a_loc % 5
b_row, b_col = b_loc // 5, b_loc % 5
if a_row != b_row and a_col != b_col:
new_a = a_row * 5 + b_col
new_b = b_row * 5 + a_col
elif a_row == b_row:
new_a = a_row * 5 + ((a_col + 1) % 5)
new_b = a_row * 5 + ((b_col + 1) % 5)
else:
new_a = ((a_row + 1) % 5) * 5 + a_col
new_b = ((b_row + 1) % 5) * 5 + a_col
ciphertext += self.key[new_a] + self.key[new_b]
return ciphertext
def decrypt(self, ciphertext: str) -> str:
"""
Decrypts `ciphertext`.
Parameters:
ciphertext (str): Stringt to be decrypted.
Returns:
str: Resulting plaintext.
"""
plaintext = ''
for i in range(0, len(ciphertext), 2):
a, b = ciphertext[i], ciphertext[i + 1]
a_loc, b_loc = self.key.index(a), self.key.index(b)
a_row, a_col = a_loc // 5, a_loc % 5
b_row, b_col = b_loc // 5, b_loc % 5
if a_row != b_row and a_col != b_col:
new_a = a_row * 5 + b_col
new_b = b_row * 5 + a_col
elif a_row == b_row:
new_a = a_row * 5 + ((a_col - 1) % 5)
new_b = a_row * 5 + ((b_col - 1) % 5)
else:
new_a = ((a_row - 1) % 5) * 5 + a_col
new_b = ((b_row - 1) % 5) * 5 + a_col
plaintext += self.key[new_a] + self.key[new_b]
return plaintext
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/classical/playfair.py
| 0.623377 | 0.375821 |
playfair.py
|
pypi
|
from samson.math.general import mod_inv
from samson.core.base_object import BaseObject
class AffineCipher(BaseObject):
"""
Monoalphabetic substitution of the form `(ax + b) mod m`.
The Caesar cipher is an AffineCipher with a=1.
"""
def __init__(self, a: int, b: int, alphabet: str='ABCDEFGHIJKLMNOPQRSTUVWXYZ ,.'):
"""
Parameters:
a (int): Multiplier.
b (int): Linear shift.
alphabet (str): Alphabet (in order) to encrypt over. Input must also be in this alphabet.
"""
self.a = a
self.b = b
self.alphabet = alphabet
self.char_map = {}
for i in range(len(alphabet)):
self.char_map[alphabet[i]] = alphabet[(a*i+b)%len(alphabet)]
inv_a = mod_inv(a, len(alphabet))
self.inv_char_map = {}
for i in range(len(alphabet)):
self.inv_char_map[alphabet[i]] = alphabet[(inv_a*(i-b))%len(alphabet)]
def __reprdir__(self):
return ['a', 'b', 'alphabet']
def encrypt(self, plaintext: str) -> str:
"""
Encrypts `plaintext`.
Parameters:
plaintext (str): String to be encrypted.
Returns:
str: Resulting ciphertext.
"""
primitive_len = len(self.alphabet[0])
ciphertext = ''
for i in range(0, len(plaintext), primitive_len):
curr_symbol = plaintext[i:i + primitive_len]
if curr_symbol in self.char_map:
ciphertext += self.char_map[curr_symbol]
else:
ciphertext += curr_symbol
return ciphertext
def decrypt(self, ciphertext: str) -> str:
"""
Decrypts `ciphertext`.
Parameters:
ciphertext (str): String to be decrypted.
Returns:
str: Resulting plaintext.
"""
primitive_len = len(self.alphabet[0])
plaintext = ''
for i in range(0, len(ciphertext), primitive_len):
curr_symbol = ciphertext[i:i + primitive_len]
if curr_symbol in self.inv_char_map:
plaintext += self.inv_char_map[curr_symbol]
else:
plaintext += curr_symbol
return plaintext
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/classical/affine.py
| 0.767516 | 0.198511 |
affine.py
|
pypi
|
from samson.analysis.general import chisquare, count_items
from samson.utilities.bytes import Bytes
from samson.analyzers.english_analyzer import EnglishAnalyzer
from samson.core.base_object import BaseObject
import string
letter_freq = {
b'e': 0.1249,
b't': 0.0928,
b'a': 0.0804,
b'o': 0.0764,
b'i': 0.0757,
b'n': 0.0723,
b's': 0.0651,
b'r': 0.0628,
b'h': 0.0505,
b'l': 0.0407,
b'd': 0.0382,
b'c': 0.0334,
b'u': 0.0273,
b'm': 0.0251,
b'f': 0.0240,
b'p': 0.0214,
b'g': 0.0187,
b'w': 0.0168,
b'y': 0.0166,
b'b': 0.0148,
b'v': 0.0105,
b'k': 0.0054,
b'x': 0.0023,
b'j': 0.0016,
b'q': 0.0012,
b'z': 0.0009
}
letter_distribution = {}
for key, val in letter_freq.items():
letter_distribution[ord(key)] = val
class Vigenere(BaseObject):
"""
Polyalphabetic subsitution cipher that can be reduced to interwoven Caesar ciphers.
"""
def __init__(self, key: bytes, alphabet=bytes(string.ascii_lowercase, 'utf-8')):
"""
Parameters:
key (bytes): Bytes-like object to key the cipher.
alphabet (bytes): Alphabet (in order) to encrypt over. Input must also be in this alphabet.
"""
self.key = key
self.alphabet = alphabet
def encrypt(self, plaintext: bytes) -> Bytes:
"""
Encrypts `plaintext`.
Parameters:
plaintext (bytes): Bytes-like object to be encrypted.
Returns:
Bytes: Resulting ciphertext.
"""
result = []
for i, char in enumerate(plaintext):
k_i = bytes([self.key[i % len(self.key)]])
c_i_idx = (self.alphabet.index(bytes([char])) + self.alphabet.index(k_i)) % len(self.alphabet)
result.append(self.alphabet[c_i_idx])
return Bytes(bytes(result))
def decrypt(self, ciphertext: bytes) -> Bytes:
"""
Decrypts `ciphertext`.
Parameters:
ciphertext (bytes): Bytes-like object to be decrypted.
Returns:
Bytes: Resulting plaintext.
"""
result = []
for i, char in enumerate(ciphertext):
k_i = bytes([self.key[i % len(self.key)]])
p_i_idx = (self.alphabet.index(bytes([char])) - self.alphabet.index(k_i)) % len(self.alphabet)
result.append(self.alphabet[p_i_idx])
return Bytes(bytes(result))
@staticmethod
def break_vigenere(ciphertext: str, alphabet: bytes=bytes(string.ascii_lowercase, 'utf-8'), expected_distribution=letter_distribution, min_key_length: int=1, max_key_length: int=20):
ciphertext = Bytes.wrap(ciphertext)
cipher_scores = []
cipher_len = len(ciphertext)
analyzer = EnglishAnalyzer()
for i in range(min_key_length, max_key_length):
transposed = ciphertext.transpose(i)
total_key_score = 1
top_chunk_scores = []
for chunk in transposed.chunk(cipher_len // i):
curr_chunk_scores = []
for char in alphabet:
tmp_vig = Vigenere(bytes([char]))
new_chunk = tmp_vig.decrypt(chunk)
chunk_score = chisquare(count_items(new_chunk), expected_distribution)
curr_chunk_scores.append((char, chunk_score))
top_chunk_scores.append(sorted(curr_chunk_scores, key=lambda chunk_score: chunk_score[1], reverse=False)[0])
for chunk_score in top_chunk_scores:
total_key_score += chunk_score[1]
cipher_scores.append((total_key_score, top_chunk_scores))
analyzer_scores = []
for _total_score, top_chunk_scores in cipher_scores:
vig = Vigenere(bytes([char for char,score in top_chunk_scores]), alphabet=alphabet)
analyzer_scores.append((analyzer.analyze(vig.decrypt(ciphertext)) / len(vig.key), vig))
top_analyzed_score = sorted(analyzer_scores, key=lambda kv: kv[0], reverse=True)[0]
return top_analyzed_score[1]
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/classical/vigenere.py
| 0.657318 | 0.279453 |
vigenere.py
|
pypi
|
from math import ceil
def xor_buffs(buf1: bytes, buf2: bytes) -> bytearray:
"""
XORs two byte buffers.
Parameters:
buf1 (bytes): First byte buffer.
buf2 (bytes): Second byte buffer.
Returns:
bytearray: Resulting bytes.
"""
if len(buf1) != len(buf2):
raise ValueError('Buffers must be equal length.')
return bytearray([x ^ y for x, y in zip(buf1, buf2)])
def stretch_key(key: bytes, length: int, offset: int=0) -> bytes:
"""
Repeats a bytes object, `key`, until it reaches `length` shifted by `offset`.
Parameters:
length (int): Size to be stretched to.
offset (int): Offset to start from.
Returns:
bytes: Bytes stretched to `size`.
Examples:
>>> stretch_key(b'abc', 5)
b'abcab'
>>> stretch_key(b'abc', 5, offset=1)
b'cabca'
"""
offset_mod = offset % len(key)
key_stream = (key * ceil(length / len(key)))
complete_key = (key[-offset_mod:] + key_stream)[:length]
return complete_key
def transpose(ciphertext: bytes, size: int) -> list:
"""
Builds a matrix of `size` row-length and transposes the matrix.
Parameters:
size (int): Length of the rows/chunks.
Returns:
list: Transposed bytes.
"""
return [ciphertext[i::size] for i in range(size)]
def get_blocks(ciphertext: bytes, block_size: int=16, allow_partials: bool=False) -> list:
"""
Chunks the bytes into `size` length chunks.
Parameters:
size (int): Size of the chunks.
allow_partials (bool): Whether or not to allow the last chunk to be a partial.
Returns:
list: List of bytes.
"""
full_blocks = [ciphertext[i * block_size: (i + 1) * block_size] for i in range(len(ciphertext) // block_size)]
left_over = len(ciphertext) % block_size
if allow_partials and left_over > 0:
all_blocks = full_blocks + [ciphertext[-left_over:]]
else:
all_blocks = full_blocks
return all_blocks
def left_rotate(x: int, amount: int, bits: int=32) -> int:
"""
Performs a left-rotate.
Parameters:
x (int): Integer to rotate.
amount (int): Amount to rotate by.
bits (int): Bitspace to rotate over.
Returns:
int: Rotated integer.
"""
mask = 2 ** bits - 1
x &= mask
return ((x<<amount) | (x>>(bits-amount))) & mask
def right_rotate(x: int, amount: int, bits: int=32) -> int:
"""
Performs a right-rotate.
Parameters:
x (int): Integer to rotate.
amount (int): Amount to rotate by.
bits (int): Bitspace to rotate over.
Returns:
int: Rotated integer.
"""
mask = 2 ** bits - 1
return ((x>>amount) | (x<<(bits-amount))) & mask
def unxorshift_left(x: int, n: int, bits: int) -> int:
"""
Performs the reverse operation of `x` ^= (`x` << `n`) % 2**`bits`-1.
Parameters:
x (int): Integer to unxorshift.
n (int): Shift amount.
bits (int): Bitspace shifted over.
Returns:
int: Unxorshifted `x`.
"""
mask = 2**bits-1
y = x
for i in range(1, bits // n + 1):
y ^= (x << n*i) & mask
return y
def unxorshift_right(x: int, n: int, bits: int) -> int:
"""
Performs the reverse operation of `x` ^= `x` >> `n`.
Parameters:
x (int): Integer to unxorshift.
n (int): Shift amount.
bits (int): Bitspace shifted over.
Returns:
int: Unxorshifted `x`.
"""
y = x
for i in range(1, bits // n + 1):
y ^= (x >> n*i)
return y
def reverse_bits(x: int, bits: int) -> int:
"""
Reverses the bit ordering of an integer.
Parameters:
x (int): Integer to reverse.
bits (int): Bitspace to reverse.
Returns:
int: Reversed bit-order integer.
"""
y = 0
for _ in range(bits):
y = (y << 1) | (x & 1)
x >>= 1
return y
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/utilities/manipulation.py
| 0.912 | 0.699755 |
manipulation.py
|
pypi
|
from samson.utilities.manipulation import get_blocks, transpose, stretch_key
from samson.utilities.general import rand_bytes
from samson.utilities.bytes import Bytes
import math
from collections import UserString
def _zfill(bs, size, byteorder):
zeroes = max(size - len(bs), 0) * '0'
if byteorder == 'big':
new_bitstring = zeroes + bs
else:
new_bitstring = bs + zeroes
return new_bitstring
class Bitstring(UserString):
"""
Bitvector manipulation class. Supports popular manipulations such as XOR, stretching, chunking, transposing, and rotations.
Manipulations always return a new Bitstring instance instead of editing the old one.
"""
def __init__(self, value: bytes, byteorder: str='big', auto_fill: bool=True):
"""
Parameters:
value (bytes): Bytes, integer, or string of 1s and 0s.
byteorder (str): Byteorder for integer and byte conversions.
auto_fill (bool): Whether or not to automatically zero fill to the next byte.
"""
if type(value) is bytes or type(value) is bytearray or type(value) is Bytes:
value = int.from_bytes(value, byteorder)
if type(value) is int:
value = bin(value)[2:]
if auto_fill:
value = _zfill(value, math.ceil(len(value) / 8) * 8, byteorder)
if not all([bit in ['0', '1'] for bit in str(value)]):
raise ValueError("Bitstrings can only contain 1's or 0's.")
super().__init__(value)
self.byteorder = byteorder
self.auto_fill = auto_fill
def _format_return(self, value: bytes):
"""
Internal function. Used to reformat the Bitstring after manipulations for ease of use.
"""
return Bitstring(str(Bitstring(value, 'big', auto_fill=self.auto_fill).zfill(len(self))), self.byteorder, auto_fill=self.auto_fill)
@staticmethod
def wrap(value: bytes, byteorder: str='big', auto_fill: bool=True):
"""
Conditional initialization. Only creates a new Bitstring object if it already isn't one.
Parameters:
value (bytes): Bytes, integer, or string of 1s and 0s.
byteorder (str): Byteorder for integer and byte conversions.
auto_fill (bool): Whether or not to automatically zero fill to the next byte.
Returns:
Bitstring: A Bitstring representation of the object.
"""
if isinstance(value, Bitstring):
return value
else:
return Bitstring(value, byteorder=byteorder, auto_fill=auto_fill)
@staticmethod
def random(size: int=16, byteorder: str='big'):
"""
Generates a random Bitstring object using /dev/urandom.
Parameters:
size (int): Number of bytes to generate.
byteorder (int): Byteorder.
Returns:
Bitstring: Random Bitstring.
"""
return Bitstring(rand_bytes(math.ceil(size / 8)), byteorder=byteorder)[:size]
def __repr__(self):
return f'<Bitstring: {" ".join([str(chunk) for chunk in self.zfill(math.ceil(max(1, len(self)) / 8) * 8).chunk(8)])}, byteorder=\'{self.byteorder}\'>'
# Byte order will be the downfall of humanity.
def _clean_byteorder(self, value):
value.byteorder = 'big'
return value.int()
def __xor__(self, other):
other = Bitstring.wrap(other, self.byteorder, auto_fill=self.auto_fill).bytes()
result = self._clean_byteorder(self.bytes() ^ other)
return self._format_return(result)
def __rxor__(self, other):
return self.__xor__(other)
def __getitem__(self, index):
return Bitstring(UserString.__getitem__(self, index), self.byteorder)
def __and__(self, other):
other = Bitstring.wrap(other, self.byteorder, auto_fill=self.auto_fill).bytes()
result = self._clean_byteorder(self.bytes() & other)
return self._format_return(result)
def __rand__(self, other):
return self.__and__(other)
def __or__(self, other):
other = Bitstring.wrap(other, self.byteorder, auto_fill=self.auto_fill).bytes()
result = self._clean_byteorder(self.bytes() | other)
return self._format_return(result)
def __ror__(self, other):
return self.__or__(other)
def __add__(self, other):
return Bitstring(UserString.__add__(self, other), self.byteorder, auto_fill=self.auto_fill)
def __radd__(self, other):
return Bitstring(UserString(other).__add__(self), self.byteorder, auto_fill=self.auto_fill)
def __lshift__(self, num):
return self._format_return(self.bytes() << num)
def __rshift__(self, num):
return self._format_return(self.bytes() >> num)
def __invert__(self):
max_val = 2 ** len(self) - 1
return self._format_return(max_val - self.int())
def lrot(self, amount: int, bits: int=None) -> 'Bitstring':
"""
Performs a left-rotate.
Parameters:
amount (int): Amount to rotate by.
bits (int): Bitspace to rotate over.
Returns:
Bitstring: A new instance of Bitstring with the transformation applied.
"""
return self._format_return(self.bytes().lrot(amount, bits=bits))
def rrot(self, amount: int, bits: int=None) -> 'Bitstring':
"""
Performs a right-rotate.
Parameters:
amount (int): Amount to rotate by.
bits (int): Bitspace to rotate over.
Returns:
Bitstring: A new instance of Bitstring with the transformation applied.
"""
return self._format_return(self.bytes().rrot(amount, bits=bits))
def chunk(self, size: int, allow_partials: bool=False) -> list:
"""
Chunks the Bitstring into `size` length chunks.
Parameters:
size (int): Size of the chunks.
allow_partials (bool): Whether or not to allow the last chunk to be a partial.
Returns:
list: List of Bitstrings.
"""
return get_blocks(self, size, allow_partials)
def transpose(self, size: int) -> 'Bitstring':
"""
Builds a matrix of `size` row-length, transposes the matrix, and collapses it back into a Bitstring object.
Parameters:
size (int): Length of the rows/chunks.
Returns:
Bitstring: Transposed bits.
"""
return self._format_return(''.join(transpose(str(self), size)))
def zfill(self, size: int) -> 'Bitstring':
"""
Fills the Bitstring to specified size with 0 bits _such that the integer representation stays the same according to the byteorder_.
Parameters:
size (int): Size of the resulting Bitstring.
Returns:
Bitstring: Bitstring padded with zeroes.
"""
return _zfill(self, size, self.byteorder)
def stretch(self, size: int, offset: int=0) -> 'Bitstring':
"""
Repeats a Bitstring object until it reaches `size` length shifted by `offset`.
Parameters:
size (int): Size to be stretched to.
offset (int): Offset to start from.
Returns:
Bitstring: Bitstring stretched to `size`.
Examples:
>>> stretch_key(b'abc', 5)
b'abcab'
>>> stretch_key(b'abc', 5, offset=1)
b'cabca'
"""
return self._format_return(stretch_key(self, size, offset))
def to_int(self) -> int:
"""
Converts to an integer representation.
Returns:
int: Integer representation.
"""
return self.bytes().int()
def int(self) -> int:
"""
Converts to an integer representation.
Returns:
int: Integer representation.
"""
return self.to_int()
def to_bytes(self) -> Bytes:
"""
Converts to a Bytes representation.
Returns:
Bytes: Bytes representation.
"""
return Bytes([int(str(chunk), 2) for chunk in self.zfill(self.byte_length()).chunk(8, allow_partials=True)], self.byteorder)
def bytes(self) -> Bytes:
"""
Converts to a Bytes representation.
Returns:
Bytes: Bytes representation.
"""
return self.to_bytes()
def byte_length(self) -> int:
"""
The Bitstrings length to the nearest byte.
Returns:
int: The Bitstring's byte-length.
"""
return math.ceil(len(self) / 8)
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/utilities/bitstring.py
| 0.740925 | 0.431584 |
bitstring.py
|
pypi
|
from samson.utilities.manipulation import xor_buffs, left_rotate, right_rotate, get_blocks, transpose, stretch_key
from samson.encoding.general import int_to_bytes
from samson.utilities.general import rand_bytes
from copy import deepcopy
import codecs
class Bytes(bytearray):
"""
Bytearray convenience class. Supports popular manipulations such as XOR, stretching, chunking, transposing, and rotations.
Manipulations always return a new Bytes instance instead of editing the old one.
"""
def __init__(self, bytes_like: bytes=b'', byteorder: str='big'):
"""
Parameters:
bytes_like (bytes): Any bytes-like interface or integer. Integers will be converted using the byteorder.
byteorder (str): Byte order of the input. Will be used when converting between integer and byte representations.
"""
if issubclass(type(bytes_like), int):
bytes_like = int_to_bytes(bytes_like, byteorder)
# Unfortunately, we need this for pickling
if type(bytes_like) is str:
bytes_like = bytes_like.encode('latin-1')
super().__init__(bytes_like)
self.byteorder = byteorder
@staticmethod
def wrap(bytes_like: bytes, byteorder: str='big') -> 'Bytes':
"""
Conditional initialization. Only creates a new Bytes object if it already isn't one.
Parameters:
bytes_like (bytes): Any bytes-like interface or integer. Integers will be converted using the byteorder.
byteorder (str): Byte order of the input. Will be used when converting between integer and byte representations.
Returns:
Bytes: A Bytes representation of the object.
"""
if isinstance(bytes_like, Bytes):
return bytes_like
else:
return Bytes(bytes_like, byteorder=byteorder)
@staticmethod
def random(size: int=16, byteorder: str='big') -> 'Bytes':
"""
Generates a random Bytes object using /dev/urandom.
Parameters:
size (int): Number of bytes to generate.
byteorder (int): Byteorder.
Returns:
Bytes: Random Bytes.
"""
return Bytes(rand_bytes(size), byteorder=byteorder)
@staticmethod
def read_file(filename: str) -> 'Bytes':
with open(filename, 'rb') as f:
return Bytes(f.read())
def write_file(self, filename: str) -> int:
with open(filename, 'wb') as f:
return f.write(self)
def __repr__(self):
return f"<Bytes: {str(bytes(self))}, byteorder='{self.byteorder}'>"
def __str__(self):
return self.__repr__()
def __hash__(self):
return hash(self.int())
def __deepcopy__(self, memo):
result = Bytes(bytes_like=bytearray(self), byteorder=self.byteorder)
memo[id(self)] = result
return result
# Operators
def __xor__(self, other):
if type(other) is int:
return Bytes(int.to_bytes(self.to_int() ^ other, len(self), self.byteorder), self.byteorder)
else:
return Bytes(xor_buffs(self, other), self.byteorder)
def __rxor__(self, other):
return self.__xor__(other)
def __getitem__(self, index):
result = bytearray.__getitem__(self, index)
if type(result) is int:
return result
else:
return Bytes(result, self.byteorder)
def __and__(self, other):
other_as_int = other
if not type(other) is int:
other_as_int = int.from_bytes(other, self.byteorder)
return Bytes(int.to_bytes(self.to_int() & other_as_int, len(self), self.byteorder), self.byteorder)
def __rand__(self, other):
return self.__and__(other)
def __or__(self, other):
other_as_int = other
if not type(other) is int:
other_as_int = int.from_bytes(other, self.byteorder)
return Bytes(int.to_bytes(self.to_int() | other_as_int, len(self), self.byteorder), self.byteorder)
def __ror__(self, other):
return self.__or__(other)
def __add__(self, other):
return Bytes(bytearray.__add__(self, other), self.byteorder)
def __radd__(self, other):
return Bytes(bytearray(other).__add__(self), self.byteorder)
def __lshift__(self, num):
return Bytes(int.to_bytes((self.to_int() << num) % (2**(len(self) * 8)), len(self), self.byteorder))
def __rshift__(self, num):
return Bytes(int.to_bytes((self.to_int() >> num) % (2**(len(self) * 8)), len(self), self.byteorder))
def __invert__(self):
max_val = 2 ** (len(self) * 8) - 1
return Bytes(max_val - self.to_int(), self.byteorder)
# Manipulations
def lrot(self, amount: int, bits: int=None) -> 'Bytes':
"""
Performs a left-rotate.
Parameters:
amount (int): Amount to rotate by.
bits (int): Bitspace to rotate over.
Returns:
Bytes: A new instance of Bytes with the transformation applied.
"""
if not bits:
bits = len(self) * 8
back_to_bytes = int.to_bytes(left_rotate(self.to_int(), amount % bits, bits), bits // 8, self.byteorder)
return Bytes(back_to_bytes, self.byteorder)
def rrot(self, amount: int, bits: int=None) -> 'Bytes':
"""
Performs a right-rotate.
Parameters:
amount (int): Amount to rotate by.
bits (int): Bitspace to rotate over.
Returns:
Bytes: A new instance of Bytes with the transformation applied.
"""
if not bits:
bits = len(self) * 8
back_to_bytes = int.to_bytes(right_rotate(self.to_int(), amount % bits, bits), bits // 8, self.byteorder)
return Bytes(back_to_bytes, self.byteorder)
def chunk(self, size: int, allow_partials: bool=False) -> list:
"""
Chunks the Bytes into `size` length chunks.
Parameters:
size (int): Size of the chunks.
allow_partials (bool): Whether or not to allow the last chunk to be a partial.
Returns:
list: List of Bytes.
"""
return get_blocks(self, size, allow_partials)
def transpose(self, size: int) -> 'Bytes':
"""
Builds a matrix of `size` row-length, transposes the matrix, and collapses it back into a Bytes object.
Parameters:
size (int): Length of the rows/chunks.
Returns:
Bytes: Transposed bytes.
"""
return Bytes(b''.join(transpose(self, size)), self.byteorder)
def zfill(self, size: int) -> 'Bytes':
"""
Fills the Bytes to specified size with NUL bytes _such that the integer representation stays the same according to the byteorder_.
Parameters:
size (int): Size of the resulting Bytes.
Returns:
Bytes: Bytes padded with zeroes.
"""
return Bytes(int.to_bytes(self.to_int(), size, self.byteorder), self.byteorder)
def pad_congruent_left(self, congruence: int, pad_byte: bytes=b'\x00') -> 'Bytes':
"""
Pads the bytes left until the length is congruent to `congruence`.
Parameters:
congruence (int): What the size should be congruent to.
pad_byte (bytes): Byte to pad with.
Returns:
Bytes: Padded bytes.
"""
return ((congruence - (len(self) % congruence)) % congruence) * pad_byte + self
def pad_congruent_right(self, congruence: int, pad_byte: bytes=b'\x00') -> 'Bytes':
"""
Pads the bytes right until the length is congruent to `congruence`.
Parameters:
congruence (int): What the size should be congruent to.
pad_byte (bytes): Byte to pad with.
Returns:
Bytes: Padded bytes.
"""
return self + ((congruence - (len(self) % congruence)) % congruence) * pad_byte
def stretch(self, size: int, offset: int=0) -> 'Bytes':
"""
Repeats a Bytes object until it reaches `size` length shifted by `offset`.
Parameters:
size (int): Size to be stretched to.
offset (int): Offset to start from.
Returns:
Bytes: Bytes stretched to `size`.
Examples:
>>> stretch_key(b'abc', 5)
b'abcab'
>>> stretch_key(b'abc', 5, offset=1)
b'cabca'
"""
return Bytes(stretch_key(self, size, offset), self.byteorder)
def change_byteorder(self, byteorder: str=None) -> 'Bytes':
"""
Changes the byteorder WITHOUT reordering the bytes. This is useful
for interpreting an existing byte string differently.
Parameters:
byteorder (str): Byteorder to switch to. If not specified, defaults to the opposite of `self`.
Returns:
Bytes: Swapped order bytes.
"""
o = deepcopy(self)
if not byteorder:
byteorder = 'little' if self.byteorder == 'big' else 'big'
o.byteorder = byteorder
return o
def unpack_length_encoded(self, length_size: int=2) -> list:
curr = self
parts = []
while len(curr):
length = curr[:length_size].int()
data = curr[length_size:length+length_size]
parts.append(data)
curr = curr[length+length_size:]
return parts
# Conversions
def to_int(self) -> int:
"""
Converts to an integer representation.
Returns:
int: Integer representation.
"""
return int.from_bytes(self, self.byteorder)
def int(self) -> int:
"""
Converts to an integer representation.
Returns:
int: Integer representation.
"""
return self.to_int()
def to_hex(self) -> 'Bytes':
"""
Converts to an hex representation.
Returns:
Bytes: Hex representation.
"""
return Bytes(codecs.encode(self, 'hex_codec'), self.byteorder)
def hex(self) -> 'Bytes':
"""
Converts to an hex representation.
Returns:
Bytes: Hex representation.
"""
return self.to_hex()
def unhex(self) -> 'Bytes':
"""
Converts from an hex representation.
Returns:
Bytes: Raw bytes representation.
"""
return Bytes(codecs.decode(self, 'hex_codec'), self.byteorder)
def to_bin(self) -> 'Bitstring':
"""
Converts to a Bitstring representation.
Returns:
Bitstring: Bitstring representation.
"""
from samson.utilities.bitstring import Bitstring
return Bitstring(self, byteorder=self.byteorder).zfill(len(self) * 8)
def bin(self) -> 'Bitstring':
"""
Converts to a Bitstring representation.
Returns:
Bitstring: Bitstring representation.
"""
return self.to_bin()
def to_bits(self) -> 'Bitstring':
"""
Converts to a Bitstring representation.
Returns:
Bitstring: Bitstring representation.
"""
return self.to_bin()
def bits(self) -> 'Bitstring':
"""
Converts to a Bitstring representation.
Returns:
Bitstring: Bitstring representation.
"""
return self.to_bits()
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/utilities/bytes.py
| 0.869507 | 0.517815 |
bytes.py
|
pypi
|
from samson.protocols.diffie_hellman import DiffieHellman
from samson.utilities.bytes import Bytes
from samson.math.general import mod_inv, random_int_between
from samson.core.primitives import NumberTheoreticalAlg, Primitive
from samson.core.metadata import EphemeralType, EphemeralSpec, SizeType, SizeSpec, FrequencyType
from samson.ace.decorators import register_primitive
@register_primitive()
class ElGamal(NumberTheoreticalAlg):
"""
ElGamal public key encryption
"""
EPHEMERAL = EphemeralSpec(ephemeral_type=EphemeralType.KEY, size=SizeSpec(size_type=SizeType.DEPENDENT, selector=lambda elgamal: elgamal.p.bit_length()))
USAGE_FREQUENCY = FrequencyType.UNUSUAL
def __init__(self, g: int=2, p: int=DiffieHellman.MODP_2048, key: int=None):
"""
Parameters:
g (int): Generator.
p (int): Prime modulus.
key (int): Key.
"""
Primitive.__init__(self)
self.key = key or random_int_between(1, p)
self.g = g
self.p = p
self.pub = pow(self.g, self.key, self.p)
def encrypt(self, plaintext: bytes, k: int=None) -> (int, int):
"""
Encrypts `plaintext`.
Parameters:
plaintext (bytes): Message to encrypt.
k (int): (Optional) Ephemeral key.
Returns:
(int, int): Formatted as (ephemeral key, ciphertext).
References:
https://en.wikipedia.org/wiki/ElGamal_encryption
"""
K_e = k or random_int_between(1, self.p)
c_1 = pow(self.g, K_e, self.p)
s = pow(self.pub, K_e, self.p)
plaintext = Bytes.wrap(plaintext)
return c_1, (s * plaintext.int()) % self.p
def decrypt(self, key_and_ciphertext: (int ,int)) -> Bytes:
"""
Decrypts `key_and_ciphertext`.
Parameters:
key_and_ciphertext ((int, int)): Ephemeral key and ciphertext.
Returns:
Bytes: Plaintext.
"""
c_1, ciphertext = key_and_ciphertext
s = pow(c_1, self.key, self.p)
return Bytes((mod_inv(s, self.p) * ciphertext) % self.p)
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/public_key/elgamal.py
| 0.823293 | 0.163579 |
elgamal.py
|
pypi
|
from samson.math.general import mod_inv, find_prime, random_int_between, is_prime
from samson.utilities.bytes import Bytes
from samson.encoding.openssh.openssh_dsa_key import OpenSSHDSAPrivateKey, OpenSSHDSAPublicKey, SSH2DSAPublicKey
from samson.encoding.x509.x509_dsa_public_key import X509DSAPublicKey
from samson.encoding.pkcs1.pkcs1_dsa_private_key import PKCS1DSAPrivateKey
from samson.encoding.pkcs8.pkcs8_dsa_private_key import PKCS8DSAPrivateKey
from samson.encoding.x509.x509_dsa_certificate import X509DSACertificate, X509DSASigningAlgorithms, X509DSACertificateSigningRequest, X509DSAParams
from samson.encoding.general import PKIEncoding
from samson.core.encodable_pki import EncodablePKI
from samson.core.primitives import SignatureAlg, Primitive
from samson.core.metadata import EphemeralType, EphemeralSpec, SizeType, SizeSpec, FrequencyType
from samson.ace.decorators import register_primitive
from samson.hashes.sha2 import SHA256
@register_primitive()
class DSA(EncodablePKI, SignatureAlg):
"""
Digital Signature Algorithm
"""
PRIV_ENCODINGS = {
PKIEncoding.OpenSSH: OpenSSHDSAPrivateKey,
PKIEncoding.PKCS1: PKCS1DSAPrivateKey,
PKIEncoding.PKCS8: PKCS8DSAPrivateKey
}
PUB_ENCODINGS = {
PKIEncoding.OpenSSH: OpenSSHDSAPublicKey,
PKIEncoding.SSH2: SSH2DSAPublicKey,
PKIEncoding.X509_CERT: X509DSACertificate,
PKIEncoding.X509: X509DSAPublicKey,
PKIEncoding.X509_CSR: X509DSACertificateSigningRequest
}
X509_SIGNING_ALGORITHMS = X509DSASigningAlgorithms
X509_SIGNING_DEFAULT = X509DSASigningAlgorithms.id_dsa_with_sha256
X509_SIGNING_PARAMS = X509DSAParams
EPHEMERAL = EphemeralSpec(ephemeral_type=EphemeralType.KEY, size=SizeSpec(size_type=SizeType.DEPENDENT, selector=lambda dsa: dsa.q.bit_length()))
USAGE_FREQUENCY = FrequencyType.OFTEN
def __init__(self, hash_obj: object=SHA256(), p: int=None, q: int=None, g: int=None, x: int=None, L: int=2048, N: int=256):
"""
Parameters:
hash_obj (object): Instantiated object with compatible hash interface.
p (int): (Optional) Prime modulus.
q (int): (Optional) Prime modulus.
g (int): (Optional) Generator.
x (int): (Optional) Private key.
L (int): (Optional) Bit length of `p`.
N (int): (Optional) Bit length of `q`.
"""
Primitive.__init__(self)
# Parameter generation
# https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
if not q:
q = find_prime(N)
# Start somewhere in 2**(L-1); ensure it's even
i = Bytes.random((L-1) // 8).int() // 2 * 2
# Construct the base as an even multiple of `q`
base = 2**(L-1) // (2*q) * 2
while not is_prime((base + i) * q + 1):
i += 2
p = (base + i) * q + 1
assert (p-1) % q == 0
# Construct `g`
while True:
h = Bytes.random(N // 8).int() % (p-1)
g = pow(h, (p-1) // q, p)
if h > 1 and h < (p-1) and g > 1:
break
self.p = p
self.q = q
self.g = g
self.x = x or random_int_between(1, self.q)
self.y = pow(self.g, self.x, self.p)
self.hash_obj = hash_obj
def __reprdir__(self):
return ['hash_obj', 'p', 'q', 'g', 'x', 'y']
def sign(self, message: bytes, k: int=None) -> (int, int):
"""
Signs a `message`.
Parameters:
message (bytes): Message to sign.
k (int): (Optional) Ephemeral key.
Returns:
(int, int): Signature formatted as (r, s).
"""
k = k or random_int_between(1, self.q)
inv_k = mod_inv(k, self.q)
r = pow(self.g, k, self.p) % self.q
s = (inv_k * (self.hash_obj.hash(message).int() + self.x * r)) % self.q
return (r, s)
def verify(self, message: bytes, sig: (int, int)) -> bool:
"""
Verifies a `message` against a `sig`.
Parameters:
message (bytes): Message.
sig ((int, int)): Signature of `message`.
Returns:
bool: Whether the signature is valid or not.
"""
(r, s) = sig
w = mod_inv(s, self.q)
u_1 = (self.hash_obj.hash(message).int() * w) % self.q
u_2 = (r * w) % self.q
v = (pow(self.g, u_1, self.p) * pow(self.y, u_2, self.p) % self.p) % self.q
return v == r
# Confirmed works on ECDSA as well
def derive_k_from_sigs(self, msg_a: bytes, sig_a: (int, int), msg_b: bytes, sig_b: (int, int)) -> int:
"""
Derives `k` from signatures that share an `r` value.
Parameters:
msg_a (bytes): Message A.
msg_b (bytes): Message B.
sig_a ((int, int)): Signature of `msg_a`.
sig_b ((int, int)): Signature of `msg_b`.
Returns:
int: Derived `k`.
"""
(r_a, s_a) = sig_a
(r_b, s_b) = sig_b
if r_a != r_b:
raise ValueError('Signatures do not share an `r` value')
s = (s_a - s_b) % self.q
m = (self.hash_obj.hash(msg_a).int() - self.hash_obj.hash(msg_b).int()) % self.q
return mod_inv(s, self.q) * m % self.q
# Confirmed works on ECDSA as well
def derive_x_from_k(self, message: bytes, k: int, sig: (int, int)) -> int:
"""
Derives `x` from a known `k`.
Parameters:
message (bytes): Message.
k (int): `k` used in `message`'s signature.
sig ((int, int)): Signature of `message`.
Returns:
int: Derived `x`.
"""
(r, s) = sig
return ((s * k) - self.hash_obj.hash(message).int()) * mod_inv(r, self.q) % self.q
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/public_key/dsa.py
| 0.721154 | 0.178812 |
dsa.py
|
pypi
|
from samson.math.polynomial import Polynomial
from samson.math.symbols import Symbol
from samson.math.algebra.rings.integer_ring import ZZ
from samson.utilities.exceptions import NotInvertibleException
from samson.utilities.general import shuffle
from samson.math.general import is_power_of_two, is_prime, mod_inv
from samson.utilities.bytes import Bytes
from samson.core.primitives import NumberTheoreticalAlg, Primitive
from samson.core.metadata import EphemeralType, EphemeralSpec, SizeType, SizeSpec, SecurityProofType, FrequencyType
from samson.ace.decorators import register_primitive
import math
x = Symbol('x')
P = ZZ[x]
def all_coeffs(poly: Polynomial) -> list:
"""
Returns the coefficients of a `poly` as a dense integer vector.
Parameters:
poly (Polynomial): Polynomial.
Returns:
list: Integer vector.
"""
return [int(poly.coeffs[i]) for i in range(poly.coeffs.last() + 1)]
def minimize_poly(poly: Polynomial, mod: int) -> list:
"""
Minimizes the absolute distance between coefficients and zero in a symmetric ring.
Parameters:
poly (Polynomial): Polynomial.
mod (int): Modulus.
Returns:
list: Coefficient list.
"""
return [coeff - mod if abs(coeff - mod) < coeff else coeff for coeff in all_coeffs(poly)]
def encode_bytes(in_arr: list) -> Bytes:
"""
Encodes a list of numbers as Bytes.
Parameters:
in_arr (list): List to encode.
Returns:
Bytes: List encoded as Bytes.
"""
return Bytes([num % 256 for num in in_arr])
def decode_bytes(in_bytes: bytes) -> list:
"""
Decodes bytes into a list.
Parameters:
in_bytes (bytes): Bytes to decode.
Returns:
list: List of integer representations of the bytes.
"""
return [num - 256 if num > 127 else num for num in in_bytes]
def rand_poly(length: int, len_non_zeroes: int, neg_ones_mod: int=0) -> Polynomial:
"""
Generates a random polynomial.
Parameters:
length (int): Desired length of polynomial.
len_non_zeroes (int): Number of non-zero values in polynomial.
neg_ones_mod (int): Modifier that reduces the number of -1 coefficients.
Returns:
Polynomial: Random polynomial.
"""
poly_arr = [0] * ((length - len_non_zeroes * 2) + neg_ones_mod)
poly_arr += [1] * len_non_zeroes
poly_arr += [-1] * (len_non_zeroes - neg_ones_mod)
shuffle(poly_arr)
return Polynomial(poly_arr, ZZ)
def invert_poly(f_poly: Polynomial, R_poly: Polynomial, p: int) -> Polynomial:
"""
Inverts a polynomial `f_poly` over `R_poly` in GF(p).
Parameters:
f_poly (Polynomial): Polynomial to be inverted.
R_poly (Polynomial): Polynomial to be inverted _over_.
p (int): Integer modulus.
Returns:
Polynomial: Inverted polynomial.
"""
power_of_two = is_power_of_two(p)
if is_prime(p) or power_of_two:
if power_of_two:
Z_p = ZZ/ZZ(2)
else:
Z_p = ZZ/ZZ(p)
f_poly_p = Polynomial([(idx, Z_p[coeff]) for idx, coeff in f_poly.coeffs], Z_p)
R_poly_p = Polynomial([(idx, Z_p[coeff]) for idx, coeff in R_poly.coeffs], Z_p)
inv_poly = mod_inv(f_poly_p, R_poly_p)
inv_poly = Polynomial([(idx, ZZ[int(coeff)]) for idx, coeff in inv_poly.coeffs], ZZ)
if power_of_two:
for _ in range(int(math.log(p, 2))):
inv_poly = (2 * inv_poly) - (f_poly * (inv_poly ** 2))
inv_poly = (inv_poly % R_poly).trunc(p)
else:
raise NotInvertibleException(f"Polynomial not invertible in Z_{p}. NTRU: p and q must be prime or power of two.")
return inv_poly
# https://en.wikipedia.org/wiki/NTRUEncrypt
@register_primitive()
class NTRU(NumberTheoreticalAlg):
"""
Nth-degree TRUncated polynomial ring
"""
SECURITY_PROOF = SecurityProofType.SHORTEST_VECTOR
KEY_SIZE = SizeSpec(size_type=SizeType.ARBITRARY, typical=[167, 251, 347, 503])
EPHEMERAL = EphemeralSpec(ephemeral_type=EphemeralType.KEY, size=SizeSpec(size_type=SizeType.DEPENDENT, selector=lambda ntru: ntru.N))
USAGE_FREQUENCY = FrequencyType.UNUSUAL
def __init__(self, N: int, p: int=3, q: int=128, f_poly: Polynomial=None, g_poly: Polynomial=None):
"""
Parameters:
N (int): Polynomial degree/modulus.
p (int): Small modulus.
q (int): Large modulus.
f_poly (Polynomial): F-polynomial of private key.
g_poly (Polynomial): G-polynomial of private key.
"""
Primitive.__init__(self)
self.N = N
self.p = p
self.q = q
self.R_poly = x**N - 1
self.f_poly = f_poly
self.g_poly = g_poly
self.h_poly = None
priv_not_specified = [poly is None for poly in [f_poly, g_poly]]
# Generate random keys
if all(priv_not_specified):
self.generate_random_keys()
# Tried to specify only part of private key
elif any(priv_not_specified):
raise ValueError("Must provide ALL values for private key: f_poly, g_poly")
# Specified private key, but not public key
else:
self.generate_public_key()
def generate_random_keys(self):
"""
Generates random private and public keys.
"""
self.g_poly = rand_poly(self.N, int(math.sqrt(self.q)))
while True:
try:
self.f_poly = rand_poly(self.N, self.N // 3, neg_ones_mod=1)
self.generate_public_key()
break
except NotInvertibleException:
pass
def generate_public_key(self):
"""
Attempts to find the public key for the current private key. May throw `NotInvertibleException`.
"""
self.f_p_poly = invert_poly(self.f_poly, self.R_poly, self.p)
self.f_q_poly = invert_poly(self.f_poly, self.R_poly, self.q)
p_f_q_poly = (self.p * self.f_q_poly).trunc(self.q)
pfq_trunc = (p_f_q_poly * self.g_poly).trunc(self.q)
self.h_poly = (pfq_trunc % self.R_poly).trunc(self.q)
def encrypt(self, plaintext: bytes, random_poly: Polynomial=None) -> Bytes:
"""
Encrypts `plaintext`.
Parameters:
plaintext (bytes): Plaintext to encrypt.
random_poly (Polynomial): (Optional) The random polynomial used in encryption.
Returns:
Bytes: Encrypted ciphertext.
"""
random_poly = random_poly or rand_poly(self.N, int(math.sqrt(self.q)))
# Convert plaintext into polynomial
pt_poly = P([int(bit) for bit in bin(int.from_bytes(plaintext, 'big'))[2:].zfill(len(plaintext) * 8)])
rhm = (random_poly * self.h_poly).trunc(self.q) + pt_poly
ct_poly = (rhm % self.R_poly).trunc(self.q)
return encode_bytes(minimize_poly(ct_poly, self.q))
def decrypt(self, ciphertext: bytes) -> Bytes:
"""
Decrypts `ciphertext` into plaintext.
Parameters:
ciphertext (bytes): Ciphertext.
Returns:
Bytes: Decrypted plaintext.
"""
# Convert ciphertext into polynomial
ct_poly = decode_bytes(ciphertext)
msg_poly = P(ct_poly)
a_poly = ((self.f_poly * msg_poly) % self.R_poly).trunc(self.q)
a_poly = P(minimize_poly(a_poly, self.q))
b_poly = a_poly.trunc(self.p)
pt_poly = ((self.f_p_poly * b_poly) % self.R_poly).trunc(self.p)
bit_length = math.ceil(pt_poly.coeffs.len() / 8) * 8
pt_bitstring = ''.join([str(bit % 2) for bit in all_coeffs(pt_poly)])[::-1].zfill(bit_length)[::-1]
return Bytes(int(pt_bitstring, 2)).zfill(bit_length // 8)
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/public_key/ntru.py
| 0.926154 | 0.561185 |
ntru.py
|
pypi
|
from samson.math.general import mod_inv, generate_superincreasing_seq, find_coprime
from samson.utilities.bytes import Bytes
from samson.utilities.runtime import RUNTIME
from samson.core.primitives import EncryptionAlg
class MerkleHellmanKnapsack(EncryptionAlg):
"""
Merkle-Hellman Knapsack cryptosystem.
Broken and extremely rare cryptosystem based off of the hardness of the Knapsack problem.
"""
def __init__(self, priv: list=None, q: int=None, r: int=None, max_diff: int=2**20, key_len: int=8):
"""
Parameters:
priv (list): Private key made from a superincreasing sequence.
q (int): Modulus. Integer greater than the sum of `priv`.
r (int): Multiplier. Integer coprime to `q` and between `q // 4` and `q`.
max_diff (int): Maximum difference between integers in the superincreasing sequence. Used for generating `priv`.
key_len (int): Desired length of the key.
"""
super_seq = generate_superincreasing_seq(key_len + 1, max_diff, starting=Bytes.random(max(1, key_len // 8)).int())
self.priv = priv or super_seq[:key_len]
self.q = q or super_seq[-1]
self.r = r or find_coprime(self.q, range(self.q // 4, self.q))
self.pub = [(w * self.r) % self.q for w in self.priv]
def __reprdir__(self):
return ['priv', 'pub', 'q', 'r']
def encrypt(self, message: bytes) -> list:
"""
Encrypt `message`.
Parameters:
message (bytes): Message to encrypt.
Returns:
list: List of ciphertext integers. List cardinality dependent on message/key-length ratio.
"""
bin_str = ''
for byte in message:
bin_str += bin(byte)[2:].zfill(8)
all_sums = []
for i in range(len(bin_str) // len(self.pub)):
byte_str = bin_str[i * len(self.pub):(i + 1) * len(self.pub)]
all_sums.append(sum([int(byte_str[j]) * self.pub[j] for j in range(len(self.pub))]))
return all_sums
def decrypt(self, sums: list) -> Bytes:
"""
Decrypts `sums` back into plaintext.
Parameters:
sums (list): List of ciphertext sums.
Returns:
Bytes: Decrypted plaintext.
"""
r_inv = mod_inv(self.r, self.q)
inv_sums = [(byte_sum * r_inv) % self.q for byte_sum in sums]
plaintext = Bytes(b'')
for inv_sum in inv_sums:
curr = inv_sum
bin_string = ''
for i in range(len(self.pub) - 1, -1, -1):
if self.priv[i] <= curr:
curr -= self.priv[i]
bin_string += '1'
else:
bin_string += '0'
plaintext += int.to_bytes(int(bin_string[::-1], 2), len(self.pub) // 8, 'big')
return plaintext
@classmethod
@RUNTIME.report
def recover_plaintext(cls: object, ciphertext: int, pub: list, alpha: int=1) -> Bytes:
"""
Attempts to recover the plaintext without the private key.
Parameters:
ciphertext (int): A ciphertext sum.
pub (int): The public key.
alpha (int): Punishment coefficient for deviation from guessed bit distribution.
Returns:
Bytes: Recovered plaintext.
"""
from samson.math.matrix import Matrix
from samson.math.algebra.all import QQ
# Construct the problem matrix
ident = Matrix.identity(len(pub), coeff_ring=QQ)
pub_matrix = ident.col_join(Matrix([pub], coeff_ring=QQ))
problem_matrix = pub_matrix.row_join(Matrix([[0] * len(pub) + [-ciphertext]], coeff_ring=QQ).T)
# Attempt to crack the ciphertext using various punishment coefficients
for i in RUNTIME.report_progress(range(len(pub)), desc='Alphaspace searched'):
alpha_penalizer = Matrix([[alpha] * len(pub) + [-alpha * i]], coeff_ring=QQ)
problem_matrix_prime = problem_matrix.col_join(alpha_penalizer).T
solution_matrix = problem_matrix_prime.LLL(0.99)
for row in solution_matrix.rows:
relevant = row[:-2]
new_row = [item for item in relevant if item >= QQ.zero and item <= QQ.one]
if len(new_row) == len(relevant):
return Bytes(int(''.join([str(int(float(val))) for val in relevant]), 2))
return solution_matrix
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/public_key/merkle_hellman_knapsack.py
| 0.851953 | 0.375936 |
merkle_hellman_knapsack.py
|
pypi
|
from samson.utilities.bytes import Bytes
from samson.public_key.dsa import DSA
from samson.math.algebra.curves.twisted_edwards_curve import TwistedEdwardsPoint, TwistedEdwardsCurve, bit
from samson.math.algebra.curves.named import EdwardsCurve25519
from samson.hashes.sha2 import SHA512
from samson.encoding.openssh.openssh_eddsa_key import OpenSSHEdDSAPrivateKey, OpenSSHEdDSAPublicKey, SSH2EdDSAPublicKey
from samson.encoding.pkcs8.pkcs8_eddsa_private_key import PKCS8EdDSAPrivateKey
from samson.encoding.x509.x509_eddsa_public_key import X509EdDSAPublicKey
from samson.encoding.jwk.jwk_eddsa_private_key import JWKEdDSAPrivateKey
from samson.encoding.jwk.jwk_eddsa_public_key import JWKEdDSAPublicKey
from samson.encoding.dns_key.dns_key_eddsa_key import DNSKeyEdDSAPublicKey, DNSKeyEdDSAPrivateKey
from samson.encoding.general import PKIEncoding
from samson.core.primitives import Primitive
from samson.core.metadata import SizeType, SizeSpec, FrequencyType
from samson.ace.decorators import register_primitive
# Originally (reverse?)-engineered from: https://ed25519.cr.yp.to/python/ed25519.py
# Fit to RFC8032 (https://tools.ietf.org/html/rfc8032#appendix-A)
# and against OpenSSH_7.8p1
@register_primitive()
class EdDSA(DSA):
"""
Edwards Curve Digitial Signature Algorithm
"""
PRIV_ENCODINGS = {
PKIEncoding.OpenSSH: OpenSSHEdDSAPrivateKey,
PKIEncoding.PKCS8: PKCS8EdDSAPrivateKey,
PKIEncoding.JWK: JWKEdDSAPrivateKey,
PKIEncoding.DNS_KEY: DNSKeyEdDSAPrivateKey
}
PUB_ENCODINGS = {
PKIEncoding.OpenSSH: OpenSSHEdDSAPublicKey,
PKIEncoding.SSH2: SSH2EdDSAPublicKey,
PKIEncoding.X509: X509EdDSAPublicKey,
PKIEncoding.JWK: JWKEdDSAPublicKey,
PKIEncoding.DNS_KEY: DNSKeyEdDSAPublicKey
}
KEY_SIZE = SizeSpec(size_type=SizeType.RANGE, sizes=[255, 448])
OUTPUT_SIZE = SizeSpec(size_type=SizeType.RANGE, sizes=[510, 896])
USAGE_FREQUENCY = FrequencyType.OFTEN
def __init__(self, curve: TwistedEdwardsCurve=EdwardsCurve25519, hash_obj: object=SHA512(), d: int=None, A: TwistedEdwardsPoint=None, a: int=None, h: bytes=None, clamp: bool=True):
"""
Parameters:
curve (TwistedEdwardsCurve): Curve used for calculations.
hash_obj (object): Instantiated object with compatible hash interface.
d (int): Private key.
A (TwistedEdwardsPoint): (Optional) Public point.
a (int): (Optional) Public scalar.
h (bytes): (Optional) Hashed private key.
clamp (bool): Whether or not to clamp the public scalar.
"""
Primitive.__init__(self)
self.B = curve.B
self.curve = curve
self.d = Bytes.wrap(d or max(1, Bytes.random(hash_obj.digest_size).int()))
self.H = hash_obj
self.h = h or hash_obj.hash(self.d)
a = a or self.h[:self.curve.b // 8].int()
self.a = curve.clamp_to_curve(a, True) if clamp else a
self.A = A or self.B * self.a
def __reprdir__(self):
return ['d', 'a', 'A', 'curve', 'H']
def encode_point(self, P: TwistedEdwardsPoint) -> Bytes:
"""
Encodes a `TwistedEdwardsPoint` as `Bytes`.
Parameters:
P (TwistedEdwardsPoint): Point to encode.
Returns:
Bytes: `Bytes` encoding.
"""
x, y = int(P.x), int(P.y)
return Bytes(((x & 1) << self.curve.b-1) + ((y << 1) >> 1), 'little').zfill(self.curve.b // 8)
def decode_point(self, in_bytes: Bytes) -> TwistedEdwardsPoint:
"""
Decodes `Bytes` to a `TwistedEdwardsPoint`.
Parameters:
in_bytes (Bytes): `TwistedEdwardsPoint` encoded as `Bytes`.
Returns:
TwistedEdwardsPoint: Decoded point.
"""
y_bytes = Bytes([_ for _ in in_bytes], 'little')
y_bytes[-1] &= 0x7F
y = y_bytes.int()
x = int(self.curve.recover_point_from_y(y).x)
if (x & 1) != bit(in_bytes, self.curve.b-1):
x = self.curve.order() - x
return TwistedEdwardsPoint(x, y, self.curve)
def get_pub_bytes(self) -> Bytes:
return self.encode_point(self.A)
def sign(self, message: bytes) -> Bytes:
"""
Signs a `message`.
Parameters:
message (bytes): Message to sign.
k (int): (Optional) Ephemeral key.
Returns:
Bytes: Signature formatted as r + s.
"""
r = self.H.hash(self.curve.magic + self.h[self.curve.b//8:] + message)[::-1].int()
R = self.B * (r % self.curve.l)
eR = self.encode_point(R)
k = self.H.hash(self.curve.magic + eR + self.encode_point(self.A) + message)[::-1].int()
S = (r + (k % self.curve.l) * self.a) % self.curve.l
return eR + Bytes(S, 'little').zfill(self.curve.b//8)
def verify(self, message: bytes, sig: bytes) -> bool:
"""
Verifies a `message` against a `sig`.
Parameters:
message (bytes): Message.
sig (bytes): Signature of `message`.
Returns:
bool: Whether the signature is valid or not.
"""
sig = Bytes.wrap(sig, 'little')
if len(sig) != self.curve.b // 4:
raise ValueError("`sig` length is wrong.")
R = self.decode_point(sig[:self.curve.b//8])
S = sig[self.curve.b//8:].int()
h = self.H.hash(self.curve.magic + self.encode_point(R) + self.encode_point(self.A) + message)[::-1].int()
return self.B * S == R + (self.A * h)
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/public_key/eddsa.py
| 0.875721 | 0.214671 |
eddsa.py
|
pypi
|
from samson.oracles.padding_oracle import PaddingOracle
from samson.utilities.bytes import Bytes
from samson.utilities.exceptions import NoSolutionException
from samson.utilities.runtime import RUNTIME
from random import randint
import math
import logging
log = logging.getLogger(__name__)
def _ceil(a, b):
return (a + b - 1) // b
def _append_and_merge(new_a, new_b, intervals):
for i, (a, b) in enumerate(intervals):
if not (b < new_a or a > new_b):
new_a = min(a, new_a)
new_b = max(b, new_b)
intervals[i] = new_a, new_b
return
intervals.append((new_a, new_b))
class PKCS1v15PaddingOracleAttack(object):
"""
Performs a plaintext recovery attack.
The PKCS#1 v1.5 padding oracle attack found by Daniel Bleichenbacher is an adaptive chosen-plaintext attack that
takes advantage of an information leak through the validation of the plaintext's padding. Using RSA's homomorphic
properties, the algorithm can iteratively converge on the correct plaintext.
Conditions:
* RSA is being used
* PKCS#1 v1.5 padding is being used
* The user has access to an oracle that allows abitrary plaintext input and leaks whether the padding is correct.
"""
def __init__(self, oracle: PaddingOracle):
"""
Parameters:
oracle (PaddingOracle): An oracle that takes in an integer and returns whether the padding is correct.
"""
self.oracle = oracle
@RUNTIME.report
def execute(self, ciphertext: int, n: int, e: int, key_length: int) -> Bytes:
"""
Executes the attack.
Parameters:
ciphertext (int): The ciphertext represented as an integer.
n (int): The RSA instance's modulus.
e (int): The RSA instance's public exponent.
key_length (int): The the bit length of the RSA instance (2048, 4096, etc).
Returns:
Bytes: The ciphertext's corresponding plaintext.
"""
key_byte_len = key_length // 8
# Convenience variables
B = 2 ** (8 * (key_byte_len - 2))
# Initial values
c = ciphertext
c_0 = ciphertext
M = [(2*B, 3*B - 1)]
i = 1
if not self.oracle.check_padding(c):
log.debug("Initial padding not correct; attempting blinding")
# Step 1: Blinding
while True:
s = randint(0, n - 1)
c_0 = (c * pow(s, e, n)) % n
if self.oracle.check_padding(c_0):
log.debug("Padding is now correct; blinding complete")
break
# Setup reporting
last_log_diff = math.log(M[0][1] - M[0][0], 2)
progress = RUNTIME.report_progress(None, total=last_log_diff)
# Step 2
while True:
log.debug(f"Starting iteration {i}")
log.debug(f"Current intervals: {M}")
diff = math.log(sum([interval[1] - interval[0] for interval in M]) + 1, 2)
progress.update(last_log_diff - diff)
last_log_diff = diff
# Step 2.a
if i == 1:
s = _ceil(n, 3*B)
log.debug(f"Starting search at {s}")
while True:
c = c_0 * pow(s, e, n) % n
if self.oracle.check_padding(c):
break
s += 1
# Step 2.b
elif len(M) >= 2:
log.debug(f"Intervals left: {M}")
while True:
s += 1
c = c_0 * pow(s, e, n) % n
if self.oracle.check_padding(c):
break
# Step 2.c
elif len(M) == 1:
log.debug("Only one interval")
a, b = M[0]
if a == b:
return Bytes(b'\x00' + Bytes(a))
r = _ceil(2 * (b*s - 2*B), n)
s = _ceil(2*B + r*n, b)
while True:
c = c_0 * pow(s, e, n) % n
if self.oracle.check_padding(c):
break
s += 1
if s > (3*B + r*n) // a:
r += 1
s = _ceil(2*B + r*n, b)
M_new = []
for a, b in M:
min_r = _ceil(a*s - 3*B + 1, n)
max_r = (b*s - 2*B) // n
for r in range(min_r, max_r + 1):
new_a = max(a, _ceil(2*B + r*n, s))
new_b = min(b, (3*B - 1 + r*n) // s)
if new_a > new_b:
raise Exception("Step 3: new_a > new_b? new_a: {} new_b: {}".format(new_a, new_b))
# Now we need to check for overlap between ranges and merge them
_append_and_merge(new_a, new_b, M_new)
if len(M_new) == 0:
raise NoSolutionException("There are zero intervals in 'M_new'")
M = M_new
i += 1
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/attacks/pkcs1v15_padding_oracle_attack.py
| 0.648132 | 0.307592 |
pkcs1v15_padding_oracle_attack.py
|
pypi
|
from samson.analysis.general import generate_rc4_bias_map, RC4_BIAS_MAP
from samson.oracles.chosen_plaintext_oracle import ChosenPlaintextOracle
from samson.utilities.runtime import RUNTIME
from samson.utilities.bytes import Bytes
from samson.ace.decorators import define_exploit
from samson.ace.consequence import Consequence, Requirement, Manipulation
import multiprocessing
import itertools
import struct
import math
import gc
import logging
log = logging.getLogger(__name__)
@define_exploit(consequence=Consequence.PLAINTEXT_RECOVERY, requirements=[Requirement.EVENTUALLY_DECRYPTS, Manipulation.PT_BIT_LEVEL.PT_BIT_LEVEL])
class RC4PrependAttack(object):
"""
Performs a plaintext recovery attack.
The RC4PrependAttack uses an ChosenPlaintextOracle that prepends the payload and then encrypts the whole message with a randomly generated key.
The attack uses specific byte biases found in the RC4 keystream and feeds the plaintext into these locations. Using the law of large numbers,
the keystream bias will surface, and we can XOR it with the ciphertext to return the plaintext. This specific implementation uses several optmizations.
The first is concurrency/parallelism and is self-explanatory. The second is the use of concurrent biases. We first determine which biases we can still use
in the attack. This is necessary since we can only feed the plaintext forward, so plaintext index five is not eligible to use RC4 bias index two. Next, we determine
which biases are "active". If the plaintext is 20 characters long, and the current padding position is 0, then we can utilize both RC4 bias indices 2 and 16 (i.e. 1 and 15 using a zero-based-index).
Lastly, we introduce "branches". If a byte happens to decrypted more than one and has different outcomes, we keep both. At the end, we return the Cartesian product of all
byte decryptions. This will normally just be one.
Conditions:
* RC4 is being used
* The user has access to an oracle that encrypts user-controlled plaintext and a secret under a random key
* The user-controlled plaintext is prepended to the secret
"""
def __init__(self, oracle: ChosenPlaintextOracle):
"""
Parameters:
oracle (ChosenPlaintextOracle): An oracle that takes in arbitrary plaintext bytes and returns its encryption under a random key.
"""
self.oracle = oracle
self.strongest_biases = [1, 15, 31]
def _encrypt_chunk(self, payload: bytes, chunk_size: int):
return [bytearray(self.oracle.request(payload)) for _ in range(chunk_size)]
@RUNTIME.report
def execute(self, secret_length: int, sample_size: int=2**23, chunk_size: int=2**19) -> Bytes:
"""
Executes the attack.
Parameters:
secret_length (int): The length of the secret you're trying to recover.
sample_size (int): The amount of samples to collect per byte of the secret. Higher numbers are slower but more accurate.
chunk_size (int): The size of sample chunks per CPU before a forceful garbage collection saves the day.
Returns:
Bytes: The recovered plaintext.
"""
cracked_indices = [set() for i in range(secret_length)]
cpu_count = multiprocessing.cpu_count()
pool = multiprocessing.Pool(processes=cpu_count)
log.info(f"Running with {cpu_count} cores")
for i in RUNTIME.report_progress(range(secret_length), unit='bytes'):
log.debug(f"Starting iteration {i + 1}/{secret_length}")
if len(cracked_indices[i]) > 0:
continue
applicable_biases = [bias for bias in self.strongest_biases if i <= bias or (secret_length + i >= bias and i < bias)]
padding_len = max(applicable_biases[0] - i, 0)
active_biases = [bias for bias in applicable_biases if padding_len + secret_length > bias]
payload = b'\x00' * padding_len
num_chunks = math.ceil(sample_size / chunk_size)
log.debug(f"Sampling {sample_size} ciphertexts")
flattened_list = []
for i in range(math.ceil(num_chunks / cpu_count)):
random_ciphertexts = [pool.apply_async(self._encrypt_chunk, (payload, chunk_size)) for i in range(min(num_chunks - (i*cpu_count), cpu_count))]
flattened_list.extend([result for result_list in random_ciphertexts for result in result_list.get()])
gc.collect()
log.debug("Generating bias map")
bias_map = generate_rc4_bias_map(flattened_list)
for bias_idx in active_biases:
cracked_indices[bias_idx - padding_len].add(RC4_BIAS_MAP[bias_idx] ^ bias_map[bias_idx][0][0])
all_branches = itertools.product(*[list(results) for results in cracked_indices])
return [Bytes(struct.pack('B' * len(branch), *branch)) for branch in all_branches]
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/attacks/rc4_prepend_attack.py
| 0.726329 | 0.38194 |
rc4_prepend_attack.py
|
pypi
|
from samson.utilities.manipulation import get_blocks
from samson.utilities.bytes import Bytes
from samson.oracles.chosen_plaintext_oracle import ChosenPlaintextOracle
from samson.utilities.runtime import RUNTIME
import struct
import logging
log = logging.getLogger(__name__)
class ECBPrependAttack(object):
"""
Performs a plaintext recovery attack.
By prepending data to the secret, we can take advantage of ECB's statelessness and iteratively build
ciphertext blocks that match the secret's ciphertext blocks.
Conditions:
* ECB is being used
* The user has access to an oracle that accepts arbitrary plaintext and returns the ciphertext
* The user's input is prepended to the secret plaintext
"""
def __init__(self, oracle: ChosenPlaintextOracle):
"""
Parameters:
oracle (ChosenPlaintextOracle): An oracle that takes in plaintext and returns the ciphertext.
"""
self.oracle = oracle
@RUNTIME.report
def execute(self) -> Bytes:
"""
Executes the attack.
Parameters:
unpad (bool): Whether or not to PKCS7 unpad the result.
Returns:
Bytes: The recovered plaintext.
"""
baseline = len(self.oracle.request(b''))
block_size = self.oracle.test_io_relation()['block_size']
plaintexts = []
for curr_block in RUNTIME.report_progress(range(baseline // block_size), unit='blocks'):
log.debug(f"Starting iteration {curr_block}")
plaintext = b''
for curr_byte in RUNTIME.report_progress(range(block_size), unit='bytes'):
if curr_block == 0:
payload = ('A' * (block_size - (curr_byte + 1))).encode()
else:
payload = plaintexts[-1][curr_byte + 1:]
one_byte_short = get_blocks(self.oracle.request(payload), block_size=block_size)[curr_block]
for i in range(256):
curr_byte = struct.pack('B', i)
ciphertext = self.oracle.request(payload + plaintext + curr_byte)
# We're always editing the first block to look like block 'curr_block'
if get_blocks(ciphertext, block_size=block_size)[0] == one_byte_short:
plaintext += curr_byte
break
plaintexts.append(plaintext)
return Bytes(b''.join(plaintexts))
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/attacks/ecb_prepend_attack.py
| 0.727007 | 0.269662 |
ecb_prepend_attack.py
|
pypi
|
from samson.math.algebra.curves.weierstrass_curve import WeierstrassCurve, WeierstrassPoint
from samson.math.algebra.curves.named import _PRECOMPUTED_ICA_PLANS, _PRECOMPUTED_ICA_ORDERS
from samson.math.general import crt, product, lcm, bsgs, kth_root
from samson.math.factorization.general import factor
from samson.protocols.ecdhe import ECDHE
from samson.utilities.runtime import RUNTIME
from samson.utilities.exceptions import SearchspaceExhaustedException
from typing import List
import logging
log = logging.getLogger(__name__)
class InvalidCurveAttack(object):
"""
The Invalid Curve attack takes advantage of systems that don't validate whether the other party's public key is on the curve.
The attacker can generate curves of smoother order with a different `b` constant, and then generate a public key
that lies inside of a subgroup.
There are two phases to this attack:
1) Finding residues modulo the small factors of the group order
2) Bruteforcing the residue configuration. (ZZ/ZZ(67))(15) may actually be (ZZ/ZZ(67))(52).
Conditions:
* Elliptic Curve Diffie-Hellman is being used
* The user has access to an oracle that accepts arbitrary public keys and returns the residue
"""
def __init__(self, oracle: 'Oracle', curve: WeierstrassCurve, threads: int=1):
"""
Parameters:
oracle (Oracle): Oracle that accepts (public_key: WeierstrassPoint, factor: int) and returns (residue: int).
curve (WeierstrassCurve): Curve that the victim is using.
"""
self.oracle = oracle
self.curve = curve
self.threads = threads
@RUNTIME.report
def execute(self, public_key: WeierstrassPoint, invalid_curves: List[WeierstrassCurve]=None, max_factor_size: int=2**16) -> int:
"""
Executes the attack.
Parameters:
public_key (int): ECDH public key to crack.
invalid_curves (list): List of invalid curves to use in the attack.
max_factor_size (int): Max factor size to prevent attempting to factor forever.
Returns:
int: Private key.
References:
"Validation of Elliptic Curve Public Keys" (https://iacr.org/archive/pkc2003/25670211/25670211.pdf)
"""
residues = []
# Reaching cardinality only determines the key up to sign.
# By getting to cardinality squared, we can get the exact key
# without having to do a lengthy bruteforce
cardinality = self.curve.cardinality()**2
if invalid_curves:
curve_facs = [(inv_curve, [(r, e) for r, e in factor(inv_curve.cardinality(), use_rho=False, limit=max_factor_size).items() if r < max_factor_size]) for inv_curve in invalid_curves]
# Check if we can meet the required cardinality
max_card_achieved = 1
for prod in [product([r**e for r,e in facs]) for _, facs in curve_facs]:
max_card_achieved = lcm(max_card_achieved, prod)
if max_card_achieved < cardinality:
raise RuntimeError(f'Maximum achievable modulus is only {"%.2f"%(max_card_achieved / cardinality)}% of curve cardinality squared. Supply more invalid curves.')
# Plan which factors to use
flattened = [[(inv_curve, (r,e)) for r,e in facs] for inv_curve, facs in curve_facs]
flattened = [item for sublist in flattened for item in sublist]
fac_dict = {}
for inv_curve, (r,e) in flattened:
if r not in fac_dict:
fac_dict[r] = []
fac_dict[r].append((inv_curve, e))
planned_card = 1
initial_plan = []
# Add greedily
for fac, curve_exponents in sorted(fac_dict.items(), key=lambda item: item[0]):
selected_curve, exponent = max(curve_exponents, key=lambda item: item[1])
# Two is a special case, and we require an exponent of at least 3.
if fac == 2 and exponent < 3:
continue
initial_plan.append((selected_curve, fac, exponent))
planned_card *= fac**exponent
final_plan = []
# Remove greedily
for curve, fac, exponent in sorted(initial_plan, key=lambda item: item[1], reverse=True):
final_exp = exponent
for _ in range(exponent):
if planned_card // fac > cardinality:
planned_card //= fac
final_exp -= 1
else:
break
final_plan.append((curve, fac, exponent))
else:
try:
final_plan = _PRECOMPUTED_ICA_PLANS[self.curve]
orders = _PRECOMPUTED_ICA_ORDERS[self.curve]
inv_curves = {b: WeierstrassCurve(a=self.curve.a, b=self.curve.ring(b), cardinality=orders[b], base_tuple=(self.curve.G.x, self.curve.G.y), ring=self.curve.ring) for b in set([b for b,f,e in final_plan])}
final_plan = [(inv_curves[b], f, e) for b,f,e in final_plan]
except KeyError:
raise RuntimeError('No invalid curves provided and no precomputed plan found')
# Display plan stats
avg_requests = 0
needed_res = 0
for curve, fac, exponent in final_plan:
avg_requests += ((fac+1) // 2)*exponent
needed_res += exponent
log.debug(f'Attack plan consists of {needed_res} residues and an average of {avg_requests} oracle requests')
# Execute the attack
@RUNTIME.threaded(threads=self.threads, starmap=True)
def find_residues(inv_curve, fac, exponent):
res = 0
mal_ecdhe = ECDHE(G=self.curve.G, d=1)
exp_mod = int(fac == 2)
full_pp_group = fac**exponent
first_subgroup = fac**(exponent-1)
already_seen = set()
# Find a prime power generator on the invalid curve
first_order = full_pp_group // first_subgroup
attempts = 0
while True:
point = inv_curve.random()
bad_pub = point * (inv_curve.cardinality() // full_pp_group)
if bad_pub * first_subgroup:
break
# Heuristics to determine if we can't generate that subgroup
already_seen.add(bad_pub * first_subgroup)
attempts += 1
if len(already_seen) == first_order or attempts == first_order**3:
log.warning(f'No generator of subgroup size {first_order} for curve {inv_curve}. Decrementing exponent')
first_order *= fac
first_subgroup //= fac
exponent -= 1
attempts = 0
already_seen = set()
bad_pub = bad_pub.cache_mul(bad_pub.curve.cardinality().bit_length())
# Query the oracle
for curr_e in range(exponent-exp_mod*2):
subgroup = first_subgroup // fac**curr_e
curr_r = 0
for i in range(1, fac):
pub_mod = subgroup*(res + i*fac**curr_e)
if self.oracle.request(bad_pub*subgroup, mal_ecdhe.derive_key(bad_pub*pub_mod)):
curr_r = i
break
res += curr_r * fac**curr_e
return res, fac**(curr_e+1)
residues = find_residues(final_plan)
res, mod = crt([(r**2 % p, p) for r,p in residues])
p = int(self.curve.ring.quotient)
if mod > p**2:
return kth_root(res, 2)
else:
# We should only be here for P521.
# P521's prime `p` is M521 (2^521 - 1). Since P521's `a` parameter (-3) is a
# quadratic residue of the field, and `p` is 3 mod 4, there exists a supersingular
# curve `E: y^2 = x^3 + ax` (note that `b` is 0) with order `p+1`. Now `p+1` is a
# power of 2, meaning it's literally the smoothest possible invalid curve we can use.
# Even more fortunate, negation is idempotent in Z2, so we don't have to care about
# negative points. The biggest stipulation is that the public key for the
# first subgroup confinement will always result in 0 or G, and, therefore, give us
# no information. We simply skip it, and then solve the missing relation.
# We have a relation d % mod == res
# Therefore:
# d - m*mod == res
# d = res + m*mod
# y = d * G
# y = G * (res + m*mod)
# y = G*res + G*m*mod
# So by starting BSGS's accumulator at `G*res` and setting the generator to `G*mod`,
# we'll solve for `m` given `y`.
res, mod = crt(residues)
g_prime = self.curve.G*mod
y_prime = res * self.curve.G
order = self.curve.order() // mod + 1
try:
m = bsgs(g_prime, public_key, e=y_prime, end=order)
except SearchspaceExhaustedException:
res = -res % mod
y_prime = res * self.curve.G
m = bsgs(g_prime, public_key, e=y_prime, end=order)
return res + mod*m
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/attacks/invalid_curve_attack.py
| 0.859958 | 0.31736 |
invalid_curve_attack.py
|
pypi
|
from math import exp
from samson.utilities.runtime import RUNTIME
from samson.oracles.oracle import Oracle
from samson.math.factorization.general import factor
from samson.math.general import crt, bsgs
from samson.utilities.exceptions import SearchspaceExhaustedException
import logging
log = logging.getLogger(__name__)
class InsecureTwistAttack(object):
def __init__(self, oracle: Oracle, g: 'WeierstrassPoint', processes: int=1):
self.oracle = oracle
self.g = g
self.processes = processes
@RUNTIME.report
def execute(self, public_key: int, max_factor_size: int=2**24) -> int:
E = self.g.curve
E2 = E.quadratic_twist()
M, _ = E2.to_montgomery_form()
u = M.find_gen()
order = u.order()
residues = []
idempotents = []
facs = [(p, e) for p,e in factor(order).items() if p < max_factor_size]
log.info(f'Found factors: {facs}')
def find_residues(p, exponent):
res = 0
for e in range(1, exponent+1):
subgroup = p**e
v = u*(u.order() // subgroup)
def find_sub_res(res):
for i in range(res, subgroup, subgroup // p):
if self.oracle.request(v, v*i):
return i
# Try on both sides of the field
found = find_sub_res(res)
if found is None:
found = find_sub_res(-res % (subgroup // p))
res = found
res %= subgroup
return res, subgroup
residues = [find_residues(p, e) for p,e in facs]
idempotents = []
nonidems = []
# Just so we call the oracle less later
for r, n in residues:
if not r or n == 2:
idempotents.append((r, n))
else:
nonidems.append((r, n))
ra, na = nonidems[0]
rb, nb = nonidems[1]
v = u*(u.order() // (na*nb))
# Synchronize the sign of the first two residues
for sign_a, sign_b in [(1, 1), (1, -1), (-1, 1), (-1, -1)]:
r, _ = crt([(sign_a*ra, na), (sign_b*rb, nb)])
if self.oracle.request(v, v*r):
ra, na = sign_a*ra % na, na
# Sync the signs of the rest
for res_r, res_n in nonidems[1:]:
r, n = crt([(ra, na), (res_r, res_n)])
v = u*(u.order() // n)
a = self.oracle.request(v, v*r)
b = self.oracle.request(v, v*(-r % n))
# As long as the signs sync, we're good
sign = (a or b)*2-1
ra, na = crt([(ra, na), (sign*res_r, res_n)])
for sign in [1, -1]:
n_residues = [(sign*ra, na)] + idempotents
r, n = crt(n_residues)
gr = self.g*r
gn = self.g*n
try:
k = bsgs(gn, public_key, E.G.order() // n, e=gr)
return r + k*n
except SearchspaceExhaustedException:
pass
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/attacks/insecure_twist_attack.py
| 0.476092 | 0.205296 |
insecure_twist_attack.py
|
pypi
|
from samson.utilities.bytes import Bytes
from samson.oracles.padding_oracle import PaddingOracle
from samson.public_key.rsa import RSA
from samson.utilities.runtime import RUNTIME
from samson.ace.decorators import define_exploit
from samson.ace.consequence import Consequence, Requirement, Manipulation
import math
import logging
log = logging.getLogger(__name__)
# AKA OAEP padding oracle
# http://archiv.infsec.ethz.ch/education/fs08/secsem/Manger01.pdf
# @define_exploit(consequence=Consequence.PLAINTEXT_RECOVERY, requirements=[Requirement.EVENTUALLY_DECRYPTS, Consequence.PLAINTEXT_MANIPULATION])
@define_exploit(consequence=Consequence.ENCRYPTION_BYPASS, requirements=[Requirement.EVENTUALLY_DECRYPTS, Manipulation.PT_MULTIPLICATIVE])
class MangersAttack(object):
"""
Performs a plaintext recovery attack.
Manger's attack stems from a padding oracle on RSA-OAEP. According to OAEP's specification, the first byte
*has* to be zero. If the code checks this and leaks whether it's zero or not, we can efficiently retrieve
the plaintext through an adaptive chosen-plaintext attack.
"""
def __init__(self, padding_oracle: PaddingOracle, rsa: RSA):
"""
Parameters:
padding_oracle (PaddingOracle): An oracle that takes in bytes and returns whether the first byte of the decrypted plaintext is zero.
rsa (RSA): An RSA instance containing the public key parameters.
"""
self.oracle = padding_oracle
self.rsa = rsa
def _greater_equal_B(self, f, c, e, N):
f_e = pow(f, e, N)
return self.oracle.check_padding(Bytes((c * f_e) % N))
@RUNTIME.report
def execute(self, ciphertext: bytes) -> Bytes:
"""
Executes Manger's attack.
Parameters:
ciphertext (bytes): The ciphertext to decrypt.
Returns:
Bytes: The ciphertext's corresponding plaintext.
"""
ciphertext = Bytes.wrap(ciphertext)
ct_int = ciphertext.int()
k = math.ceil(math.log(self.rsa.n, 256))
B = 2 ** (8 * (k - 1))
n = self.rsa.n
e = self.rsa.e
log.debug(f"k: {k}, B: {B}, n: {n}, e: {e}")
# Step 1
f1 = 2
log.info("Starting step 1")
while not self._greater_equal_B(f1, ct_int, e, n):
f1 *= 2
f1 //= 2
log.debug(f"Found f1: {f1}")
# Step 2
nB = n + B
nB_B = nB // B
f2 = nB_B * f1
log.info("Starting step 2")
while self._greater_equal_B(f2, ct_int, e, n):
f2 += f1
log.debug(f"Found f2: {f2}")
# Step 3
div_mod = 1 if n % f2 else 0
m_min = n // f2 + div_mod
m_max = nB // f2
BB = 2*B
diff = m_max - m_min
ctr = 0
log.info("Starting step 3")
log.debug(f"B-(diff * f2) = {B - (diff * f2)}")
# Reporting
last_log_diff = math.log(diff, 2)
progress = RUNTIME.report_progress(None, total=last_log_diff)
while diff > 0:
if ctr % 100 == 0:
log.debug(f"Iteration {ctr} difference: {diff}")
f = BB // diff
f_min = f * m_min
i = f_min // n
iN = i*n
div_mod = 1 if iN % m_min else 0
f3 = iN // m_min + div_mod
iNB = iN + B
if self._greater_equal_B(f3, ct_int, e, n):
div_mod = 1 if iNB % f3 else 0
m_min = iNB // f3 + div_mod
else:
m_max = iNB // f3
diff = m_max - m_min
# Update progress
log_diff = math.log(diff + 1, 2)
progress.update(last_log_diff - log_diff)
last_log_diff = log_diff
ctr += 1
return Bytes(m_min)
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/attacks/mangers_attack.py
| 0.621541 | 0.322859 |
mangers_attack.py
|
pypi
|
from samson.oracles.chosen_plaintext_oracle import ChosenPlaintextOracle
from samson.utilities.bytes import Bytes
class XORBitflippingAttack(object):
"""
Performs a plaintext manipulation attack.
CTR/stream ciphers will XOR the keystream with the ciphertext to decrypt the data. By injecting known plaintext,
we can recover that block's keystream and XOR in our own plaintext. While this may seem extraneous given
we can already inject a payload, this particular attack lends itself to bypassing validation functions.
Imagine if an application encrypts a URL-encoded payload with its application key and gives it to us as way of keeping state.
The developer assumes we can't modify the ciphertext without corrupting the string, so they trust the ciphertext
when it's received.
CBC will XOR the bitshift of the edited cipher block
with the next blocks. To exploit this structure, we must
craft a payload in reverse such that it creates our desired string.
To do this, we need a known plaintext and a desired plaintext.
We fill the targeted block with the known plaintext.
We XOR our desired text, 'hiya;admin=true;', with the plaintext to find the "difference".
Finally, we XOR the difference with the original cipher block.
comment1=cooking
%20MCs;userdata=
aaaaaaaaaaaaaaaa
;comment2=%20lik
e%20a%20pound%20
of%20baconPPPPPP
Conditions:
* CBC, CTR, or a stream cipher is being used
* The user has access to an oracle that allows encryption of arbitrary plaintext and returns the ciphertext.
"""
def __init__(self, oracle: ChosenPlaintextOracle, block_size: int=16):
"""
Parameters:
oracle (ChosenPlaintextOracle): An oracle that takes in arbitrary plaintext and returns the ciphertext.
block_size (int): Block size of the underlying block cipher.
"""
self.oracle = oracle
self.block_size = block_size
def execute(self, desired_injection: bytes, index: int=16) -> Bytes:
"""
Executes the attack.
Parameters:
desired_injection (bytes): Bytes to inject at `index`.
index (int): Index to inject the bytes.
Returns:
Bytes: The manipulated ciphertext.
"""
payload = b'a' * self.block_size
ciphertext = self.oracle.request(payload)
end_of_block = index + self.block_size
edited_cipher = Bytes(ciphertext)
edited_cipher[index:end_of_block] = edited_cipher[index:end_of_block] ^ desired_injection ^ payload
return edited_cipher
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/attacks/xor_bitflipping_attack.py
| 0.860222 | 0.552178 |
xor_bitflipping_attack.py
|
pypi
|
from samson.utilities.bytes import Bytes
from samson.oracles.padding_oracle import PaddingOracle
from samson.utilities.runtime import RUNTIME
from samson.ace.decorators import define_exploit
from samson.ace.consequence import Consequence, Requirement, Manipulation
import struct
import logging
log = logging.getLogger(__name__)
# https://grymoire.wordpress.com/2014/12/05/cbc-padding-oracle-attacks-simplified-key-concepts-and-pitfalls/
# @define_exploit(consequence=Consequence.PLAINTEXT_RECOVERY, requirements=[Requirement.EVENTUALLY_DECRYPTS, Consequence.PLAINTEXT_MANIPULATION])
@define_exploit(consequence=Consequence.ENCRYPTION_BYPASS, requirements=[Requirement.EVENTUALLY_DECRYPTS, Manipulation.PT_BIT_LEVEL])
class CBCPaddingOracleAttack(object):
"""
Performs a CBC padding oracle attack.
Currently only works with PKCS7.
Conditions:
* CBC is being used
* The system leaks whether the plaintext's padding was correct or not
* The user has access to an oracle that attempts to decrypt arbitrary ciphertext
"""
def __init__(self, oracle: PaddingOracle, block_size: int=16, alphabet: list=[byte for byte in range(256)], batch_requests: bool=False, threads: int=1):
"""
Parameters:
oracle (PaddingOracle): An oracle that takes in a bytes-like object and returns a boolean indicating whether the padding was correct.
block_size (int): Block size of the block cipher being used.
alphabet (list): Bytes range the plaintext is made out of.
batch_requests (bool): Whether or not the oracle can take batch requests.
threads (int): Number of threads to use.
"""
self.oracle = oracle
self.block_size = block_size
self.alphabet = alphabet
self.batch_requests = batch_requests
self.threads = threads
@RUNTIME.report
def decrypt(self, ciphertext: bytes, iv: bytes=None) -> Bytes:
"""
Decrypts the `ciphertext` using a CBC padding oracle.
Parameters:
ciphertext (bytes): Bytes-like ciphertext to be decrypted.
iv (bytes): Initialization vector (or previous ciphertext block) of the ciphertext to crack.
Returns:
Bytes: Plaintext corresponding to the inputted ciphertext.
"""
blocks = Bytes.wrap(ciphertext).chunk(self.block_size)
if not iv:
iv = blocks[0]
blocks = blocks[1:]
reversed_blocks = blocks[::-1]
iv = Bytes.wrap(iv)
plaintexts = []
for i, block in enumerate(RUNTIME.report_progress(reversed_blocks, desc='Blocks cracked', unit='blocks')):
log.debug(f"Starting iteration {i}")
plaintext = Bytes(b'')
if i == len(reversed_blocks) - 1:
preceding_block = iv
else:
preceding_block = reversed_blocks[i + 1]
for _ in RUNTIME.report_progress(range(len(block)), desc='Bytes cracked', unit='bytes'):
last_working_char = None
exploit_blocks = {}
# Generate candidate blocks
for possible_char in self.alphabet:
test_byte = struct.pack('B', possible_char)
payload = test_byte + plaintext
prefix = b'\x00' * (self.block_size - len(payload))
padding = (struct.pack('B', len(payload)) * (len(payload))) ^ payload
fake_block = prefix + padding
exploit_block = fake_block ^ preceding_block
new_cipher = bytes(exploit_block + block)
exploit_blocks[new_cipher] = test_byte
if self.batch_requests:
best_block = self.oracle.check_padding([k for k,v in exploit_blocks.items()])
last_working_char = exploit_blocks[best_block]
log.debug(f"Found working byte: {last_working_char}")
else:
@RUNTIME.threaded(threads=self.threads, starmap=True)
def attempt_exploit_block(exploit_block, byte):
if self.oracle.check_padding(exploit_block):
return byte
last_working_char = max([b for b in attempt_exploit_block(exploit_blocks.items()) if b is not None])
plaintext = last_working_char + plaintext
plaintexts.append(plaintext)
return Bytes(b''.join(plaintexts[::-1]))
execute = decrypt
def encrypt(self, ciphertext: bytes, new_plaintext: bytes, iv: bytes=None, pad: bool=True) -> Bytes:
"""
Encrypts the `new_plaintext` using a CBC padding oracle on `ciphertext`.
Parameters:
ciphertext (bytes): Bytes-like ciphertext to be decrypted.
new_plaintext (bytes): Desired plaintext.
iv (bytes): Initialization vector (or previous ciphertext block) of the ciphertext to crack.
pad (bool): Whether or not to pad the plaintext with PKCS7.
Returns:
Bytes: Ciphertext corresponding to the inputted plaintext.
"""
ct_blocks = Bytes.wrap(ciphertext).chunk(self.block_size)
if not iv:
iv = ct_blocks[0]
ct_blocks = ct_blocks[1:]
if pad:
from samson.padding.pkcs7 import PKCS7
new_plaintext = PKCS7(self.block_size).pad(new_plaintext)
new_pt_blocks = Bytes.wrap(new_plaintext).chunk(self.block_size)
ct_blocks = [iv] + ct_blocks[-len(new_pt_blocks):]
for i in reversed(range(1 ,len(ct_blocks))):
pt_blk_i = self.decrypt(iv=ct_blocks[i-1], ciphertext=ct_blocks[i])
ct_blocks[i-1] ^= pt_blk_i ^ new_pt_blocks[i-1]
return ct_blocks[0], b''.join(ct_blocks[1:])
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/attacks/cbc_padding_oracle_attack.py
| 0.80784 | 0.279414 |
cbc_padding_oracle_attack.py
|
pypi
|
from samson.utilities.bytes import Bytes
from samson.analyzers.analyzer import Analyzer
from samson.utilities.runtime import RUNTIME
import struct
import logging
log = logging.getLogger(__name__)
class XORTranspositionAttack(object):
"""
Performs a plaintext recovery attack.
Using only an Analyzer, attempts to break a many-time pad using structural properties.
This attack has two phases:
* Transposition analysis - creates a matrix out of the bytes and transposes it so the rows share a common keystream byte before analyzing it. WARNING: the ciphertexts are trimmed to the length of the smallest sample.
* Full-text analysis - reverts the transposed matrix and then copies the new, partial plaintexts over the original ciphertexts. Each ciphertext is analyzed in its entirety and the best character per position is chosen. This process can be repeated to incrementally recover more plaintext.
Conditions:
* A stream/OTP-like cipher is used. I.E. plaintext XOR keystream
* The user has collected more than one ciphertext using the same keystream.
"""
def __init__(self, analyzer: Analyzer):
"""
Parameters:
analyzer (Analyzer): Analyzer that correctly scores the underlying plaintext.
"""
self.analyzer = analyzer
@RUNTIME.report
def execute(self, ciphertexts: list, iterations: int=3) -> list:
"""
Executes the attack.
Parameters:
ciphertexts (list): List of bytes-like ciphertexts using the same keystream.
iterations (int): Number of iterations of the full-text analysis phase. Accuracy-time trade-off.
Returns:
list: List of recovered plaintexts.
"""
min_size = min([len(ciphertext) for ciphertext in ciphertexts])
same_size_ciphers = [ciphertext[:min_size] for ciphertext in ciphertexts]
transposed_ciphers = [bytearray(transposed) for transposed in zip(*same_size_ciphers)]
assert [bytearray(transposed) for transposed in zip(*transposed_ciphers)] == same_size_ciphers
log.debug("Starting initial transposition analysis")
# Transposition analysis first (transposition)
transposed_plaintexts = []
for cipher in RUNTIME.report_progress(transposed_ciphers, desc='Transposition analysis', unit='ciphers'):
all_chars = {}
for char in range(256):
plaintext = Bytes(struct.pack('B', char)).stretch(len(cipher)) ^ cipher
all_chars[char] = (self.analyzer.analyze(plaintext), plaintext)
transposed_plaintexts.append(sorted(all_chars.items(), key=lambda kv: kv[1][0], reverse=True)[0][1][1])
retransposed_plaintexts = [bytearray(transposed) for transposed in zip(*transposed_plaintexts)]
log.debug("Starting full-text analysis on retransposed text")
# Clean up with a character-by-character, higher-context analysis (retransposed)
for j in RUNTIME.report_progress(range(iterations), desc='Higher-context analysis'):
log.debug(f"Starting iteration {j + 1}/{iterations}")
differential_mask = bytearray()
for i in RUNTIME.report_progress(range(min_size), desc='Building differential mask', unit='bytes'):
all_chars = {}
for char in range(256):
full_text_analyses = []
for curr_cipher in retransposed_plaintexts:
cipher_copy = bytearray([_ for _ in curr_cipher])
cipher_copy[i] = ord(Bytes(struct.pack('B', char)) ^ struct.pack('B', curr_cipher[i]))
full_text_analyses.append(self.analyzer.analyze(cipher_copy))
all_chars[char] = (sum(full_text_analyses), char)
best_char = sorted(all_chars.items(), key=lambda kv: kv[1][0], reverse=True)[0][1][1]
differential_mask += struct.pack('B', best_char)
retransposed_plaintexts = [Bytes.wrap(cipher) ^ differential_mask for cipher in retransposed_plaintexts]
return retransposed_plaintexts
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/attacks/xor_transposition_attack.py
| 0.825203 | 0.437343 |
xor_transposition_attack.py
|
pypi
|
from samson.math.general import random_int_between, crt, mod_inv, bsgs
from samson.math.factorization.general import trial_division
from samson.math.algebra.rings.integer_ring import ZZ
from samson.utilities.runtime import RUNTIME
from samson.oracles.oracle import Oracle
from functools import reduce
import math
import logging
log = logging.getLogger(__name__)
class DiffieHellmanSubgroupConfinementAttack(object):
"""
The Diffie-Hellman Subgroup Confinement attack takes advantage of smooth multiplicative group orders of unsafe primes used in Diffie-Hellman.
There are two phases to this attack:
1) Finding residues modulo the small factors of the multiplicative group order
2) Solving the discrete logarithm of the remaining factors
Conditions:
* Diffie-Hellman is being used
* The user has access to an boolean oracle that accepts arbitrary public keys and returns whether the residue was correct
* The left over key space is small enough to solve DLP
"""
def __init__(self, oracle: Oracle, p: int, g: int=None, order: int=None, threads: int=1):
"""
Parameters:
oracle (Oracle): Oracle that accepts (public_key: int, residue: int) and returns (is_correct: bool).
p (int): Prime modulus.
g (int): Generator.
order (int): Order of multiplicative group.
"""
self.oracle = oracle
self.p = p
self.g = g
self._group = (ZZ/ZZ(p)).mul_group()
self.order = order or (self._group(g).order() if g else self._group.order())
self.threads = threads
if order:
self._group.order_cache = order
@RUNTIME.report
def execute(self, public_key: int, max_factor_size: int=2**16) -> int:
"""
Executes the attack.
Parameters:
public_key (int): Diffie-Hellman public key to crack.
max_factor_size (int): Max factor size to prevent attempting to factor forever.
Returns:
int: Private key.
"""
# Factor as much as we can
facs = trial_division(self.p-1, limit=max_factor_size)
log.debug(f'Found factors: {facs}')
# Request residues from crafted public keys
@RUNTIME.threaded(threads=self.threads, starmap=True)
def find_residues(fac, exponent):
res = 0
for curr_e in range(1, exponent+1):
subgroup = fac**curr_e
h = 1
while h == 1:
t = random_int_between(2, self.p)
h = pow(t, (self.p-1) // subgroup, self.p)
for i in range(res, subgroup+1, subgroup // fac):
if self.oracle.request(h, pow(h, i, self.p)):
res = i
break
res %= subgroup
return res, subgroup
residues = find_residues(facs.items())
# Build partials using CRT
n, r = crt(residues)
# Oh, I guess we already found it...
if r >= self.order:
return n % self.order
g_prime = pow(self.g, r, self.p)
y_prime = (public_key * mod_inv(pow(self.g, n, self.p), self.p)) % self.p
log.info(f'Recovered {"%.2f"%math.log(reduce(int.__mul__, facs, 1), 2)}/{"%.2f"%math.log(self.order, 2)} bits')
log.info(f'Found relation: x = {n} + m*{r}')
log.debug(f"g' = {g_prime}")
log.debug(f"y' = {y_prime}")
# Solve DLP
R = (ZZ/ZZ(self.p)).mul_group()
m = bsgs(R(g_prime), R(y_prime), end=(self.order - 1) // r)
return n + m*r
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/attacks/diffie_hellman_subgroup_confinement_attack.py
| 0.79162 | 0.264367 |
diffie_hellman_subgroup_confinement_attack.py
|
pypi
|
from samson.oracles.oracle import Oracle
from samson.utilities.bytes import Bytes
import struct
import string
import logging
log = logging.getLogger(__name__)
alphabet = (string.ascii_lowercase + string.ascii_uppercase + string.digits + '=/+' + ':;').encode()
padding_chars = ')(\{\}\\[]<%@#^`~$*!|`'[::-1].encode() + b'>.\'_,?;:+-='
class CRIMEAttack(object):
"""
Performs a compression ratio side channel attack.
Even if a message is encrypted, information about the contents of the message can still be leaked. CRIME/BREACH measures
is an adaptive chosen-plaintext attack that measures the size of a compressed-then-encrypted message. By crafting our insertions,
we can determine whether specific patterns exist in the message and eventually recover entire plaintexts.
Conditions:
* The user has access to a length oracle that takes in arbitrary bytes and outputs the compressed length.
"""
def __init__(self, oracle: Oracle, alphabet: bytes=alphabet, padding_chars: bytes=padding_chars):
"""
Parameters:
oracle (Oracle): A length oracle that takes in arbitrary bytes and outputs the compressed length.
alphabet (bytes): Allowed characters to try.
padding_chars (bytes): Characters not likely to show up and can be used as "padding."
"""
self.oracle = oracle
self.alphabet = alphabet
self.padding_chars = padding_chars
def execute(self, known_plaintext: bytes, secret_len: int, constant_padding: bytes=b'\t\t\t\t\t') -> Bytes:
"""
Executes the attack.
Parameters:
known_plaintext (bytes): Partial known plaintext to seed the attack.
secret_len (int): Length of the secret. Better to be higher than lower.
constant_padding (bytes): A padding that is always appended. This parameter can easily be the difference between a failure and success.
Returns:
Bytes: The recovered plaintext.
"""
plaintext = known_plaintext
padding = self.find_padding(plaintext, constant_padding)
if padding == None:
raise RuntimeError("No suitable padding found")
ctr = 0
while (len(plaintext) - len(known_plaintext)) < secret_len:
log.debug(f'Attempt format of "{(plaintext + b"{}" + padding).decode()}"')
padded_sizes = [(struct.pack('B', char), self.oracle.request(plaintext + struct.pack('B', char) + padding + constant_padding)) for char in self.alphabet]
sorted_sizes = sorted(padded_sizes, key=lambda req: req[1])
log.debug(f'Sizes for iteration {ctr}: {sorted_sizes}')
if sorted_sizes[0][1] == sorted_sizes[1][1]:
return Bytes(plaintext)
else:
plaintext += sorted_sizes[0][0]
ctr += 1
return Bytes(plaintext)
def find_padding(self, payload: bytes, constant_padding: bytes) -> bytes:
"""
Internal function. Used to find an appropriate padding for the oracle.
"""
reference_len = self.oracle.request(payload)
padding = b''
log.debug('Attempting to find padding')
for char in self.padding_chars:
padding += struct.pack('B', char)
new_len = self.oracle.request(payload + padding + constant_padding)
if new_len > reference_len:
padding = padding[:-1]
log.debug(f'Found suitable padding "{padding.decode()}"')
return padding
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/attacks/crime_attack.py
| 0.801548 | 0.313574 |
crime_attack.py
|
pypi
|
from samson.block_ciphers.rijndael import SBOX as RIJ_SBOX
from samson.utilities.bytes import Bytes
from samson.core.primitives import StreamCipher, Primitive
from samson.core.metadata import ConstructionType, UsageType, SizeType, SizeSpec, EphemeralType, EphemeralSpec, FrequencyType
from samson.ace.decorators import register_primitive
SQ = [
0x25,0x24,0x73,0x67,0xD7,0xAE,0x5C,0x30,0xA4,0xEE,0x6E,0xCB,0x7D,0xB5,0x82,0xDB,
0xE4,0x8E,0x48,0x49,0x4F,0x5D,0x6A,0x78,0x70,0x88,0xE8,0x5F,0x5E,0x84,0x65,0xE2,
0xD8,0xE9,0xCC,0xED,0x40,0x2F,0x11,0x28,0x57,0xD2,0xAC,0xE3,0x4A,0x15,0x1B,0xB9,
0xB2,0x80,0x85,0xA6,0x2E,0x02,0x47,0x29,0x07,0x4B,0x0E,0xC1,0x51,0xAA,0x89,0xD4,
0xCA,0x01,0x46,0xB3,0xEF,0xDD,0x44,0x7B,0xC2,0x7F,0xBE,0xC3,0x9F,0x20,0x4C,0x64,
0x83,0xA2,0x68,0x42,0x13,0xB4,0x41,0xCD,0xBA,0xC6,0xBB,0x6D,0x4D,0x71,0x21,0xF4,
0x8D,0xB0,0xE5,0x93,0xFE,0x8F,0xE6,0xCF,0x43,0x45,0x31,0x22,0x37,0x36,0x96,0xFA,
0xBC,0x0F,0x08,0x52,0x1D,0x55,0x1A,0xC5,0x4E,0x23,0x69,0x7A,0x92,0xFF,0x5B,0x5A,
0xEB,0x9A,0x1C,0xA9,0xD1,0x7E,0x0D,0xFC,0x50,0x8A,0xB6,0x62,0xF5,0x0A,0xF8,0xDC,
0x03,0x3C,0x0C,0x39,0xF1,0xB8,0xF3,0x3D,0xF2,0xD5,0x97,0x66,0x81,0x32,0xA0,0x00,
0x06,0xCE,0xF6,0xEA,0xB7,0x17,0xF7,0x8C,0x79,0xD6,0xA7,0xBF,0x8B,0x3F,0x1F,0x53,
0x63,0x75,0x35,0x2C,0x60,0xFD,0x27,0xD3,0x94,0xA5,0x7C,0xA1,0x05,0x58,0x2D,0xBD,
0xD9,0xC7,0xAF,0x6B,0x54,0x0B,0xE0,0x38,0x04,0xC8,0x9D,0xE7,0x14,0xB1,0x87,0x9C,
0xDF,0x6F,0xF9,0xDA,0x2A,0xC4,0x59,0x16,0x74,0x91,0xAB,0x26,0x61,0x76,0x34,0x2B,
0xAD,0x99,0xFB,0x72,0xEC,0x33,0x12,0xDE,0x98,0x3B,0xC0,0x9B,0x3E,0x18,0x10,0x3A,
0x56,0xE1,0x77,0xC9,0x1E,0x9E,0x95,0xA3,0x90,0x19,0xA8,0x6C,0x09,0xD0,0xF0,0x86
]
# https://www.gsma.com/aboutus/wp-content/uploads/2014/12/snow3gspec.pdf
# https://github.com/mitshell/CryptoMobile/blob/master/C_alg/SNOW_3G.c
@register_primitive()
class SNOW3G(StreamCipher):
"""
SNOW3G stream cipher
Used in 4G LTE encryption.
"""
CONSTRUCTION_TYPES = [ConstructionType.LFSR]
USAGE_TYPE = UsageType.CELLULAR
USAGE_FREQUENCY = FrequencyType.OFTEN
EPHEMERAL = EphemeralSpec(ephemeral_type=EphemeralType.NONCE, size=SizeSpec(size_type=SizeType.SINGLE, sizes=128))
def __init__(self, key: bytes, iv: bytes):
"""
Parameters:
key (bytes): Key (128 or 256 bits).
iv (bytes): Initialization vector (16 bytes).
"""
Primitive.__init__(self)
self.key = Bytes.wrap(key)
self.iv = Bytes.wrap(iv)
k0, k1, k2, k3 = [chunk.to_int() for chunk in self.key.chunk(4)]
iv0, iv1, iv2, iv3 = [chunk.to_int() for chunk in self.iv.chunk(4)]
s = [None] * 16
s[15] = k3 ^ iv0
s[14] = k2
s[13] = k1
s[12] = k0 ^ iv1
s[11] = k3 ^ 0xFFFFFFFF
s[10] = k2 ^ 0xFFFFFFFF ^ iv2
s[9] = k1 ^ 0xFFFFFFFF ^ iv3
s[8] = k0 ^ 0xFFFFFFFF
s[7] = k3
s[6] = k2
s[5] = k1
s[4] = k0
s[3] = k3 ^ 0xFFFFFFFF
s[2] = k2 ^ 0xFFFFFFFF
s[1] = k1 ^ 0xFFFFFFFF
s[0] = k0 ^ 0xFFFFFFFF
self.s = s
self.R1 = 0
self.R2 = 0
self.R3 = 0
for _ in range(32):
F = self.clock_FSM()
self.clock_lfsr(F)
def MULx(self, V: int, c: int) -> int:
if V >> 7:
return ((V << 1) % 256) ^ c
else:
return V << 1
def MULa(self, c: int) -> int:
return (self.MULxPOW(c, 23, 0xA9) << 24) + (self.MULxPOW(c, 245, 0xA9) << 16) + (self.MULxPOW(c, 48, 0xA9) << 8) + self.MULxPOW(c, 239, 0xA9)
def DIVa(self, c: int) -> int:
return (self.MULxPOW(c, 16, 0xA9) << 24) + (self.MULxPOW(c, 39, 0xA9) << 16) + (self.MULxPOW(c, 6, 0xA9) << 8) + self.MULxPOW(c, 64, 0xA9)
def MULxPOW(self, V: int, i: int, c: int) -> int:
if i == 0:
return V
else:
return self.MULx(self.MULxPOW(V, i - 1, c), c)
def S1(self, w: int) -> Bytes:
return self._perform_sbox_transform(Bytes.wrap(w).zfill(4), RIJ_SBOX, 0x1B, True)
def S2(self, w: int) -> Bytes:
return self._perform_sbox_transform(Bytes.wrap(w).zfill(4), SQ, 0x69)
def _perform_sbox_transform(self, w: bytes, sbox: list, val: int, s2=False) -> Bytes:
sqw0, sqw1, sqw2, sqw3 = [sbox[w_i] for w_i in w]
r0 = self.MULx(sqw0, val) ^ sqw1 ^ sqw2 ^ self.MULx(sqw3, val) ^ sqw3
r1 = self.MULx(sqw0, val) ^ sqw0 ^ self.MULx(sqw1, val) ^ sqw2 ^ sqw3
r2 = sqw0 ^ self.MULx(sqw1, val) ^ sqw1 ^ self.MULx(sqw2, val) ^ sqw3
r3 = sqw0 ^ sqw1 ^ self.MULx(sqw2, val) ^ sqw2 ^ self.MULx(sqw3, val)
return Bytes([r0, r1, r2, r3]).to_int()
def clock_FSM(self) -> int:
"""
Used internally. Clocks the internal FSM.
Returns:
int: Next value of `F`.
"""
F = ((self.s[15] + self.R1) % (2 ** 32)) ^ self.R2
r = (self.R2 + (self.R3 ^ self.s[5])) % (2 ** 32)
self.R3 = self.S2(self.R2)
self.R2 = self.S1(self.R1)
self.R1 = r
return F
def clock_lfsr(self, F: int=None):
"""
Used internally. Clocks the LFSR and possibly combines with `F`.
Parameters:
F (int): Value of `F` to be clocked with.
"""
v = ((self.s[0] << 8) & 0xFFFFFF00) ^ self.MULa((self.s[0] >> 24) & 0xFF) ^ self.s[2] ^ ((self.s[11] >> 8) & 0x00FFFFFF) ^ self.DIVa(self.s[11] & 0xFF)
if F:
v^= F
for i in range(15):
self.s[i] = self.s[i + 1]
self.s[15] = v
def generate(self, length: int) -> Bytes:
"""
Generates `length` of keystream.
Parameters:
length (int): Desired length of keystream in bytes.
Returns:
Bytes: Keystream.
"""
_F = self.clock_FSM()
self.clock_lfsr()
ks = []
for _ in range(length):
F = self.clock_FSM()
ks.append(F ^ self.s[0])
self.clock_lfsr()
return sum([Bytes(i).zfill(4) for i in ks])
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/stream_ciphers/snow3g.py
| 0.459561 | 0.170888 |
snow3g.py
|
pypi
|
from samson.prngs.bitsliced_flfsr import BitslicedFLFSR
from samson.core.primitives import StreamCipher, Primitive
from samson.utilities.bytes import Bytes
from samson.core.metadata import ConstructionType, UsageType, SizeType, SizeSpec, EphemeralType, EphemeralSpec
from samson.ace.decorators import register_primitive
# https://github.com/ttsou/airprobe/blob/master/A5.1/python/A51_Tables/a51.py
# Implemented in big endian
@register_primitive()
class A51(StreamCipher):
"""
A5/1 stream cipher
Used in GSM celluar encryption.
"""
CONSTRUCTION_TYPES = [ConstructionType.LFSR]
USAGE_TYPE = UsageType.CELLULAR
KEY_SIZE = SizeSpec(size_type=SizeType.SINGLE, sizes=64)
EPHEMERAL = EphemeralSpec(ephemeral_type=EphemeralType.NONCE, size=SizeSpec(size_type=SizeType.SINGLE, sizes=22))
def __init__(self, key: bytes, frame_num: int):
"""
Parameters:
key (bytes): Key (64 bits).
frame_num (int): Current frame number (22 bits).
"""
Primitive.__init__(self)
self.key = key
self.frame_num = frame_num
self.lfsr_regs = [
BitslicedFLFSR(19, 10, [13, 16, 17, 18]),
BitslicedFLFSR(22, 11, [20, 21]),
BitslicedFLFSR(23, 12, [7, 20, 21, 22])
]
for lfsr in self.lfsr_regs:
lfsr.mix_state(self.key, 64)
lfsr.mix_state(self.frame_num, 22)
for _ in range(100):
self.clock()
def clock(self):
"""
Performs the majority-vote clocking.
"""
majority = sum([lfsr.clock_value() for lfsr in self.lfsr_regs]) // 2
for lfsr in self.lfsr_regs:
if lfsr.clock_value() == majority:
lfsr.clock()
def generate(self, length: int) -> Bytes:
"""
Generates `length` of keystream.
Parameters:
length (int): Desired length of keystream in bytes.
Returns:
Bytes: Keystream.
"""
bitstring = ''
for _ in range(length * 8):
self.clock()
bitstring += str(self.lfsr_regs[0].value() ^ self.lfsr_regs[1].value() ^ self.lfsr_regs[2].value())
return Bytes(int(bitstring, 2)).zfill(length)
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/stream_ciphers/a51.py
| 0.786541 | 0.247748 |
a51.py
|
pypi
|
from samson.utilities.manipulation import left_rotate, get_blocks
from samson.utilities.bytes import Bytes
from samson.core.primitives import StreamCipher, Primitive
from samson.core.metadata import SizeType, SizeSpec, EphemeralSpec, EphemeralType, ConstructionType, FrequencyType
from samson.ace.decorators import register_primitive
from copy import deepcopy
import math
def QUARTER_ROUND(a: int, b: int, c: int, d: int) -> (int, int, int, int):
"""
Performs a quarter round of Salsa.
Parameters:
a (int): Salsa state variable.
b (int): Salsa state variable.
c (int): Salsa state variable.
d (int): Salsa state variable.
Returns:
(int, int, int, int): New values for (a, b, c, d).
"""
b = (b ^ left_rotate((a + d) & 0xFFFFFFFF, 7))
c = (c ^ left_rotate((b + a) & 0xFFFFFFFF, 9))
d = (d ^ left_rotate((c + b) & 0xFFFFFFFF, 13))
a = (a ^ left_rotate((d + c) & 0xFFFFFFFF, 18))
return a, b, c, d
@register_primitive()
class Salsa(StreamCipher):
"""
Salsa stream cipher
Add-rotate-xor (ARX) structure.
https://en.wikipedia.org/wiki/Salsa20
"""
CONSTRUCTION_TYPES = [ConstructionType.ADD_ROTATE_XOR]
EPHEMERAL = EphemeralSpec(ephemeral_type=EphemeralType.NONCE, size=SizeSpec(size_type=SizeType.SINGLE, sizes=96))
USAGE_FREQUENCY = FrequencyType.UNUSUAL
def __init__(self, key: bytes, nonce: bytes, rounds: int=20, constant: bytes=b"expand 32-byte k"):
"""
Parameters:
key (bytes): Key (128 or 256 bits).
nonce (bytes): Nonce (8 bytes).
rounds (int): Number of rounds to perform.
constant (bytes): Constant used in generating the keystream (16 bytes).
"""
Primitive.__init__(self)
# If key is 80 bits, zero pad it (https://cr.yp.to/snuffle/salsafamily-20071225.pdf, 4.1)
if len(key) == 10:
key = Bytes.wrap(key).zfill(16)
# If key is 128 bits, just repeat it
if len(key) == 16:
key += key
self.key = key
self.nonce = nonce
self.rounds = rounds
self.constant = constant
self.counter = 0
def full_round(self, block_num: int, state: list=None) -> Bytes:
"""
Performs a full round of Salsa.
Parameters:
block_num (int): Current block number.
Returns:
Bytes: Keystream block.
"""
ctr_bytes = int.to_bytes(block_num, 8, 'little')
cons_blocks = [int.from_bytes(block, 'little') for block in get_blocks(self.constant, 4)]
key_blocks = [int.from_bytes(block, 'little') for block in get_blocks(self.key, 4)]
ctr_blocks = [int.from_bytes(block, 'little') for block in get_blocks(ctr_bytes, 4)]
nonce_blocks = [int.from_bytes(block, 'little') for block in get_blocks(self.nonce, 4)]
x = state or [
cons_blocks[0], *key_blocks[:4],
cons_blocks[1], *nonce_blocks,
*ctr_blocks, cons_blocks[2],
*key_blocks[4:], cons_blocks[3]
]
x = deepcopy(x)
tmp = deepcopy(x)
for _ in range(self.rounds // 2):
# Odd round
x[ 0], x[ 4], x[ 8], x[12] = QUARTER_ROUND(x[ 0], x[ 4], x[ 8], x[12])
x[ 5], x[ 9], x[13], x[ 1] = QUARTER_ROUND(x[ 5], x[ 9], x[13], x[ 1])
x[10], x[14], x[ 2], x[ 6] = QUARTER_ROUND(x[10], x[14], x[ 2], x[ 6])
x[15], x[ 3], x[ 7], x[11] = QUARTER_ROUND(x[15], x[ 3], x[ 7], x[11])
# Even round
x[ 0], x[ 1], x[ 2], x[ 3] = QUARTER_ROUND(x[ 0], x[ 1], x[ 2], x[ 3])
x[ 5], x[ 6], x[ 7], x[ 4] = QUARTER_ROUND(x[ 5], x[ 6], x[ 7], x[ 4])
x[10], x[11], x[ 8], x[ 9] = QUARTER_ROUND(x[10], x[11], x[ 8], x[ 9])
x[15], x[12], x[13], x[14] = QUARTER_ROUND(x[15], x[12], x[13], x[14])
for i in range(16):
x[i] += tmp[i]
return Bytes(b''.join([int.to_bytes(state_int & 0xFFFFFFFF, 4, 'little') for state_int in x]), byteorder='little')
def yield_state(self, start_chunk: int=0, num_chunks: int=1, state: list=None):
"""
Generates `num_chunks` chunks of keystream starting from `start_chunk`.
Parameters:
num_chunks (int): Desired number of 64-byte keystream chunks.
start_chunk (int): Chunk number to start at.
state (list): Custom state to be directly injected.
Returns:
generator: Keystream chunks.
"""
for iteration in range(start_chunk, start_chunk + num_chunks):
yield self.full_round(iteration, state=state)
def generate(self, length: int) -> Bytes:
"""
Generates `length` of keystream.
Parameters:
length (int): Desired length of keystream in bytes.
Returns:
Bytes: Keystream.
"""
num_chunks = math.ceil(length / 64)
start_chunk = self.counter // 64
counter_mod = self.counter % 64
if counter_mod:
num_chunks += 1
keystream = sum(list(self.yield_state(start_chunk=start_chunk, num_chunks=num_chunks)))[counter_mod:counter_mod+length]
self.counter += length
return keystream
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/stream_ciphers/salsa.py
| 0.80271 | 0.567098 |
salsa.py
|
pypi
|
from samson.prngs.flfsr import FLFSR
from samson.utilities.bytes import Bytes
from samson.core.primitives import StreamCipher, Primitive
from samson.math.symbols import Symbol
from samson.math.algebra.rings.integer_ring import ZZ
from samson.core.metadata import ConstructionType, UsageType, SizeType, SizeSpec, EphemeralType, EphemeralSpec
from samson.ace.decorators import register_primitive
FSM_MATRIX = [
[ 0, 0, 0, 4, 0, 4, 4, 4, 0, 4, 4, 4, 4, 4, 4, 8],
[12, 12, 12, 8, 12, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 4],
[ 4, 4, 4, 0, 4, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 12],
[ 8, 8, 8, 12, 8, 12, 12, 12, 8, 12, 12, 12, 12, 12, 12, 0],
[ 5, 1, 1, 1, 1, 1, 1, 13, 1, 1, 1, 13, 1, 13, 13, 13],
[ 9, 13, 13, 13, 13, 13, 13, 1, 13, 13, 13, 1, 13, 1, 1, 1],
[ 1, 5, 5, 5, 5, 5, 5, 9, 5, 5, 5, 9, 5, 9, 9, 9],
[13, 9, 9, 9, 9, 9, 9, 5, 9, 9, 9, 5, 9, 5, 5, 5],
[14, 14, 14, 2, 14, 2, 2, 2, 14, 2, 2, 2, 2, 2, 2, 6],
[ 2, 2, 2, 14, 2, 14, 14, 14, 2, 14, 14, 14, 14, 14, 14, 10],
[10, 10, 10, 6, 10, 6, 6, 6, 10, 6, 6, 6, 6, 6, 6, 2],
[ 6, 6, 6, 10, 6, 10, 10, 10, 6, 10, 10, 10, 10, 10, 10, 14],
[11, 7, 7, 7, 7, 7, 7, 3, 7, 7, 7, 3, 7, 3, 3, 3],
[ 7, 11, 11, 11, 11, 11, 11, 15, 11, 11, 11, 15, 11, 15, 15, 15],
[15, 3, 3, 3, 3, 3, 3, 7, 3, 3, 3, 7, 3, 7, 7, 7],
[ 3, 15, 15, 15, 15, 15, 15, 11, 15, 15, 15, 11, 15, 11, 11, 11]
]
OUTPUT_MATRIX = [
[ 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0],
[ 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0],
[ 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0],
[ 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0],
[ 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1],
[ 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1],
[ 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1],
[ 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1],
[ 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0],
[ 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0],
[ 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0],
[ 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0],
[ 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1],
[ 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1],
[ 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1],
[ 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1]
]
E0_CHUNK = 5120
POLY_SIZES = [25, 31, 33, 39]
@register_primitive()
class E0(StreamCipher):
"""
E0 stream cipher
Used in Bluetooth.
"""
CONSTRUCTION_TYPES = [ConstructionType.LFSR]
USAGE_TYPE = UsageType.WIRELESS
KEY_SIZE = SizeSpec(size_type=SizeType.SINGLE, sizes=128)
EPHEMERAL = EphemeralSpec(ephemeral_type=EphemeralType.NONCE, size=SizeSpec(size_type=SizeType.SINGLE, sizes=96))
def __init__(self, kc: list, addr: list, master_clk: list):
"""
Parameters:
kc (list): Session key derived from master key.
addr (list): Hardware address.
master_clk (list): Master clock values.
"""
Primitive.__init__(self)
x = Symbol('x')
_ = (ZZ/ZZ(2))[x]
self.lfsrs = [
FLFSR(0, x**25 + x**20 + x**12 + x**8 + 1),
FLFSR(0, x**31 + x**24 + x**16 + x**12 + 1),
FLFSR(0, x**33 + x**28 + x**24 + x**4 + 1),
FLFSR(0, x**39 + x**36 + x**28 + x**4 + 1)
]
self.kc = kc
self.addr = addr
self.master_clk = master_clk
self.state = 0
self.key = 0
self.key_schedule()
def __reprdir__(self):
return ['key', 'state', 'kc', 'addr', 'master_clk']
def key_schedule(self):
"""
Prepares the internal state for encryption.
"""
ks_input = [None] * 4
ks_input[0] = ((self.master_clk[3] & 1) | (self.kc[0] << 1) | (self.kc[4] << 9) | (self.kc[8] << 17) | (self.kc[12] << 25) | (self.master_clk[1] << 33) | (self.addr[2] << 41)) & 0xFFFFFFFFFFFFFFFF
ks_input[1] = (0x1 | (self.master_clk[0] << 3) | (self.kc[1] << 7) | (self.kc[5] << 15) | (self.kc[9] << 23) | (self.kc[13] << 31) | (self.addr[0] << 39) | (self.addr[3] << 47)) & 0xFFFFFFFFFFFFFFFF
ks_input[2] = ((self.master_clk[3] >> 1) | (self.kc[2] << 1) | (self.kc[6] << 9) | (self.kc[10] << 17) | (self.kc[14] << 25) | (self.master_clk[2] << 33) | (self.addr[4] << 41)) & 0xFFFFFFFFFFFFFFFF
ks_input[3] = (0x7 | ((self.master_clk[0] >> 4) << 3) | (self.kc[3] << 7) | (self.kc[7] << 15) | (self.kc[11] << 23) | (self.kc[15] << 31) | (self.addr[1] << 39) | (self.addr[5] << 47)) & 0xFFFFFFFFFFFFFFFF
z = [0] * 16
z_i = 0
sv_state = 0
for i in range(240):
if i < 39:
self.state = 0
elif i == 238:
sv_state = self.state
self.shift()
# 'Disable' LFSRs until they're full
for j, size in enumerate(POLY_SIZES):
if i < size and (self.lfsrs[j].state & 1):
self.lfsrs[j].state -=1
for h in range(4):
self.lfsrs[h].state ^= ks_input[h] & 1
for j in range(4):
ks_input[j] >>= 1
if i >= 111 and i < 239:
z[(z_i // 8)] >>= 1
z[(z_i // 8)] |= self.key << 7
z_i += 1
self.lfsrs[0].state = z[0] | (z[4] << 8) | (z[ 8] << 16) | ((z[12] & 1) << 24)
self.lfsrs[1].state = z[1] | (z[5] << 8) | (z[ 9] << 16) | ((z[12] >> 1) << 24)
self.lfsrs[2].state = z[2] | (z[6] << 8) | (z[10] << 16) | (z[13] << 24) | ((z[15] & 1) << 32)
self.lfsrs[3].state = z[3] | (z[7] << 8) | (z[11] << 16) | (z[14] << 24) | ((z[15] >> 1) << 32)
reg_output = self.get_output_bit()
self.key = OUTPUT_MATRIX[self.state][reg_output] & 1
self.state = FSM_MATRIX[sv_state][reg_output]
def get_output_bit(self) -> int:
"""
Returns the output bit from the summation generator.
"""
return ((self.lfsrs[0].state >> 23) & 1) | ((self.lfsrs[1].state >> 22) & 2) | ((self.lfsrs[2].state >> 29) & 4) | ((self.lfsrs[3].state >> 28) & 8)
def shift(self):
"""
Clocks the LFSRs and calculates the new state.
"""
for lfsr in self.lfsrs:
_ = lfsr.clock()
reg_output = self.get_output_bit()
old_state = self.state
self.state = FSM_MATRIX[old_state][reg_output]
self.key = OUTPUT_MATRIX[old_state][reg_output] & 1
def generate(self, length: int) -> Bytes:
"""
Generates `length` of keystream.
Parameters:
length (int): Desired length of keystream in bytes.
Returns:
Bytes: Keystream.
"""
bits = []
for _ in range(length * 8):
bits.append(str(self.key))
self.shift()
return Bytes(int(''.join(bits), 2)).zfill(length)
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/stream_ciphers/e0.py
| 0.430866 | 0.15925 |
e0.py
|
pypi
|
from samson.utilities.manipulation import left_rotate, get_blocks
from samson.utilities.bytes import Bytes
from samson.stream_ciphers.salsa import Salsa
from samson.core.metadata import SizeType, SizeSpec, EphemeralSpec, EphemeralType, FrequencyType
from samson.ace.decorators import register_primitive
from copy import deepcopy
# https://en.wikipedia.org/wiki/Salsa20
def QUARTER_ROUND(a: int, b: int, c: int, d: int) -> (int, int, int, int):
"""
Performs a quarter round of ChaCha.
Parameters:
a (int): ChaCha state variable.
b (int): ChaCha state variable.
c (int): ChaCha state variable.
d (int): ChaCha state variable.
Returns:
(int, int, int, int): New values for (a, b, c, d).
"""
a = (a + b) & 0xFFFFFFFF; d ^= a; d = left_rotate(d, 16)
c = (c + d) & 0xFFFFFFFF; b ^= c; b = left_rotate(b, 12)
a = (a + b) & 0xFFFFFFFF; d ^= a; d = left_rotate(d, 8)
c = (c + d) & 0xFFFFFFFF; b ^= c; b = left_rotate(b, 7)
return a, b, c, d
@register_primitive()
class ChaCha(Salsa):
"""
ChaCha stream cipher
Add-rotate-xor (ARX) structure.
"""
EPHEMERAL = EphemeralSpec(ephemeral_type=EphemeralType.NONCE, size=SizeSpec(size_type=SizeType.SINGLE, sizes=96))
USAGE_FREQUENCY = FrequencyType.PROLIFIC
def __init__(self, key: bytes, nonce: bytes, rounds: int=20, constant: bytes=b"expand 32-byte k"):
"""
Parameters:
key (bytes): Key (128 or 256 bits).
nonce (bytes): Nonce (12 bytes).
rounds (int): Number of rounds to perform.
constant (bytes): Constant used in generating the keystream (16 bytes).
"""
super().__init__(key, nonce, rounds, constant)
def full_round(self, block_num: int, state: list=None) -> Bytes:
"""
Performs a full round of ChaCha.
Parameters:
block_num (int): Current block number.
Returns:
Bytes: Keystream block.
"""
ctr_bytes = int.to_bytes(block_num, 4, 'little')
x = state or [
*[int.from_bytes(block, 'little') for block in get_blocks(self.constant, 4)],
*[int.from_bytes(block, 'little') for block in get_blocks(self.key, 4)],
int.from_bytes(ctr_bytes, 'little'),
*[int.from_bytes(block, 'little') for block in get_blocks(self.nonce, 4)]
]
tmp = deepcopy(x)
for _ in range(self.rounds // 2):
# Odd round
x[0], x[4], x[ 8], x[12] = QUARTER_ROUND(x[0], x[4], x[ 8], x[12])
x[1], x[5], x[ 9], x[13] = QUARTER_ROUND(x[1], x[5], x[ 9], x[13])
x[2], x[6], x[10], x[14] = QUARTER_ROUND(x[2], x[6], x[10], x[14])
x[3], x[7], x[11], x[15] = QUARTER_ROUND(x[3], x[7], x[11], x[15])
# Even round
x[0], x[5], x[10], x[15] = QUARTER_ROUND(x[0], x[5], x[10], x[15])
x[1], x[6], x[11], x[12] = QUARTER_ROUND(x[1], x[6], x[11], x[12])
x[2], x[7], x[ 8], x[13] = QUARTER_ROUND(x[2], x[7], x[ 8], x[13])
x[3], x[4], x[ 9], x[14] = QUARTER_ROUND(x[3], x[4], x[ 9], x[14])
for i in range(16):
x[i] += tmp[i]
return Bytes(b''.join([int.to_bytes(state_int & 0xFFFFFFFF, 4, 'little') for state_int in x]), byteorder='little')
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/stream_ciphers/chacha.py
| 0.810216 | 0.510374 |
chacha.py
|
pypi
|
from samson.utilities.bytes import Bytes
from samson.core.primitives import StreamCipher, Primitive
from samson.ace.decorators import has_exploit
from samson.ace.exploit import BitlevelMalleability
from samson.attacks.rc4_prepend_attack import RC4PrependAttack
from samson.core.metadata import SizeType, SizeSpec, FrequencyType
from samson.ace.decorators import register_primitive
@has_exploit(RC4PrependAttack)
@has_exploit(BitlevelMalleability)
@register_primitive()
class RC4(StreamCipher):
"""
Rivest Cipher 4 (RC4)
Broken stream ciphers with large, initial-keystream biases.
"""
KEY_SIZE = SizeSpec(size_type=SizeType.RANGE, sizes=range(40, 2041))
USAGE_FREQUENCY = FrequencyType.UNUSUAL
def __init__(self, key: bytes):
"""
Parameters:
key (bytes): Key (40-2040 bits).
"""
Primitive.__init__(self)
self.key = key
self.S = self.key_schedule(key)
self.i = 0
self.j = 0
def key_schedule(self, key: bytes) -> list:
"""
Prepares the internal state using the key.
Parameters:
key (bytes): Key.
Returns:
list: State parameter `S`.
"""
key_length = len(key)
S = []
for i in range(256):
S.append(i)
j = 0
for i in range(256):
j = (j + S[i] + key[i % key_length]) % 256
S[i], S[j] = S[j], S[i]
return S
def generate(self, length: int) -> Bytes:
"""
Generates `length` of keystream.
Parameters:
length (int): Desired length of keystream in bytes.
Returns:
Bytes: Keystream.
"""
keystream = Bytes(b'')
for _ in range(length):
self.i = (self.i + 1) % 256
self.j = (self.j + self.S[self.i]) % 256
self.S[self.i], self.S[self.j] = self.S[self.j], self.S[self.i]
keystream += bytes([self.S[(self.S[self.i] + self.S[self.j]) % 256]])
return keystream
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/stream_ciphers/rc4.py
| 0.778902 | 0.171685 |
rc4.py
|
pypi
|
from samson.analyzers.analyzer import Analyzer
from samson.analysis.general import chisquare
from collections import Counter
import string
import re
from samson.auxiliary.lazy_loader import LazyLoader
_eng_data = LazyLoader('_eng_data', globals(), 'samson.auxiliary.english_data')
ASCII_RANGE = {k:0 for k in [10, 13] + list(range(20, 127))}
ASCII_LOWER = {k:0 for k in bytes(string.ascii_lowercase, 'utf-8')}
DELIMITER_REGEX = re.compile(b'[?.,! ]')
def _num_common_first_letters(words):
if not len(words):
return 0
return sum([_eng_data.FIRST_LETTER_FREQUENCIES[bytes([word[0]])] for word in words if len(word) > 0 and bytes([word[0]]) in _eng_data.FIRST_LETTER_FREQUENCIES]) / len(words)
def weighted_token_ratio(in_bytes, weighted_dict, in_bytes_len):
count = in_bytes.count
return sum([val * count(key) for key, val in weighted_dict]) / in_bytes_len
def key_count(in_bytes, key):
return (key, in_bytes.count(key))
class EnglishAnalyzer(Analyzer):
"""
Analyzer for English text.
"""
def analyze(self, in_bytes: bytes) -> float:
"""
Takes in a bytes-like object and returns a relative score.
Parameters:
in_bytes (bytes): The bytes-like object to be "scored".
Returns:
float: The relative score of the object.
"""
processed_dict = self.preprocess(in_bytes)
word_freq = processed_dict['word_freq']
alphabet_ratio = processed_dict['alphabet_ratio']
ascii_ratio = processed_dict['ascii_ratio']
common_words = processed_dict['common_words']
first_letter_freq = processed_dict['first_letter_freq']
found_words = processed_dict['found_words']
delimited_words = processed_dict['delimited_words']
bigram_score = processed_dict['bigram_score']
word_score = sum([len(word) ** (3.5 + (bytes(word, 'utf-8') in delimited_words) * 1) for word in found_words])
return (word_freq * 2 + 1) * (((alphabet_ratio + 0.6) ** 9) * 60) * ((ascii_ratio + 0.3) ** 5) * (common_words + 1) * (first_letter_freq + 1) * (word_score + 1) * (bigram_score * 25)
def preprocess(self, in_bytes: bytes, in_ciphers: bytes=None) -> dict:
"""
Takes in a bytes-like object and returns the processed feature-space used in scoring.
This is good for training statistical models.
Parameters:
in_bytes (bytes): The bytes-like object to be "scored".
in_ciphers (bytes): (Optional) If set, will check if `in_bytes` is a subset of `in_ciphers`. Used for supervised machine learning.
Returns:
dictionary: Dictionary containing the processed features.
"""
bytes_lower = in_bytes.lower()
byte_len = len(in_bytes)
delimited_words = [word for word in re.split(DELIMITER_REGEX, bytes_lower) if word != b'']
word_freq = sum([1 for w in delimited_words if len(w) > 2 and len(w) < 8 and all([letter in ASCII_RANGE for letter in w])])
alphabet_ratio = sum([1 for char in bytes_lower if char in ASCII_LOWER]) / byte_len
ascii_ratio = sum([1 for char in bytes_lower if char in ASCII_RANGE]) / byte_len
bigram_score = weighted_token_ratio(bytes_lower, _eng_data.MOST_COMMON_BIGRAMS_LOWER, byte_len)
first_letter_freq = _num_common_first_letters(delimited_words)
found_words = _eng_data.TOKENIZE([bytes_lower.decode('latin-1')])
common_words = len([word for word in found_words if word in _eng_data.MOST_COMMON_WORDS])
# We divide it by the `length*2` to normalize it since I empirically found that the chisquared of
# a uniform distribution of `length` bytes tends towards it.
monogram_chisquared = chisquare(Counter(in_bytes), _eng_data.CHAR_FREQ, byte_len) / (byte_len * 2)
return_dict = {
'word_freq': word_freq,
'alphabet_ratio': alphabet_ratio,
'ascii_ratio': ascii_ratio,
'common_words': common_words,
'first_letter_freq': first_letter_freq,
'found_words': found_words,
'delimited_words': delimited_words,
'monogram_chisquared': monogram_chisquared,
'bigram_score': bigram_score
}
if in_ciphers != None:
return_dict['is_correct'] = int(in_bytes in in_ciphers)
return return_dict
|
/samson-crypto-0.3.0.tar.gz/samson-crypto-0.3.0/samson/analyzers/english_analyzer.py
| 0.831964 | 0.298964 |
english_analyzer.py
|
pypi
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.