code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def read_gff3(f, full=True, annotation=None, as_df=False, nrows=None): """Read files in the General Feature Format. Parameters ---------- f : str Path to GFF file. full : bool, default True Whether to read and interpret the annotation column. as_df : bool, default False Whether to return as pandas DataFrame instead of PyRanges. nrows : int, default None Number of rows to read. Default None, i.e. all. Notes ----- The gff3 format encodes both Start and End as 1-based included. PyRanges (and also the DF returned by this function, if as_df=True), instead encodes intervals as 0-based, Start included and End excluded. See Also -------- pyranges.read_gtf : read files in the Gene Transfer Format """ _skiprows = skiprows(f) if not full: return read_gtf_restricted(f, _skiprows, as_df=as_df, nrows=nrows) dtypes = {"Chromosome": "category", "Feature": "category", "Strand": "category"} names = "Chromosome Source Feature Start End Score Strand Frame Attribute".split() df_iter = pd.read_csv( f, comment="#", sep="\t", header=None, names=names, dtype=dtypes, chunksize=int(1e5), skiprows=_skiprows, nrows=nrows, ) dfs = [] for df in df_iter: extra = to_rows_gff3(df.Attribute.astype(str)) df = df.drop("Attribute", axis=1) extra.set_index(df.index, inplace=True) ndf = pd.concat([df, extra], axis=1, sort=False) dfs.append(ndf) df = pd.concat(dfs, sort=False) df.loc[:, "Start"] = df.Start - 1 if not as_df: return PyRanges(df) else: return df
Read files in the General Feature Format. Parameters ---------- f : str Path to GFF file. full : bool, default True Whether to read and interpret the annotation column. as_df : bool, default False Whether to return as pandas DataFrame instead of PyRanges. nrows : int, default None Number of rows to read. Default None, i.e. all. Notes ----- The gff3 format encodes both Start and End as 1-based included. PyRanges (and also the DF returned by this function, if as_df=True), instead encodes intervals as 0-based, Start included and End excluded. See Also -------- pyranges.read_gtf : read files in the Gene Transfer Format
read_gff3
python
pyranges/pyranges
pyranges/readers.py
https://github.com/pyranges/pyranges/blob/master/pyranges/readers.py
MIT
def fdr(p_vals): """Adjust p-values with Benjamini-Hochberg. Parameters ---------- data : array-like Returns ------- Pandas.DataFrame DataFrame where values are order of data. Examples -------- >>> d = {'Chromosome': ['chr3', 'chr6', 'chr13'], 'Start': [146419383, 39800100, 24537618], 'End': [146419483, 39800200, 24537718], 'Strand': ['-', '+', '-'], 'PValue': [0.0039591368855297175, 0.0037600512992788937, 0.0075061166500909205]} >>> gr = pr.from_dict(d) >>> gr +--------------+-----------+-----------+--------------+-------------+ | Chromosome | Start | End | Strand | PValue | | (category) | (int64) | (int64) | (category) | (float64) | |--------------+-----------+-----------+--------------+-------------| | chr3 | 146419383 | 146419483 | - | 0.00395914 | | chr6 | 39800100 | 39800200 | + | 0.00376005 | | chr13 | 24537618 | 24537718 | - | 0.00750612 | +--------------+-----------+-----------+--------------+-------------+ Stranded PyRanges object has 3 rows and 5 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.FDR = pr.stats.fdr(gr.PValue) >>> gr.print(formatting={"PValue": "{:.4f}", "FDR": "{:.4}"}) +--------------+-----------+-----------+--------------+-------------+-------------+ | Chromosome | Start | End | Strand | PValue | FDR | | (category) | (int64) | (int64) | (category) | (float64) | (float64) | |--------------+-----------+-----------+--------------+-------------+-------------| | chr3 | 146419383 | 146419483 | - | 0.004 | 0.005939 | | chr6 | 39800100 | 39800200 | + | 0.0038 | 0.01128 | | chr13 | 24537618 | 24537718 | - | 0.0075 | 0.007506 | +--------------+-----------+-----------+--------------+-------------+-------------+ Stranded PyRanges object has 3 rows and 6 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ from scipy.stats import rankdata # type: ignore ranked_p_values = rankdata(p_vals) fdr = p_vals * len(p_vals) / ranked_p_values fdr[fdr > 1] = 1 return fdr
Adjust p-values with Benjamini-Hochberg. Parameters ---------- data : array-like Returns ------- Pandas.DataFrame DataFrame where values are order of data. Examples -------- >>> d = {'Chromosome': ['chr3', 'chr6', 'chr13'], 'Start': [146419383, 39800100, 24537618], 'End': [146419483, 39800200, 24537718], 'Strand': ['-', '+', '-'], 'PValue': [0.0039591368855297175, 0.0037600512992788937, 0.0075061166500909205]} >>> gr = pr.from_dict(d) >>> gr +--------------+-----------+-----------+--------------+-------------+ | Chromosome | Start | End | Strand | PValue | | (category) | (int64) | (int64) | (category) | (float64) | |--------------+-----------+-----------+--------------+-------------| | chr3 | 146419383 | 146419483 | - | 0.00395914 | | chr6 | 39800100 | 39800200 | + | 0.00376005 | | chr13 | 24537618 | 24537718 | - | 0.00750612 | +--------------+-----------+-----------+--------------+-------------+ Stranded PyRanges object has 3 rows and 5 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr.FDR = pr.stats.fdr(gr.PValue) >>> gr.print(formatting={"PValue": "{:.4f}", "FDR": "{:.4}"}) +--------------+-----------+-----------+--------------+-------------+-------------+ | Chromosome | Start | End | Strand | PValue | FDR | | (category) | (int64) | (int64) | (category) | (float64) | (float64) | |--------------+-----------+-----------+--------------+-------------+-------------| | chr3 | 146419383 | 146419483 | - | 0.004 | 0.005939 | | chr6 | 39800100 | 39800200 | + | 0.0038 | 0.01128 | | chr13 | 24537618 | 24537718 | - | 0.0075 | 0.007506 | +--------------+-----------+-----------+--------------+-------------+-------------+ Stranded PyRanges object has 3 rows and 6 columns from 3 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
fdr
python
pyranges/pyranges
pyranges/statistics.py
https://github.com/pyranges/pyranges/blob/master/pyranges/statistics.py
MIT
def fisher_exact(tp, fp, fn, tn, pseudocount=0): """Fisher's exact for contingency tables. Computes the hypotheses two-sided, less and greater at the same time. The odds-ratio is Parameters ---------- tp : array-like of int Top left square of contingency table (true positives). fp : array-like of int Top right square of contingency table (false positives). fn : array-like of int Bottom left square of contingency table (false negatives). tn : array-like of int Bottom right square of contingency table (true negatives). pseudocount : float, default 0 Values > 0 allow Odds Ratio to always be a finite number. Notes ----- The odds-ratio is computed thusly: ``((tp + pseudocount) / (fp + pseudocount)) / ((fn + pseudocount) / (tn + pseudocount))`` Returns ------- pandas.DataFrame DataFrame with columns OR and P, PLeft and PRight. See Also -------- pr.stats.fdr : correct for multiple testing Examples -------- >>> d = {"TP": [12, 0], "FP": [5, 12], "TN": [29, 10], "FN": [2, 2]} >>> df = pd.DataFrame(d) >>> df TP FP TN FN 0 12 5 29 2 1 0 12 10 2 >>> pr.stats.fisher_exact(df.TP, df.FP, df.TN, df.FN) OR P PLeft PRight 0 0.165517 0.080269 0.044555 0.994525 1 0.000000 0.000067 0.000034 1.000000 """ try: from fisher import pvalue_npy # type: ignore except ImportError: import sys print( "fisher needs to be installed to use fisher exact. pip install fisher or conda install -c bioconda fisher." ) sys.exit(-1) tp = np.array(tp, dtype=np.uint) fp = np.array(fp, dtype=np.uint) fn = np.array(fn, dtype=np.uint) tn = np.array(tn, dtype=np.uint) left, right, twosided = pvalue_npy(tp, fp, fn, tn) OR = ((tp + pseudocount) / (fp + pseudocount)) / ((fn + pseudocount) / (tn + pseudocount)) df = pd.DataFrame({"OR": OR, "P": twosided, "PLeft": left, "PRight": right}) return df
Fisher's exact for contingency tables. Computes the hypotheses two-sided, less and greater at the same time. The odds-ratio is Parameters ---------- tp : array-like of int Top left square of contingency table (true positives). fp : array-like of int Top right square of contingency table (false positives). fn : array-like of int Bottom left square of contingency table (false negatives). tn : array-like of int Bottom right square of contingency table (true negatives). pseudocount : float, default 0 Values > 0 allow Odds Ratio to always be a finite number. Notes ----- The odds-ratio is computed thusly: ``((tp + pseudocount) / (fp + pseudocount)) / ((fn + pseudocount) / (tn + pseudocount))`` Returns ------- pandas.DataFrame DataFrame with columns OR and P, PLeft and PRight. See Also -------- pr.stats.fdr : correct for multiple testing Examples -------- >>> d = {"TP": [12, 0], "FP": [5, 12], "TN": [29, 10], "FN": [2, 2]} >>> df = pd.DataFrame(d) >>> df TP FP TN FN 0 12 5 29 2 1 0 12 10 2 >>> pr.stats.fisher_exact(df.TP, df.FP, df.TN, df.FN) OR P PLeft PRight 0 0.165517 0.080269 0.044555 0.994525 1 0.000000 0.000067 0.000034 1.000000
fisher_exact
python
pyranges/pyranges
pyranges/statistics.py
https://github.com/pyranges/pyranges/blob/master/pyranges/statistics.py
MIT
def mcc(grs, genome=None, labels=None, strand=False, verbose=False): """Compute Matthew's correlation coefficient for PyRanges overlaps. Parameters ---------- grs : list of PyRanges PyRanges to compare. genome : DataFrame or dict, default None Should contain chromosome sizes. By default, end position of the rightmost intervals are used as proxies for the chromosome size, but it is recommended to use a genome. labels : list of str, default None Names to give the PyRanges in the output. strand : bool, default False Whether to compute correlations per strand. verbose : bool, default False Warn if some chromosomes are in the genome, but not in the PyRanges. Examples -------- >>> grs = [pr.data.aorta(), pr.data.aorta(), pr.data.aorta2()] >>> mcc = pr.stats.mcc(grs, labels="abc", genome={"chr1": 2100000}) >>> mcc T F TP FP TN FN MCC 0 a a 728 0 2099272 0 1.00000 1 a b 728 0 2099272 0 1.00000 3 a c 457 485 2098787 271 0.55168 2 b a 728 0 2099272 0 1.00000 5 b b 728 0 2099272 0 1.00000 6 b c 457 485 2098787 271 0.55168 4 c a 457 271 2098787 485 0.55168 7 c b 457 271 2098787 485 0.55168 8 c c 942 0 2099058 0 1.00000 To create a symmetric matrix (useful for heatmaps of correlations): >>> mcc.set_index(["T", "F"]).MCC.unstack().rename_axis(None, axis=0) F a b c a 1.00000 1.00000 0.55168 b 1.00000 1.00000 0.55168 c 0.55168 0.55168 1.00000 """ import sys from itertools import chain, combinations_with_replacement if labels is None: _labels = list(range(len(grs))) _labels = combinations_with_replacement(_labels, r=2) else: assert len(labels) == len(grs) _labels = combinations_with_replacement(labels, r=2) # remove all non-loc columns before computation grs = [gr.merge(strand=strand) for gr in grs] if genome is not None: if isinstance(genome, (pd.DataFrame, pr.PyRanges)): genome_length = int(genome.End.sum()) else: genome_length = sum(genome.values()) if verbose: # check that genome definition does not have many more # chromosomes than datafiles gr_cs = set(chain(*[gr.chromosomes for gr in grs])) g_cs = set(genome.chromosomes) surplus = g_cs - gr_cs if len(surplus): print( "The following chromosomes are in the genome, but not the PyRanges:", ", ".join(surplus), file=sys.stderr, ) if strand: def make_stranded(df): df = df.copy() df2 = df.copy() df.insert(df.shape[1], "Strand", "+") df2.insert(df2.shape[1], "Strand", "-") return pd.concat([df, df2]) genome = genome.apply(make_stranded) else: d = defaultdict(int) for gr in grs: for k, v in gr: d[k] = max(d[k], v.End.max()) genome_length = sum(d.values()) strandedness = "same" if strand else None rowdicts = [] for (lt, lf), (t, f) in zip(_labels, combinations_with_replacement(grs, r=2)): if verbose: print(lt, lf, file=sys.stderr) if lt == lf: if not strand: tp = t.length fn = 0 tn = genome_length - tp fp = 0 rowdicts.append({"T": lt, "F": lf, "TP": tp, "FP": fp, "TN": tn, "FN": fn, "MCC": 1}) else: for strand in "+ -".split(): tp = t[strand].length fn = 0 tn = genome_length - tp fp = 0 rowdicts.append( { "T": lt, "F": lf, "Strand": strand, "TP": tp, "FP": fp, "TN": tn, "FN": fn, "MCC": 1, } ) continue else: j = t.join(f, strandedness=strandedness) tp_gr = j.new_position("intersection").merge(strand=strand) if strand: for strand in "+ -".split(): tp = tp_gr[strand].length fp = f[strand].length - tp fn = t[strand].length - tp tn = genome_length - (tp + fp + fn) mcc = _mcc(tp, fp, tn, fn) rowdicts.append( { "T": lt, "F": lf, "Strand": strand, "TP": tp, "FP": fp, "TN": tn, "FN": fn, "MCC": mcc, } ) rowdicts.append( { "T": lf, "F": lt, "Strand": strand, "TP": tp, "FP": fn, "TN": tn, "FN": fp, "MCC": mcc, } ) else: tp = tp_gr.length fp = f.length - tp fn = t.length - tp tn = genome_length - (tp + fp + fn) mcc = _mcc(tp, fp, tn, fn) rowdicts.append( { "T": lt, "F": lf, "TP": tp, "FP": fp, "TN": tn, "FN": fn, "MCC": mcc, } ) rowdicts.append( { "T": lf, "F": lt, "TP": tp, "FP": fn, "TN": tn, "FN": fp, "MCC": mcc, } ) df = pd.DataFrame.from_dict(rowdicts).sort_values(["T", "F"]) return df
Compute Matthew's correlation coefficient for PyRanges overlaps. Parameters ---------- grs : list of PyRanges PyRanges to compare. genome : DataFrame or dict, default None Should contain chromosome sizes. By default, end position of the rightmost intervals are used as proxies for the chromosome size, but it is recommended to use a genome. labels : list of str, default None Names to give the PyRanges in the output. strand : bool, default False Whether to compute correlations per strand. verbose : bool, default False Warn if some chromosomes are in the genome, but not in the PyRanges. Examples -------- >>> grs = [pr.data.aorta(), pr.data.aorta(), pr.data.aorta2()] >>> mcc = pr.stats.mcc(grs, labels="abc", genome={"chr1": 2100000}) >>> mcc T F TP FP TN FN MCC 0 a a 728 0 2099272 0 1.00000 1 a b 728 0 2099272 0 1.00000 3 a c 457 485 2098787 271 0.55168 2 b a 728 0 2099272 0 1.00000 5 b b 728 0 2099272 0 1.00000 6 b c 457 485 2098787 271 0.55168 4 c a 457 271 2098787 485 0.55168 7 c b 457 271 2098787 485 0.55168 8 c c 942 0 2099058 0 1.00000 To create a symmetric matrix (useful for heatmaps of correlations): >>> mcc.set_index(["T", "F"]).MCC.unstack().rename_axis(None, axis=0) F a b c a 1.00000 1.00000 0.55168 b 1.00000 1.00000 0.55168 c 0.55168 0.55168 1.00000
mcc
python
pyranges/pyranges
pyranges/statistics.py
https://github.com/pyranges/pyranges/blob/master/pyranges/statistics.py
MIT
def rowbased_spearman(x, y): """Fast row-based Spearman's correlation. Parameters ---------- x : matrix-like 2D numerical matrix. Same size as y. y : matrix-like 2D numerical matrix. Same size as x. Returns ------- numpy.array Array with same length as input, where values are P-values. See Also -------- pyranges.statistics.rowbased_pearson : fast row-based Pearson's correlation. pr.stats.fdr : correct for multiple testing Examples -------- >>> x = np.array([[7, 2, 9], [3, 6, 0], [0, 6, 3]]) >>> y = np.array([[5, 3, 2], [9, 6, 0], [7, 3, 5]]) Perform Spearman's correlation pairwise on each row in 10x10 matrixes: >>> pr.stats.rowbased_spearman(x, y) array([-0.5, 0.5, -1. ]) """ x = np.asarray(x) y = np.asarray(y) rx = rowbased_rankdata(x) ry = rowbased_rankdata(y) return rowbased_pearson(rx, ry)
Fast row-based Spearman's correlation. Parameters ---------- x : matrix-like 2D numerical matrix. Same size as y. y : matrix-like 2D numerical matrix. Same size as x. Returns ------- numpy.array Array with same length as input, where values are P-values. See Also -------- pyranges.statistics.rowbased_pearson : fast row-based Pearson's correlation. pr.stats.fdr : correct for multiple testing Examples -------- >>> x = np.array([[7, 2, 9], [3, 6, 0], [0, 6, 3]]) >>> y = np.array([[5, 3, 2], [9, 6, 0], [7, 3, 5]]) Perform Spearman's correlation pairwise on each row in 10x10 matrixes: >>> pr.stats.rowbased_spearman(x, y) array([-0.5, 0.5, -1. ])
rowbased_spearman
python
pyranges/pyranges
pyranges/statistics.py
https://github.com/pyranges/pyranges/blob/master/pyranges/statistics.py
MIT
def rowbased_pearson(x, y): """Fast row-based Pearson's correlation. Parameters ---------- x : matrix-like 2D numerical matrix. Same size as y. y : matrix-like 2D numerical matrix. Same size as x. Returns ------- numpy.array Array with same length as input, where values are P-values. See Also -------- pyranges.statistics.rowbased_spearman : fast row-based Spearman's correlation. pr.stats.fdr : correct for multiple testing Examples -------- >>> x = np.array([[7, 2, 9], [3, 6, 0], [0, 6, 3]]) >>> y = np.array([[5, 3, 2], [9, 6, 0], [7, 3, 5]]) Perform Pearson's correlation pairwise on each row in 10x10 matrixes: >>> pr.stats.rowbased_pearson(x, y) array([-0.09078413, 0.65465367, -1. ]) """ # Thanks to https://github.com/dengemann def ss(a, axis): return np.sum(a * a, axis=axis) x = np.asarray(x) y = np.asarray(y) mx = x.mean(axis=-1) my = y.mean(axis=-1) xm, ym = x - mx[..., None], y - my[..., None] r_num = np.add.reduce(xm * ym, axis=-1) r_den = np.sqrt(ss(xm, axis=-1) * ss(ym, axis=-1)) with np.errstate(divide="ignore", invalid="ignore"): r = r_num / r_den return r
Fast row-based Pearson's correlation. Parameters ---------- x : matrix-like 2D numerical matrix. Same size as y. y : matrix-like 2D numerical matrix. Same size as x. Returns ------- numpy.array Array with same length as input, where values are P-values. See Also -------- pyranges.statistics.rowbased_spearman : fast row-based Spearman's correlation. pr.stats.fdr : correct for multiple testing Examples -------- >>> x = np.array([[7, 2, 9], [3, 6, 0], [0, 6, 3]]) >>> y = np.array([[5, 3, 2], [9, 6, 0], [7, 3, 5]]) Perform Pearson's correlation pairwise on each row in 10x10 matrixes: >>> pr.stats.rowbased_pearson(x, y) array([-0.09078413, 0.65465367, -1. ])
rowbased_pearson
python
pyranges/pyranges
pyranges/statistics.py
https://github.com/pyranges/pyranges/blob/master/pyranges/statistics.py
MIT
def rowbased_rankdata(data): """Rank order of entries in each row. Same as SciPy rankdata with method=mean. Parameters ---------- data : matrix-like The data to find order of. Returns ------- Pandas.DataFrame DataFrame where values are order of data. Examples -------- >>> x = np.random.randint(10, size=(3, 4)) >>> x = np.array([[3, 7, 6, 0], [1, 3, 8, 9], [5, 9, 3, 5]]) >>> pr.stats.rowbased_rankdata(x) 0 1 2 3 0 2.0 4.0 3.0 1.0 1 1.0 2.0 3.0 4.0 2 2.5 4.0 1.0 2.5 """ dc = np.asarray(data).copy() sorter = np.apply_along_axis(np.argsort, 1, data) inv = np.empty(data.shape, np.intp) ranks = np.tile(np.arange(data.shape[1]), (len(data), 1)) np.put_along_axis(inv, sorter, ranks, axis=1) dc = np.take_along_axis(dc, sorter, 1) res = np.apply_along_axis(lambda r: r[1:] != r[:-1], 1, dc) obs = np.column_stack([np.ones(len(res), dtype=bool), res]) dense = np.take_along_axis(np.apply_along_axis(np.cumsum, 1, obs), inv, 1) len_r = obs.shape[1] nonzero = np.count_nonzero(obs, axis=1) obs = pd.DataFrame(obs) nonzero = pd.Series(nonzero) dense = pd.DataFrame(dense) ranks = [] for _nonzero, nzdf in obs.groupby(nonzero, sort=False, observed=False): nz = np.apply_along_axis(lambda r: np.nonzero(r)[0], 1, nzdf) _count = np.column_stack([nz, np.ones(len(nz)) * len_r]) _dense = dense.reindex(nzdf.index).values _result = 0.5 * (np.take_along_axis(_count, _dense, 1) + np.take_along_axis(_count, _dense - 1, 1) + 1) result = pd.DataFrame(_result, index=nzdf.index) ranks.append(result) final = pd.concat(ranks).sort_index(kind="mergesort") return final
Rank order of entries in each row. Same as SciPy rankdata with method=mean. Parameters ---------- data : matrix-like The data to find order of. Returns ------- Pandas.DataFrame DataFrame where values are order of data. Examples -------- >>> x = np.random.randint(10, size=(3, 4)) >>> x = np.array([[3, 7, 6, 0], [1, 3, 8, 9], [5, 9, 3, 5]]) >>> pr.stats.rowbased_rankdata(x) 0 1 2 3 0 2.0 4.0 3.0 1.0 1 1.0 2.0 3.0 4.0 2 2.5 4.0 1.0 2.5
rowbased_rankdata
python
pyranges/pyranges
pyranges/statistics.py
https://github.com/pyranges/pyranges/blob/master/pyranges/statistics.py
MIT
def simes(df, groupby, pcol, keep_position=False): """Apply Simes method for giving dependent events a p-value. Parameters ---------- df : pandas.DataFrame Data to analyse with Simes. groupby : str or list of str Features equal in these columns will be merged with Simes. pcol : str Name of column with p-values. keep_position : bool, default False Keep columns "Chromosome", "Start", "End" and "Strand" if they exist. See Also -------- pr.stats.fdr : correct for multiple testing Examples -------- >>> s = '''Chromosome Start End Strand Gene PValue ... 1 10 20 + P53 0.0001 ... 1 20 20 + P53 0.0002 ... 1 30 20 + P53 0.0003 ... 2 60 65 - FOX 0.05 ... 2 70 75 - FOX 0.0000001 ... 2 80 90 - FOX 0.0000021''' >>> gr = pr.from_string(s) >>> gr +--------------+-----------+-----------+--------------+------------+-------------+ | Chromosome | Start | End | Strand | Gene | PValue | | (category) | (int64) | (int64) | (category) | (object) | (float64) | |--------------+-----------+-----------+--------------+------------+-------------| | 1 | 10 | 20 | + | P53 | 0.0001 | | 1 | 20 | 20 | + | P53 | 0.0002 | | 1 | 30 | 20 | + | P53 | 0.0003 | | 2 | 60 | 65 | - | FOX | 0.05 | | 2 | 70 | 75 | - | FOX | 1e-07 | | 2 | 80 | 90 | - | FOX | 2.1e-06 | +--------------+-----------+-----------+--------------+------------+-------------+ Stranded PyRanges object has 6 rows and 6 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> simes = pr.stats.simes(gr.df, "Gene", "PValue") >>> simes Gene Simes 0 FOX 3.000000e-07 1 P53 3.000000e-04 >>> gr.apply(lambda df: ... pr.stats.simes(df, "Gene", "PValue", keep_position=True)) +--------------+-----------+-----------+-------------+--------------+------------+ | Chromosome | Start | End | Simes | Strand | Gene | | (category) | (int64) | (int64) | (float64) | (category) | (object) | |--------------+-----------+-----------+-------------+--------------+------------| | 1 | 10 | 20 | 0.0001 | + | P53 | | 2 | 60 | 90 | 1e-07 | - | FOX | +--------------+-----------+-----------+-------------+--------------+------------+ Stranded PyRanges object has 2 rows and 6 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ if isinstance(groupby, str): groupby = [groupby] positions = [] if "Strand" in df: stranded = True if keep_position: positions += ["Chromosome", "Start", "End"] if stranded: positions += ["Strand"] sorter = groupby + [pcol] sdf = df[positions + sorter].sort_values(sorter) g = sdf.groupby(positions + groupby, observed=False) ranks = g.cumcount().values + 1 size = g.size().values size = np.repeat(size, size) multiplied = sdf[pcol].values * size simes = multiplied / ranks sdf.insert(sdf.shape[1], "Simes", simes) if keep_position: grpby_dict = { "Chromosome": "first", "Start": "min", "End": "max", "Simes": "min", } if stranded: grpby_dict["Strand"] = "first" simes = sdf.groupby(groupby, observed=False).agg(grpby_dict).reset_index() columns = list(simes.columns) columns.append(columns[0]) del columns[0] simes = simes[columns] else: simes = sdf.groupby(groupby, observed=False).Simes.min().reset_index() return simes
Apply Simes method for giving dependent events a p-value. Parameters ---------- df : pandas.DataFrame Data to analyse with Simes. groupby : str or list of str Features equal in these columns will be merged with Simes. pcol : str Name of column with p-values. keep_position : bool, default False Keep columns "Chromosome", "Start", "End" and "Strand" if they exist. See Also -------- pr.stats.fdr : correct for multiple testing Examples -------- >>> s = '''Chromosome Start End Strand Gene PValue ... 1 10 20 + P53 0.0001 ... 1 20 20 + P53 0.0002 ... 1 30 20 + P53 0.0003 ... 2 60 65 - FOX 0.05 ... 2 70 75 - FOX 0.0000001 ... 2 80 90 - FOX 0.0000021''' >>> gr = pr.from_string(s) >>> gr +--------------+-----------+-----------+--------------+------------+-------------+ | Chromosome | Start | End | Strand | Gene | PValue | | (category) | (int64) | (int64) | (category) | (object) | (float64) | |--------------+-----------+-----------+--------------+------------+-------------| | 1 | 10 | 20 | + | P53 | 0.0001 | | 1 | 20 | 20 | + | P53 | 0.0002 | | 1 | 30 | 20 | + | P53 | 0.0003 | | 2 | 60 | 65 | - | FOX | 0.05 | | 2 | 70 | 75 | - | FOX | 1e-07 | | 2 | 80 | 90 | - | FOX | 2.1e-06 | +--------------+-----------+-----------+--------------+------------+-------------+ Stranded PyRanges object has 6 rows and 6 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> simes = pr.stats.simes(gr.df, "Gene", "PValue") >>> simes Gene Simes 0 FOX 3.000000e-07 1 P53 3.000000e-04 >>> gr.apply(lambda df: ... pr.stats.simes(df, "Gene", "PValue", keep_position=True)) +--------------+-----------+-----------+-------------+--------------+------------+ | Chromosome | Start | End | Simes | Strand | Gene | | (category) | (int64) | (int64) | (float64) | (category) | (object) | |--------------+-----------+-----------+-------------+--------------+------------| | 1 | 10 | 20 | 0.0001 | + | P53 | | 2 | 60 | 90 | 1e-07 | - | FOX | +--------------+-----------+-----------+-------------+--------------+------------+ Stranded PyRanges object has 2 rows and 6 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
simes
python
pyranges/pyranges
pyranges/statistics.py
https://github.com/pyranges/pyranges/blob/master/pyranges/statistics.py
MIT
def forbes(self, other, chromsizes, strandedness=None): """Compute Forbes coefficient. Ratio which represents observed versus expected co-occurence. Described in ``Forbes SA (1907): On the local distribution of certain Illinois fishes: an essay in statistical ecology.`` Parameters ---------- other : PyRanges Intervals to compare with. chromsizes : int, dict, DataFrame or PyRanges Integer representing genome length or mapping from chromosomes to its length. strandedness : {None, "same", "opposite", False}, default None, i.e. "auto" Whether to compute without regards to strand or on same or opposite. Returns ------- float Ratio of observed versus expected co-occurence. See Also -------- pyranges.statistics.jaccard : compute the jaccard coefficient Examples -------- >>> gr, gr2 = pr.data.chipseq(), pr.data.chipseq_background() >>> chromsizes = pr.data.chromsizes() >>> gr.stats.forbes(gr2, chromsizes=chromsizes) 1.7168314674978278""" chromsizes = chromsizes_as_int(chromsizes) self = self.pr kwargs = {} kwargs["sparse"] = {"self": True, "other": True} kwargs = pr.pyranges_main.fill_kwargs(kwargs) strand = True if kwargs.get("strandedness") else False reference_length = self.merge(strand=strand).length query_length = other.merge(strand=strand).length intersection_sum = sum( v.sum() for v in self.set_intersect(other, strandedness=strandedness).lengths(as_dict=True).values() ) forbes = chromsizes * intersection_sum / (reference_length * query_length) return forbes
Compute Forbes coefficient. Ratio which represents observed versus expected co-occurence. Described in ``Forbes SA (1907): On the local distribution of certain Illinois fishes: an essay in statistical ecology.`` Parameters ---------- other : PyRanges Intervals to compare with. chromsizes : int, dict, DataFrame or PyRanges Integer representing genome length or mapping from chromosomes to its length. strandedness : {None, "same", "opposite", False}, default None, i.e. "auto" Whether to compute without regards to strand or on same or opposite. Returns ------- float Ratio of observed versus expected co-occurence. See Also -------- pyranges.statistics.jaccard : compute the jaccard coefficient Examples -------- >>> gr, gr2 = pr.data.chipseq(), pr.data.chipseq_background() >>> chromsizes = pr.data.chromsizes() >>> gr.stats.forbes(gr2, chromsizes=chromsizes) 1.7168314674978278
forbes
python
pyranges/pyranges
pyranges/statistics.py
https://github.com/pyranges/pyranges/blob/master/pyranges/statistics.py
MIT
def jaccard(self, other, **kwargs): """Compute Jaccards coefficient. Ratio of the intersection and union of two sets. Parameters ---------- other : PyRanges Intervals to compare with. chromsizes : int, dict, DataFrame or PyRanges Integer representing genome length or mapping from chromosomes to its length. strandedness : {None, "same", "opposite", False}, default None, i.e. "auto" Whether to compute without regards to strand or on same or opposite. Returns ------- float Ratio of the intersection and union of two sets. See Also -------- pyranges.statistics.forbes : compute the forbes coefficient Examples -------- >>> gr, gr2 = pr.data.chipseq(), pr.data.chipseq_background() >>> chromsizes = pr.data.chromsizes() >>> gr.stats.jaccard(gr2, chromsizes=chromsizes) 6.657941988519211e-05""" self = self.pr kwargs["sparse"] = {"self": True, "other": True} kwargs = pr.pyranges_main.fill_kwargs(kwargs) strand = True if kwargs.get("strandedness") else False intersection_sum = sum(v.sum() for v in self.set_intersect(other).lengths(as_dict=True).values()) union_sum = 0 for gr in [self, other]: union_sum += sum(v.sum() for v in gr.merge(strand=strand).lengths(as_dict=True).values()) denominator = union_sum - intersection_sum if denominator == 0: return 1 else: jc = intersection_sum / denominator return jc
Compute Jaccards coefficient. Ratio of the intersection and union of two sets. Parameters ---------- other : PyRanges Intervals to compare with. chromsizes : int, dict, DataFrame or PyRanges Integer representing genome length or mapping from chromosomes to its length. strandedness : {None, "same", "opposite", False}, default None, i.e. "auto" Whether to compute without regards to strand or on same or opposite. Returns ------- float Ratio of the intersection and union of two sets. See Also -------- pyranges.statistics.forbes : compute the forbes coefficient Examples -------- >>> gr, gr2 = pr.data.chipseq(), pr.data.chipseq_background() >>> chromsizes = pr.data.chromsizes() >>> gr.stats.jaccard(gr2, chromsizes=chromsizes) 6.657941988519211e-05
jaccard
python
pyranges/pyranges
pyranges/statistics.py
https://github.com/pyranges/pyranges/blob/master/pyranges/statistics.py
MIT
def relative_distance(self, other, **kwargs): """Compute spatial correllation between two sets. Metric which describes relative distance between each interval in one set and two closest intervals in another. Parameters ---------- other : PyRanges Intervals to compare with. chromsizes : int, dict, DataFrame or PyRanges Integer representing genome length or mapping from chromosomes to its length. strandedness : {None, "same", "opposite", False}, default None, i.e. "auto" Whether to compute without regards to strand or on same or opposite. Returns ------- pandas.DataFrame DataFrame containing the frequency of each relative distance. See Also -------- pyranges.statistics.jaccard : compute the jaccard coefficient pyranges.statistics.forbes : compute the forbes coefficient Examples -------- >>> gr, gr2 = pr.data.chipseq(), pr.data.chipseq_background() >>> chromsizes = pr.data.chromsizes() >>> gr.stats.relative_distance(gr2) reldist count total fraction 0 0.00 264 9956 0.026517 1 0.01 226 9956 0.022700 2 0.02 206 9956 0.020691 3 0.03 235 9956 0.023604 4 0.04 194 9956 0.019486 5 0.05 241 9956 0.024207 6 0.06 201 9956 0.020189 7 0.07 191 9956 0.019184 8 0.08 192 9956 0.019285 9 0.09 191 9956 0.019184 10 0.10 186 9956 0.018682 11 0.11 203 9956 0.020390 12 0.12 218 9956 0.021896 13 0.13 209 9956 0.020992 14 0.14 201 9956 0.020189 15 0.15 178 9956 0.017879 16 0.16 202 9956 0.020289 17 0.17 197 9956 0.019787 18 0.18 208 9956 0.020892 19 0.19 202 9956 0.020289 20 0.20 191 9956 0.019184 21 0.21 188 9956 0.018883 22 0.22 213 9956 0.021394 23 0.23 192 9956 0.019285 24 0.24 199 9956 0.019988 25 0.25 181 9956 0.018180 26 0.26 172 9956 0.017276 27 0.27 191 9956 0.019184 28 0.28 190 9956 0.019084 29 0.29 192 9956 0.019285 30 0.30 201 9956 0.020189 31 0.31 212 9956 0.021294 32 0.32 213 9956 0.021394 33 0.33 177 9956 0.017778 34 0.34 197 9956 0.019787 35 0.35 163 9956 0.016372 36 0.36 191 9956 0.019184 37 0.37 198 9956 0.019888 38 0.38 160 9956 0.016071 39 0.39 188 9956 0.018883 40 0.40 200 9956 0.020088 41 0.41 188 9956 0.018883 42 0.42 230 9956 0.023102 43 0.43 197 9956 0.019787 44 0.44 224 9956 0.022499 45 0.45 184 9956 0.018481 46 0.46 198 9956 0.019888 47 0.47 187 9956 0.018783 48 0.48 200 9956 0.020088 49 0.49 194 9956 0.019486 """ self = self.pr kwargs["sparse"] = {"self": True, "other": True} kwargs = pr.pyranges_main.fill_kwargs(kwargs) result = pyrange_apply(_relative_distance, self, other, **kwargs) # pylint: disable=E1132 result = pd.Series(np.concatenate(list(result.values()))) not_nan = ~np.isnan(result) result.loc[not_nan] = np.floor(result[not_nan] * 100) / 100 vc = result.value_counts(dropna=False).to_frame().reset_index() vc.columns = "reldist count".split() vc.insert(vc.shape[1], "total", len(result)) vc.insert(vc.shape[1], "fraction", vc["count"] / len(result)) vc = vc.sort_values("reldist", ascending=True) vc = vc.reset_index(drop=True) return vc
Compute spatial correllation between two sets. Metric which describes relative distance between each interval in one set and two closest intervals in another. Parameters ---------- other : PyRanges Intervals to compare with. chromsizes : int, dict, DataFrame or PyRanges Integer representing genome length or mapping from chromosomes to its length. strandedness : {None, "same", "opposite", False}, default None, i.e. "auto" Whether to compute without regards to strand or on same or opposite. Returns ------- pandas.DataFrame DataFrame containing the frequency of each relative distance. See Also -------- pyranges.statistics.jaccard : compute the jaccard coefficient pyranges.statistics.forbes : compute the forbes coefficient Examples -------- >>> gr, gr2 = pr.data.chipseq(), pr.data.chipseq_background() >>> chromsizes = pr.data.chromsizes() >>> gr.stats.relative_distance(gr2) reldist count total fraction 0 0.00 264 9956 0.026517 1 0.01 226 9956 0.022700 2 0.02 206 9956 0.020691 3 0.03 235 9956 0.023604 4 0.04 194 9956 0.019486 5 0.05 241 9956 0.024207 6 0.06 201 9956 0.020189 7 0.07 191 9956 0.019184 8 0.08 192 9956 0.019285 9 0.09 191 9956 0.019184 10 0.10 186 9956 0.018682 11 0.11 203 9956 0.020390 12 0.12 218 9956 0.021896 13 0.13 209 9956 0.020992 14 0.14 201 9956 0.020189 15 0.15 178 9956 0.017879 16 0.16 202 9956 0.020289 17 0.17 197 9956 0.019787 18 0.18 208 9956 0.020892 19 0.19 202 9956 0.020289 20 0.20 191 9956 0.019184 21 0.21 188 9956 0.018883 22 0.22 213 9956 0.021394 23 0.23 192 9956 0.019285 24 0.24 199 9956 0.019988 25 0.25 181 9956 0.018180 26 0.26 172 9956 0.017276 27 0.27 191 9956 0.019184 28 0.28 190 9956 0.019084 29 0.29 192 9956 0.019285 30 0.30 201 9956 0.020189 31 0.31 212 9956 0.021294 32 0.32 213 9956 0.021394 33 0.33 177 9956 0.017778 34 0.34 197 9956 0.019787 35 0.35 163 9956 0.016372 36 0.36 191 9956 0.019184 37 0.37 198 9956 0.019888 38 0.38 160 9956 0.016071 39 0.39 188 9956 0.018883 40 0.40 200 9956 0.020088 41 0.41 188 9956 0.018883 42 0.42 230 9956 0.023102 43 0.43 197 9956 0.019787 44 0.44 224 9956 0.022499 45 0.45 184 9956 0.018481 46 0.46 198 9956 0.019888 47 0.47 187 9956 0.018783 48 0.48 200 9956 0.020088 49 0.49 194 9956 0.019486
relative_distance
python
pyranges/pyranges
pyranges/statistics.py
https://github.com/pyranges/pyranges/blob/master/pyranges/statistics.py
MIT
def from_string(s, int64=False): """Create a PyRanges from multiline string. Parameters ---------- s : str String with data. int64 : bool, default False. Whether to use 64-bit integers for starts and ends. See Also -------- pyranges.from_dict : create a PyRanges from a dictionary. Examples -------- >>> s = '''Chromosome Start End Strand ... chr1 246719402 246719502 + ... chr5 15400908 15401008 + ... chr9 68366534 68366634 + ... chr14 79220091 79220191 + ... chr14 103456471 103456571 -''' >>> pr.from_string(s) +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 246719402 | 246719502 | + | | chr5 | 15400908 | 15401008 | + | | chr9 | 68366534 | 68366634 | + | | chr14 | 79220091 | 79220191 | + | | chr14 | 103456471 | 103456571 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 5 rows and 4 columns from 4 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. """ from io import StringIO df = pd.read_csv(StringIO(s), sep=r"\s+", index_col=None) return PyRanges(df, int64=int64)
Create a PyRanges from multiline string. Parameters ---------- s : str String with data. int64 : bool, default False. Whether to use 64-bit integers for starts and ends. See Also -------- pyranges.from_dict : create a PyRanges from a dictionary. Examples -------- >>> s = '''Chromosome Start End Strand ... chr1 246719402 246719502 + ... chr5 15400908 15401008 + ... chr9 68366534 68366634 + ... chr14 79220091 79220191 + ... chr14 103456471 103456571 -''' >>> pr.from_string(s) +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | chr1 | 246719402 | 246719502 | + | | chr5 | 15400908 | 15401008 | + | | chr9 | 68366534 | 68366634 | + | | chr14 | 79220091 | 79220191 | + | | chr14 | 103456471 | 103456571 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 5 rows and 4 columns from 4 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand.
from_string
python
pyranges/pyranges
pyranges/__init__.py
https://github.com/pyranges/pyranges/blob/master/pyranges/__init__.py
MIT
def itergrs(prs, strand=None, keys=False): r"""Iterate over multiple PyRanges at once. Parameters ---------- prs : list of PyRanges PyRanges to iterate over. strand : bool, default None, i.e. auto Whether to iterate over strands. If True, all PyRanges must be stranded. keys : bool, default False Return tuple with key and value from iterator. Examples -------- >>> d1 = {"Chromosome": [1, 1, 2], "Start": [1, 2, 3], "End": [4, 9, 12], "Strand": ["+", "+", "-"]} >>> d2 = {"Chromosome": [2, 3, 3], "Start": [5, 9, 21], "End": [81, 42, 25], "Strand": ["-", "+", "-"]} >>> gr1, gr2 = pr.from_dict(d1), pr.from_dict(d2) >>> gr1 +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | 1 | 1 | 4 | + | | 1 | 2 | 9 | + | | 2 | 3 | 12 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 3 rows and 4 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr2 +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | 2 | 5 | 81 | - | | 3 | 9 | 42 | + | | 3 | 21 | 25 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 3 rows and 4 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> ranges = [gr1, gr2] >>> for key, dfs in pr.itergrs(ranges, keys=True): ... print("-----------\n" + str(key) + "\n-----------") ... for df in dfs: ... print(df) ----------- ('1', '+') ----------- Chromosome Start End Strand 0 1 1 4 + 1 1 2 9 + Empty DataFrame Columns: [Chromosome, Start, End, Strand] Index: [] ----------- ('2', '-') ----------- Chromosome Start End Strand 2 2 3 12 - Chromosome Start End Strand 0 2 5 81 - ----------- ('3', '+') ----------- Empty DataFrame Columns: [Chromosome, Start, End, Strand] Index: [] Chromosome Start End Strand 1 3 9 42 + ----------- ('3', '-') ----------- Empty DataFrame Columns: [Chromosome, Start, End, Strand] Index: [] Chromosome Start End Strand 2 3 21 25 - """ if strand is None: strand = all([gr.stranded for gr in prs]) if strand is False and any([gr.stranded for gr in prs]): prs = [gr.unstrand() for gr in prs] grs_per_chromosome = defaultdict(list) set_keys = set() for gr in prs: set_keys.update(gr.dfs.keys()) empty_dfs = [pd.DataFrame(columns=gr.columns) for gr in prs] for gr, empty in zip(prs, empty_dfs): for k in set_keys: df = gr.dfs.get(k, empty) grs_per_chromosome[k].append(df) if not keys: return iter(grs_per_chromosome.values()) else: return iter(natsorted(grs_per_chromosome.items()))
Iterate over multiple PyRanges at once. Parameters ---------- prs : list of PyRanges PyRanges to iterate over. strand : bool, default None, i.e. auto Whether to iterate over strands. If True, all PyRanges must be stranded. keys : bool, default False Return tuple with key and value from iterator. Examples -------- >>> d1 = {"Chromosome": [1, 1, 2], "Start": [1, 2, 3], "End": [4, 9, 12], "Strand": ["+", "+", "-"]} >>> d2 = {"Chromosome": [2, 3, 3], "Start": [5, 9, 21], "End": [81, 42, 25], "Strand": ["-", "+", "-"]} >>> gr1, gr2 = pr.from_dict(d1), pr.from_dict(d2) >>> gr1 +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | 1 | 1 | 4 | + | | 1 | 2 | 9 | + | | 2 | 3 | 12 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 3 rows and 4 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> gr2 +--------------+-----------+-----------+--------------+ | Chromosome | Start | End | Strand | | (category) | (int64) | (int64) | (category) | |--------------+-----------+-----------+--------------| | 2 | 5 | 81 | - | | 3 | 9 | 42 | + | | 3 | 21 | 25 | - | +--------------+-----------+-----------+--------------+ Stranded PyRanges object has 3 rows and 4 columns from 2 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> ranges = [gr1, gr2] >>> for key, dfs in pr.itergrs(ranges, keys=True): ... print("-----------\n" + str(key) + "\n-----------") ... for df in dfs: ... print(df) ----------- ('1', '+') ----------- Chromosome Start End Strand 0 1 1 4 + 1 1 2 9 + Empty DataFrame Columns: [Chromosome, Start, End, Strand] Index: [] ----------- ('2', '-') ----------- Chromosome Start End Strand 2 2 3 12 - Chromosome Start End Strand 0 2 5 81 - ----------- ('3', '+') ----------- Empty DataFrame Columns: [Chromosome, Start, End, Strand] Index: [] Chromosome Start End Strand 1 3 9 42 + ----------- ('3', '-') ----------- Empty DataFrame Columns: [Chromosome, Start, End, Strand] Index: [] Chromosome Start End Strand 2 3 21 25 -
itergrs
python
pyranges/pyranges
pyranges/__init__.py
https://github.com/pyranges/pyranges/blob/master/pyranges/__init__.py
MIT
def random(n=1000, length=100, chromsizes=None, strand=True, int64=False, seed=None): """Return PyRanges with random intervals. Parameters ---------- n : int, default 1000 Number of intervals. length : int, default 100 Length of intervals. chromsizes : dict or DataFrame, default None, i.e. use "hg19" Draw intervals from within these bounds. strand : bool, default True Data should have strand. int64 : bool, default False Use int64 to represent Start and End. Examples -------- # >>> pr.random() # +--------------+-----------+-----------+--------------+ # | Chromosome | Start | End | Strand | # | (category) | (int64) | (int64) | (category) | # |--------------+-----------+-----------+--------------| # | chr1 | 216128004 | 216128104 | + | # | chr1 | 114387955 | 114388055 | + | # | chr1 | 67597551 | 67597651 | + | # | chr1 | 26306616 | 26306716 | + | # | ... | ... | ... | ... | # | chrY | 20811459 | 20811559 | - | # | chrY | 12221362 | 12221462 | - | # | chrY | 8578041 | 8578141 | - | # | chrY | 43259695 | 43259795 | - | # +--------------+-----------+-----------+--------------+ # Stranded PyRanges object has 1,000 rows and 4 columns from 24 chromosomes. # For printing, the PyRanges was sorted on Chromosome and Strand. To have random interval lengths: # >>> gr = pr.random(length=1) # >>> gr.End += np.random.randint(int(1e5), size=len(gr)) # >>> gr.Length = gr.lengths() # >>> gr # +--------------+-----------+-----------+--------------+-----------+ # | Chromosome | Start | End | Strand | Length | # | (category) | (int64) | (int64) | (category) | (int64) | # |--------------+-----------+-----------+--------------+-----------| # | chr1 | 203654331 | 203695380 | + | 41049 | # | chr1 | 46918271 | 46978908 | + | 60637 | # | chr1 | 97355021 | 97391587 | + | 36566 | # | chr1 | 57284999 | 57323542 | + | 38543 | # | ... | ... | ... | ... | ... | # | chrY | 31665821 | 31692660 | - | 26839 | # | chrY | 20236607 | 20253473 | - | 16866 | # | chrY | 33255377 | 33315933 | - | 60556 | # | chrY | 31182964 | 31205467 | - | 22503 | # +--------------+-----------+-----------+--------------+-----------+ # Stranded PyRanges object has 1,000 rows and 5 columns from 24 chromosomes. # For printing, the PyRanges was sorted on Chromosome and Strand. """ if chromsizes is None: chromsizes = data.chromsizes() df = chromsizes.df elif isinstance(chromsizes, dict): df = pd.DataFrame({"Chromosome": list(chromsizes.keys()), "End": list(chromsizes.values())}) else: df = chromsizes.df p = df.End / df.End.sum() n_per_chrom = pd.Series(np.random.choice(df.index, size=n, p=p)).value_counts(sort=False).to_frame() n_per_chrom.insert(1, "Chromosome", df.loc[n_per_chrom.index].Chromosome) n_per_chrom.columns = "Count Chromosome".split() random_dfs = [] for _, (count, chrom) in n_per_chrom.iterrows(): r = np.random.randint(0, df[df.Chromosome == chrom].End - length, size=count) _df = pd.DataFrame({"Chromosome": chrom, "Start": r, "End": r + length}) random_dfs.append(_df) random_df = pd.concat(random_dfs) if strand: s = np.random.choice("+ -".split(), size=n) random_df.insert(3, "Strand", s) return PyRanges(random_df, int64=int64)
Return PyRanges with random intervals. Parameters ---------- n : int, default 1000 Number of intervals. length : int, default 100 Length of intervals. chromsizes : dict or DataFrame, default None, i.e. use "hg19" Draw intervals from within these bounds. strand : bool, default True Data should have strand. int64 : bool, default False Use int64 to represent Start and End. Examples -------- # >>> pr.random() # +--------------+-----------+-----------+--------------+ # | Chromosome | Start | End | Strand | # | (category) | (int64) | (int64) | (category) | # |--------------+-----------+-----------+--------------| # | chr1 | 216128004 | 216128104 | + | # | chr1 | 114387955 | 114388055 | + | # | chr1 | 67597551 | 67597651 | + | # | chr1 | 26306616 | 26306716 | + | # | ... | ... | ... | ... | # | chrY | 20811459 | 20811559 | - | # | chrY | 12221362 | 12221462 | - | # | chrY | 8578041 | 8578141 | - | # | chrY | 43259695 | 43259795 | - | # +--------------+-----------+-----------+--------------+ # Stranded PyRanges object has 1,000 rows and 4 columns from 24 chromosomes. # For printing, the PyRanges was sorted on Chromosome and Strand. To have random interval lengths: # >>> gr = pr.random(length=1) # >>> gr.End += np.random.randint(int(1e5), size=len(gr)) # >>> gr.Length = gr.lengths() # >>> gr # +--------------+-----------+-----------+--------------+-----------+ # | Chromosome | Start | End | Strand | Length | # | (category) | (int64) | (int64) | (category) | (int64) | # |--------------+-----------+-----------+--------------+-----------| # | chr1 | 203654331 | 203695380 | + | 41049 | # | chr1 | 46918271 | 46978908 | + | 60637 | # | chr1 | 97355021 | 97391587 | + | 36566 | # | chr1 | 57284999 | 57323542 | + | 38543 | # | ... | ... | ... | ... | ... | # | chrY | 31665821 | 31692660 | - | 26839 | # | chrY | 20236607 | 20253473 | - | 16866 | # | chrY | 33255377 | 33315933 | - | 60556 | # | chrY | 31182964 | 31205467 | - | 22503 | # +--------------+-----------+-----------+--------------+-----------+ # Stranded PyRanges object has 1,000 rows and 5 columns from 24 chromosomes. # For printing, the PyRanges was sorted on Chromosome and Strand.
random
python
pyranges/pyranges
pyranges/__init__.py
https://github.com/pyranges/pyranges/blob/master/pyranges/__init__.py
MIT
def to_bigwig(gr, path, chromosome_sizes): """Write df to bigwig. Must contain the columns Chromosome, Start, End and Score. All others are ignored. Parameters ---------- path : str Where to write bigwig. chromosome_sizes : PyRanges or dict If dict: map of chromosome names to chromosome length. Examples -------- Extended example with how to prepare your data for writing bigwigs: >>> d = {'Chromosome': ['chr1', 'chr1', 'chr1'], 'Start': [1, 4, 6], ... 'End': [7, 8, 10], 'Strand': ['+', '-', '-'], ... 'Value': [10, 20, 30]} >>> import pyranges as pr >>> gr = pr.from_dict(d) >>> hg19 = pr.data.chromsizes() >>> print(hg19) +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 0 | 249250621 | | chr2 | 0 | 243199373 | | chr3 | 0 | 198022430 | | chr4 | 0 | 191154276 | | ... | ... | ... | | chr22 | 0 | 51304566 | | chrM | 0 | 16571 | | chrX | 0 | 155270560 | | chrY | 0 | 59373566 | +--------------+-----------+-----------+ Unstranded PyRanges object has 25 rows and 3 columns from 25 chromosomes. For printing, the PyRanges was sorted on Chromosome. Overlapping intervals are invalid in bigwigs: >>> to_bigwig(gr, "outpath.bw", hg19) Traceback (most recent call last): ... AssertionError: Can only write one strand at a time. Use an unstranded PyRanges or subset on strand first. >>> to_bigwig(gr["-"], "outpath.bw", hg19) Traceback (most recent call last): ... AssertionError: Intervals must not overlap. >>> gr +--------------+-----------+-----------+--------------+-----------+ | Chromosome | Start | End | Strand | Value | | (category) | (int64) | (int64) | (category) | (int64) | |--------------+-----------+-----------+--------------+-----------| | chr1 | 1 | 7 | + | 10 | | chr1 | 4 | 8 | - | 20 | | chr1 | 6 | 10 | - | 30 | +--------------+-----------+-----------+--------------+-----------+ Stranded PyRanges object has 3 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> value = gr.to_rle(rpm=False, value_col="Value") >>> value chr1 + -- +--------+-----+------+ | Runs | 1 | 6 | |--------+-----+------| | Values | 0.0 | 10.0 | +--------+-----+------+ Rle of length 7 containing 2 elements (avg. length 3.5) <BLANKLINE> chr1 - -- +--------+-----+------+------+------+ | Runs | 4 | 2 | 2 | 2 | |--------+-----+------+------+------| | Values | 0.0 | 20.0 | 50.0 | 30.0 | +--------+-----+------+------+------+ Rle of length 10 containing 4 elements (avg. length 2.5) RleDict object with 2 chromosomes/strand pairs. >>> raw = gr.to_rle(rpm=False) >>> raw chr1 + -- +--------+-----+-----+ | Runs | 1 | 6 | |--------+-----+-----| | Values | 0.0 | 1.0 | +--------+-----+-----+ Rle of length 7 containing 2 elements (avg. length 3.5) <BLANKLINE> chr1 - -- +--------+-----+-----+-----+-----+ | Runs | 4 | 2 | 2 | 2 | |--------+-----+-----+-----+-----| | Values | 0.0 | 1.0 | 2.0 | 1.0 | +--------+-----+-----+-----+-----+ Rle of length 10 containing 4 elements (avg. length 2.5) RleDict object with 2 chromosomes/strand pairs. >>> result = (value / raw).apply_values(np.log10) >>> result chr1 + -- +--------+-----+-----+ | Runs | 1 | 6 | |--------+-----+-----| | Values | nan | 1.0 | +--------+-----+-----+ Rle of length 7 containing 2 elements (avg. length 3.5) <BLANKLINE> chr1 - -- +--------+-----+--------------------+--------------------+--------------------+ | Runs | 4 | 2 | 2 | 2 | |--------+-----+--------------------+--------------------+--------------------| | Values | nan | 1.3010300397872925 | 1.3979400396347046 | 1.4771212339401245 | +--------+-----+--------------------+--------------------+--------------------+ Rle of length 10 containing 4 elements (avg. length 2.5) RleDict object with 2 chromosomes/strand pairs. >>> out = result.numbers_only().to_ranges() >>> out +--------------+-----------+-----------+-------------+--------------+ | Chromosome | Start | End | Score | Strand | | (category) | (int64) | (int64) | (float64) | (category) | |--------------+-----------+-----------+-------------+--------------| | chr1 | 1 | 7 | 1 | + | | chr1 | 4 | 6 | 1.30103 | - | | chr1 | 6 | 8 | 1.39794 | - | | chr1 | 8 | 10 | 1.47712 | - | +--------------+-----------+-----------+-------------+--------------+ Stranded PyRanges object has 4 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> to_bigwig(out["-"], "deleteme_reverse.bw", hg19) >>> to_bigwig(out["+"], "deleteme_forward.bw", hg19) """ try: import pyBigWig # type: ignore except ModuleNotFoundError: print( "pybigwig must be installed to create bigwigs. Use `conda install -c bioconda pybigwig` or `pip install pybigwig` to install it." ) import sys sys.exit(1) assert ( len(gr.strands) <= 1 ), "Can only write one strand at a time. Use an unstranded PyRanges or subset on strand first." assert np.sum(gr.lengths()) == gr.merge().length, "Intervals must not overlap." df = gr.df unique_chromosomes = list(df.Chromosome.drop_duplicates()) if not isinstance(chromosome_sizes, dict): size_df = chromosome_sizes.df chromosome_sizes = {k: v for k, v in zip(size_df.Chromosome, size_df.End)} header = [(c, int(chromosome_sizes[c])) for c in unique_chromosomes] bw = pyBigWig.open(path, "w") bw.addHeader(header) chromosomes = df.Chromosome.tolist() starts = df.Start.tolist() ends = df.End.tolist() values = df.Score.tolist() bw.addEntries(chromosomes, starts, ends=ends, values=values)
Write df to bigwig. Must contain the columns Chromosome, Start, End and Score. All others are ignored. Parameters ---------- path : str Where to write bigwig. chromosome_sizes : PyRanges or dict If dict: map of chromosome names to chromosome length. Examples -------- Extended example with how to prepare your data for writing bigwigs: >>> d = {'Chromosome': ['chr1', 'chr1', 'chr1'], 'Start': [1, 4, 6], ... 'End': [7, 8, 10], 'Strand': ['+', '-', '-'], ... 'Value': [10, 20, 30]} >>> import pyranges as pr >>> gr = pr.from_dict(d) >>> hg19 = pr.data.chromsizes() >>> print(hg19) +--------------+-----------+-----------+ | Chromosome | Start | End | | (category) | (int64) | (int64) | |--------------+-----------+-----------| | chr1 | 0 | 249250621 | | chr2 | 0 | 243199373 | | chr3 | 0 | 198022430 | | chr4 | 0 | 191154276 | | ... | ... | ... | | chr22 | 0 | 51304566 | | chrM | 0 | 16571 | | chrX | 0 | 155270560 | | chrY | 0 | 59373566 | +--------------+-----------+-----------+ Unstranded PyRanges object has 25 rows and 3 columns from 25 chromosomes. For printing, the PyRanges was sorted on Chromosome. Overlapping intervals are invalid in bigwigs: >>> to_bigwig(gr, "outpath.bw", hg19) Traceback (most recent call last): ... AssertionError: Can only write one strand at a time. Use an unstranded PyRanges or subset on strand first. >>> to_bigwig(gr["-"], "outpath.bw", hg19) Traceback (most recent call last): ... AssertionError: Intervals must not overlap. >>> gr +--------------+-----------+-----------+--------------+-----------+ | Chromosome | Start | End | Strand | Value | | (category) | (int64) | (int64) | (category) | (int64) | |--------------+-----------+-----------+--------------+-----------| | chr1 | 1 | 7 | + | 10 | | chr1 | 4 | 8 | - | 20 | | chr1 | 6 | 10 | - | 30 | +--------------+-----------+-----------+--------------+-----------+ Stranded PyRanges object has 3 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> value = gr.to_rle(rpm=False, value_col="Value") >>> value chr1 + -- +--------+-----+------+ | Runs | 1 | 6 | |--------+-----+------| | Values | 0.0 | 10.0 | +--------+-----+------+ Rle of length 7 containing 2 elements (avg. length 3.5) <BLANKLINE> chr1 - -- +--------+-----+------+------+------+ | Runs | 4 | 2 | 2 | 2 | |--------+-----+------+------+------| | Values | 0.0 | 20.0 | 50.0 | 30.0 | +--------+-----+------+------+------+ Rle of length 10 containing 4 elements (avg. length 2.5) RleDict object with 2 chromosomes/strand pairs. >>> raw = gr.to_rle(rpm=False) >>> raw chr1 + -- +--------+-----+-----+ | Runs | 1 | 6 | |--------+-----+-----| | Values | 0.0 | 1.0 | +--------+-----+-----+ Rle of length 7 containing 2 elements (avg. length 3.5) <BLANKLINE> chr1 - -- +--------+-----+-----+-----+-----+ | Runs | 4 | 2 | 2 | 2 | |--------+-----+-----+-----+-----| | Values | 0.0 | 1.0 | 2.0 | 1.0 | +--------+-----+-----+-----+-----+ Rle of length 10 containing 4 elements (avg. length 2.5) RleDict object with 2 chromosomes/strand pairs. >>> result = (value / raw).apply_values(np.log10) >>> result chr1 + -- +--------+-----+-----+ | Runs | 1 | 6 | |--------+-----+-----| | Values | nan | 1.0 | +--------+-----+-----+ Rle of length 7 containing 2 elements (avg. length 3.5) <BLANKLINE> chr1 - -- +--------+-----+--------------------+--------------------+--------------------+ | Runs | 4 | 2 | 2 | 2 | |--------+-----+--------------------+--------------------+--------------------| | Values | nan | 1.3010300397872925 | 1.3979400396347046 | 1.4771212339401245 | +--------+-----+--------------------+--------------------+--------------------+ Rle of length 10 containing 4 elements (avg. length 2.5) RleDict object with 2 chromosomes/strand pairs. >>> out = result.numbers_only().to_ranges() >>> out +--------------+-----------+-----------+-------------+--------------+ | Chromosome | Start | End | Score | Strand | | (category) | (int64) | (int64) | (float64) | (category) | |--------------+-----------+-----------+-------------+--------------| | chr1 | 1 | 7 | 1 | + | | chr1 | 4 | 6 | 1.30103 | - | | chr1 | 6 | 8 | 1.39794 | - | | chr1 | 8 | 10 | 1.47712 | - | +--------------+-----------+-----------+-------------+--------------+ Stranded PyRanges object has 4 rows and 5 columns from 1 chromosomes. For printing, the PyRanges was sorted on Chromosome and Strand. >>> to_bigwig(out["-"], "deleteme_reverse.bw", hg19) >>> to_bigwig(out["+"], "deleteme_forward.bw", hg19)
to_bigwig
python
pyranges/pyranges
pyranges/__init__.py
https://github.com/pyranges/pyranges/blob/master/pyranges/__init__.py
MIT
def _handle_eval_return(self, result, col, as_pyranges, subset): """Handle return from eval. If col is set, add/update cols. If subset is True, use return series to subset PyRanges. Otherwise return PyRanges or dict of data.""" if as_pyranges: if not result: return pr.PyRanges() first_hit = list(result.values())[0] if isinstance(first_hit, pd.Series): if first_hit.dtype == bool and subset: return self[result] elif col: self.__setattr__(col, result) return self else: raise Exception("Cannot return PyRanges when function returns a Series! Use as_pyranges=False.") return pr.PyRanges(result) else: return result
Handle return from eval. If col is set, add/update cols. If subset is True, use return series to subset PyRanges. Otherwise return PyRanges or dict of data.
_handle_eval_return
python
pyranges/pyranges
pyranges/methods/call.py
https://github.com/pyranges/pyranges/blob/master/pyranges/methods/call.py
MIT
def sort_one_by_one(d, col1, col2): """ Equivalent to pd.sort_values(by=[col1, col2]), but faster. """ d = d.sort_values(by=[col2]) return d.sort_values(by=[col1], kind="mergesort")
Equivalent to pd.sort_values(by=[col1, col2]), but faster.
sort_one_by_one
python
pyranges/pyranges
pyranges/methods/sort.py
https://github.com/pyranges/pyranges/blob/master/pyranges/methods/sort.py
MIT
def _introns_correct(full, genes, exons, introns, by): """Testing that introns: 1: ends larger than starts 2: the intersection of the computed introns and exons per gene are 0 3: that the number of introns overlapping each gene is the same as number of introns per gene 4 & 5: that the intron positions are the same as the ones computed with the slow, but correct algo """ id_column = by_to_id[by] if len(introns): assert (introns.Start < introns.End).all(), str(introns[(introns.Start >= introns.End)]) expected_results = {} based_on = {} for gene_id, gdf in full.groupby(id_column): # #[full.gene_id.isin(["ENSG00000078808.16"])] # print("gdf " * 10) # print(gdf) if not len(gdf[gdf.Feature == "gene"]) or not len(gdf[gdf.Feature == "transcript"]): continue expected_results[gene_id] = compute_introns_single(gdf, by) based_on[gene_id] = pr.PyRanges(gdf[gdf.Feature.isin([by, "exon"])]).df if not len(introns): for v in expected_results.values(): assert v.empty return # test passed for gene_id, idf in introns.groupby(id_column): idf = idf.sort_values("Start End".split()) if gene_id not in expected_results: continue expected = expected_results[gene_id] exons = pr.PyRanges(based_on[gene_id]).subset(lambda df: df.Feature == "exon").merge(by=id_column) genes = pr.PyRanges(based_on[gene_id]).subset(lambda df: df.Feature == by) print("exons", exons) print("based_on", based_on[gene_id]) print("actual", idf["Chromosome Start End Strand".split()]) print("expected", expected["Chromosome Start End Strand".split()]) _introns = pr.PyRanges(idf) assert len(exons.intersect(_introns)) == 0 assert len(genes.intersect(_introns)) == len(_introns) assert list(idf.Start) == list(expected.Start), "not equal" assert list(idf.End) == list(expected.End), "not equal"
Testing that introns: 1: ends larger than starts 2: the intersection of the computed introns and exons per gene are 0 3: that the number of introns overlapping each gene is the same as number of introns per gene 4 & 5: that the intron positions are the same as the ones computed with the slow, but correct algo
_introns_correct
python
pyranges/pyranges
tests/unit/test_genomicfeatures.py
https://github.com/pyranges/pyranges/blob/master/tests/unit/test_genomicfeatures.py
MIT
def test_introns_single(): "Assert that our fast method of computing introns is the same as the slow, correct one in compute_introns_single" gr = pr.data.gencode_gtf()[["gene_id", "Feature"]] exons = gr[gr.Feature == "exon"].merge(by="gene_id") exons.Feature = "exon" exons = exons.df df = pd.concat([gr[gr.Feature == "gene"].df, exons], sort=False) print(df) for gid, gdf in df.groupby("gene_id"): print("-------" * 20) print(gid) print(gdf) print("gdf", len(gdf)) expected = compute_introns_single(gdf, by="gene") print("expected", len(expected)) actual = pr.PyRanges(gdf).features.introns().df print("actual", len(actual)) if actual.empty: assert expected.empty continue assert list(expected.Start) == list(actual.Start) assert list(expected.End) == list(actual.End)
Assert that our fast method of computing introns is the same as the slow, correct one in compute_introns_single
test_introns_single
python
pyranges/pyranges
tests/unit/test_genomicfeatures.py
https://github.com/pyranges/pyranges/blob/master/tests/unit/test_genomicfeatures.py
MIT
def makecube(): """ Generate vertices & indices for a filled cube """ vtype = [('a_position', np.float32, 3), ('a_texcoord', np.float32, 2)] itype = np.uint32 # Vertices positions p = np.array([[1, 1, 1], [-1, 1, 1], [-1, -1, 1], [1, -1, 1], [1, -1, -1], [1, 1, -1], [-1, 1, -1], [-1, -1, -1]]) # Texture coords t = np.array([[0, 0], [0, 1], [1, 1], [1, 0]]) faces_p = [0, 1, 2, 3, 0, 3, 4, 5, 0, 5, 6, 1, 1, 6, 7, 2, 7, 4, 3, 2, 4, 7, 6, 5] faces_t = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3] vertices = np.zeros(24, vtype) vertices['a_position'] = p[faces_p] vertices['a_texcoord'] = t[faces_t] indices = np.resize( np.array([0, 1, 2, 0, 2, 3], dtype=itype), 6 * (2 * 3)) indices += np.repeat(4 * np.arange(6), 6).astype(np.uint32) return vertices, indices
Generate vertices & indices for a filled cube
makecube
python
timctho/VNect-tensorflow
vispy_test.py
https://github.com/timctho/VNect-tensorflow/blob/master/vispy_test.py
Apache-2.0
def _create_base_cipher(dict_parameters): """This method instantiates and returns a handle to a low-level base cipher. It will absorb named parameters in the process.""" use_aesni = dict_parameters.pop("use_aesni", True) try: key = dict_parameters.pop("key") except KeyError: raise TypeError("Missing 'key' parameter") expect_byte_string(key) if len(key) not in key_size: raise ValueError("Incorrect AES key length (%d bytes)" % len(key)) if use_aesni and _raw_aesni_lib: start_operation = _raw_aesni_lib.AESNI_start_operation stop_operation = _raw_aesni_lib.AESNI_stop_operation else: start_operation = _raw_aes_lib.AES_start_operation stop_operation = _raw_aes_lib.AES_stop_operation cipher = VoidPointer() result = start_operation(key, c_size_t(len(key)), cipher.address_of()) if result: raise ValueError("Error %X while instantiating the AES cipher" % result) return SmartPointer(cipher.get(), stop_operation)
This method instantiates and returns a handle to a low-level base cipher. It will absorb named parameters in the process.
_create_base_cipher
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/AES.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/AES.py
MIT
def new(key, mode, *args, **kwargs): """Create a new AES cipher :Parameters: key : byte string The secret key to use in the symmetric cipher. It must be 16 (*AES-128*), 24 (*AES-192*), or 32 (*AES-256*) bytes long. Only in `MODE_SIV`, it needs to be 32, 48, or 64 bytes long. mode : a *MODE_** constant The chaining mode to use for encryption or decryption. If in doubt, use `MODE_EAX`. :Keywords: iv : byte string (*Only* `MODE_CBC`, `MODE_CFB`, `MODE_OFB`, `MODE_OPENPGP`). The initialization vector to use for encryption or decryption. For `MODE_OPENPGP`, it must be 16 bytes long for encryption and 18 bytes for decryption (in the latter case, it is actually the *encrypted* IV which was prefixed to the ciphertext). For all other modes, it must be 16 bytes long. In not provided, a random byte string is used (you must then read its value with the ``iv`` attribute). nonce : byte string (*Only* `MODE_CCM`, `MODE_EAX`, `MODE_GCM`, `MODE_SIV`, `MODE_OCB`, `MODE_CTR`). A value that must never be reused for any other encryption done with this key. For `MODE_CCM`, its length must be in the range ``[7..13]``. Bear in mind that with CCM there is a trade-off between nonce length and maximum message size. For `MODE_OCB`, its length must be in the range ``[1..15]``. For `MODE_CTR`, its length must be in the range ``[0..15]``. For the other modes, there are no restrictions on its length. The recommended length depends on the mode: 8 bytes for `MODE_CTR`, 11 bytes for `MODE_CCM`, 15 bytes for `MODE_OCB` and 16 bytes for the remaining modes. In not provided, a random byte string of the recommended length is used (you must then read its value with the ``nonce`` attribute). segment_size : integer (*Only* `MODE_CFB`).The number of **bits** the plaintext and ciphertext are segmented in. It must be a multiple of 8. If not specified, it will be assumed to be 8. mac_len : integer (*Only* `MODE_EAX`, `MODE_GCM`, `MODE_OCB`, `MODE_CCM`) Length of the authentication tag, in bytes. It must be even and in the range ``[4..16]``. The recommended value (and the default, if not specified) is 16. msg_len : integer (*Only* `MODE_CCM`). Length of the message to (de)cipher. If not specified, ``encrypt`` must be called with the entire message. Similarly, ``decrypt`` can only be called once. assoc_len : integer (*Only* `MODE_CCM`). Length of the associated data. If not specified, all associated data is buffered internally, which may represent a problem for very large messages. initial_value : integer (*Only* `MODE_CTR`). The initial value for the counter within the counter block. By default it is 0. use_aesni : boolean Use Intel AES-NI hardware extensions if available. :Return: an AES object, of the applicable mode: - CBC_ mode - CCM_ mode - CFB_ mode - CTR_ mode - EAX_ mode - ECB_ mode - GCM_ mode - OCB_ mode - OFB_ mode - OpenPgp_ mode - SIV_ mode .. _CBC: Cryptodome.Cipher._mode_cbc.CbcMode-class.html .. _CCM: Cryptodome.Cipher._mode_ccm.CcmMode-class.html .. _CFB: Cryptodome.Cipher._mode_cfb.CfbMode-class.html .. _CTR: Cryptodome.Cipher._mode_ctr.CtrMode-class.html .. _EAX: Cryptodome.Cipher._mode_eax.EaxMode-class.html .. _ECB: Cryptodome.Cipher._mode_ecb.EcbMode-class.html .. _GCM: Cryptodome.Cipher._mode_gcm.GcmMode-class.html .. _OCB: Cryptodome.Cipher._mode_ocb.OcbMode-class.html .. _OFB: Cryptodome.Cipher._mode_ofb.OfbMode-class.html .. _OpenPgp: Cryptodome.Cipher._mode_openpgp.OpenPgpMode-class.html .. _SIV: Cryptodome.Cipher._mode_siv.SivMode-class.html """ kwargs["add_aes_modes"] = True return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs)
Create a new AES cipher :Parameters: key : byte string The secret key to use in the symmetric cipher. It must be 16 (*AES-128*), 24 (*AES-192*), or 32 (*AES-256*) bytes long. Only in `MODE_SIV`, it needs to be 32, 48, or 64 bytes long. mode : a *MODE_** constant The chaining mode to use for encryption or decryption. If in doubt, use `MODE_EAX`. :Keywords: iv : byte string (*Only* `MODE_CBC`, `MODE_CFB`, `MODE_OFB`, `MODE_OPENPGP`). The initialization vector to use for encryption or decryption. For `MODE_OPENPGP`, it must be 16 bytes long for encryption and 18 bytes for decryption (in the latter case, it is actually the *encrypted* IV which was prefixed to the ciphertext). For all other modes, it must be 16 bytes long. In not provided, a random byte string is used (you must then read its value with the ``iv`` attribute). nonce : byte string (*Only* `MODE_CCM`, `MODE_EAX`, `MODE_GCM`, `MODE_SIV`, `MODE_OCB`, `MODE_CTR`). A value that must never be reused for any other encryption done with this key. For `MODE_CCM`, its length must be in the range ``[7..13]``. Bear in mind that with CCM there is a trade-off between nonce length and maximum message size. For `MODE_OCB`, its length must be in the range ``[1..15]``. For `MODE_CTR`, its length must be in the range ``[0..15]``. For the other modes, there are no restrictions on its length. The recommended length depends on the mode: 8 bytes for `MODE_CTR`, 11 bytes for `MODE_CCM`, 15 bytes for `MODE_OCB` and 16 bytes for the remaining modes. In not provided, a random byte string of the recommended length is used (you must then read its value with the ``nonce`` attribute). segment_size : integer (*Only* `MODE_CFB`).The number of **bits** the plaintext and ciphertext are segmented in. It must be a multiple of 8. If not specified, it will be assumed to be 8. mac_len : integer (*Only* `MODE_EAX`, `MODE_GCM`, `MODE_OCB`, `MODE_CCM`) Length of the authentication tag, in bytes. It must be even and in the range ``[4..16]``. The recommended value (and the default, if not specified) is 16. msg_len : integer (*Only* `MODE_CCM`). Length of the message to (de)cipher. If not specified, ``encrypt`` must be called with the entire message. Similarly, ``decrypt`` can only be called once. assoc_len : integer (*Only* `MODE_CCM`). Length of the associated data. If not specified, all associated data is buffered internally, which may represent a problem for very large messages. initial_value : integer (*Only* `MODE_CTR`). The initial value for the counter within the counter block. By default it is 0. use_aesni : boolean Use Intel AES-NI hardware extensions if available. :Return: an AES object, of the applicable mode: - CBC_ mode - CCM_ mode - CFB_ mode - CTR_ mode - EAX_ mode - ECB_ mode - GCM_ mode - OCB_ mode - OFB_ mode - OpenPgp_ mode - SIV_ mode .. _CBC: Cryptodome.Cipher._mode_cbc.CbcMode-class.html .. _CCM: Cryptodome.Cipher._mode_ccm.CcmMode-class.html .. _CFB: Cryptodome.Cipher._mode_cfb.CfbMode-class.html .. _CTR: Cryptodome.Cipher._mode_ctr.CtrMode-class.html .. _EAX: Cryptodome.Cipher._mode_eax.EaxMode-class.html .. _ECB: Cryptodome.Cipher._mode_ecb.EcbMode-class.html .. _GCM: Cryptodome.Cipher._mode_gcm.GcmMode-class.html .. _OCB: Cryptodome.Cipher._mode_ocb.OcbMode-class.html .. _OFB: Cryptodome.Cipher._mode_ofb.OfbMode-class.html .. _OpenPgp: Cryptodome.Cipher._mode_openpgp.OpenPgpMode-class.html .. _SIV: Cryptodome.Cipher._mode_siv.SivMode-class.html
new
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/AES.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/AES.py
MIT
def __init__(self, key, *args, **kwargs): """Initialize an ARC4 cipher object See also `new()` at the module level.""" if len(args) > 0: ndrop = args[0] args = args[1:] else: ndrop = kwargs.pop('drop', 0) if len(key) not in key_size: raise ValueError("Incorrect ARC4 key length (%d bytes)" % len(key)) expect_byte_string(key) self._state = VoidPointer() result = _raw_arc4_lib.ARC4_stream_init(key, c_size_t(len(key)), self._state.address_of()) if result != 0: raise ValueError("Error %d while creating the ARC4 cipher" % result) self._state = SmartPointer(self._state.get(), _raw_arc4_lib.ARC4_stream_destroy) if ndrop > 0: # This is OK even if the cipher is used for decryption, # since encrypt and decrypt are actually the same thing # with ARC4. self.encrypt(b('\x00') * ndrop) self.block_size = 1 self.key_size = len(key)
Initialize an ARC4 cipher object See also `new()` at the module level.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/ARC4.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/ARC4.py
MIT
def encrypt(self, plaintext): """Encrypt a piece of data. :Parameters: plaintext : byte string The piece of data to encrypt. It can be of any size. :Return: the encrypted data (byte string, as long as the plaintext). """ expect_byte_string(plaintext) ciphertext = create_string_buffer(len(plaintext)) result = _raw_arc4_lib.ARC4_stream_encrypt(self._state.get(), plaintext, ciphertext, c_size_t(len(plaintext))) if result: raise ValueError("Error %d while encrypting with RC4" % result) return get_raw_buffer(ciphertext)
Encrypt a piece of data. :Parameters: plaintext : byte string The piece of data to encrypt. It can be of any size. :Return: the encrypted data (byte string, as long as the plaintext).
encrypt
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/ARC4.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/ARC4.py
MIT
def decrypt(self, ciphertext): """Decrypt a piece of data. :Parameters: ciphertext : byte string The piece of data to decrypt. It can be of any size. :Return: the decrypted data (byte string, as long as the ciphertext). """ try: return self.encrypt(ciphertext) except ValueError, e: raise ValueError(str(e).replace("enc", "dec"))
Decrypt a piece of data. :Parameters: ciphertext : byte string The piece of data to decrypt. It can be of any size. :Return: the decrypted data (byte string, as long as the ciphertext).
decrypt
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/ARC4.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/ARC4.py
MIT
def _create_base_cipher(dict_parameters): """This method instantiates and returns a smart pointer to a low-level base cipher. It will absorb named parameters in the process.""" try: key = dict_parameters.pop("key") except KeyError: raise TypeError("Missing 'key' parameter") expect_byte_string(key) if len(key) not in key_size: raise ValueError("Incorrect Blowfish key length (%d bytes)" % len(key)) start_operation = _raw_blowfish_lib.Blowfish_start_operation stop_operation = _raw_blowfish_lib.Blowfish_stop_operation void_p = VoidPointer() result = start_operation(key, c_size_t(len(key)), void_p.address_of()) if result: raise ValueError("Error %X while instantiating the Blowfish cipher" % result) return SmartPointer(void_p.get(), stop_operation)
This method instantiates and returns a smart pointer to a low-level base cipher. It will absorb named parameters in the process.
_create_base_cipher
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/Blowfish.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/Blowfish.py
MIT
def __init__(self, key, nonce): """Initialize a ChaCha20 cipher object See also `new()` at the module level.""" expect_byte_string(key) expect_byte_string(nonce) self.nonce = nonce self._next = ( self.encrypt, self.decrypt ) self._state = VoidPointer() result = _raw_chacha20_lib.chacha20_init( self._state.address_of(), key, c_size_t(len(key)), nonce, c_size_t(len(nonce))) if result: raise ValueError("Error %d instantiating a ChaCha20 cipher") self._state = SmartPointer(self._state.get(), _raw_chacha20_lib.chacha20_destroy)
Initialize a ChaCha20 cipher object See also `new()` at the module level.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/ChaCha20.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/ChaCha20.py
MIT
def seek(self, position): """Seek at a certain position in the key stream. :Parameters: position : integer The absolute position within the key stream, in bytes. """ offset = position & 0x3f position >>= 6 block_low = position & 0xFFFFFFFF block_high = position >> 32 result = _raw_chacha20_lib.chacha20_seek( self._state.get(), c_ulong(block_high), c_ulong(block_low), offset ) if result: raise ValueError("Error %d while seeking with ChaCha20" % result)
Seek at a certain position in the key stream. :Parameters: position : integer The absolute position within the key stream, in bytes.
seek
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/ChaCha20.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/ChaCha20.py
MIT
def new(**kwargs): """Create a new ChaCha20 cipher :Keywords: key : byte string The secret key to use in the symmetric cipher. It must be 32 bytes long. nonce : byte string A mandatory value that must never be reused for any other encryption done with this key. It must be 8 bytes long. If not provided, a random byte string will be generated (you can read it back via the ``nonce`` attribute). :Return: a `ChaCha20Cipher` object """ try: key = kwargs.pop("key") except KeyError, e: raise TypeError("Missing parameter %s" % e) nonce = kwargs.pop("nonce", None) if nonce is None: nonce = get_random_bytes(8) if len(key) != 32: raise ValueError("ChaCha20 key must be 32 bytes long") if len(nonce) != 8: raise ValueError("ChaCha20 nonce must be 8 bytes long") if kwargs: raise TypeError("Unknown parameters: " + str(kwargs)) return ChaCha20Cipher(key, nonce)
Create a new ChaCha20 cipher :Keywords: key : byte string The secret key to use in the symmetric cipher. It must be 32 bytes long. nonce : byte string A mandatory value that must never be reused for any other encryption done with this key. It must be 8 bytes long. If not provided, a random byte string will be generated (you can read it back via the ``nonce`` attribute). :Return: a `ChaCha20Cipher` object
new
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/ChaCha20.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/ChaCha20.py
MIT
def adjust_key_parity(key_in): """Return the TDES key with parity bits correctly set""" def parity_byte(key_byte): parity = 1 for i in xrange(1, 8): parity ^= (key_byte >> i) & 1 return (key_byte & 0xFE) | parity if len(key_in) not in key_size: raise ValueError("Not a valid TDES key") key_out = b("").join([ bchr(parity_byte(bord(x)) )for x in key_in ]) if key_out[:8] == key_out[8:16] or key_out[-16:-8] == key_out[-8:]: raise ValueError("Triple DES key degenerates to single DES") return key_out
Return the TDES key with parity bits correctly set
adjust_key_parity
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/DES3.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/DES3.py
MIT
def _create_base_cipher(dict_parameters): """This method instantiates and returns a handle to a low-level base cipher. It will absorb named parameters in the process.""" try: key_in = dict_parameters.pop("key") except KeyError: raise TypeError("Missing 'key' parameter") key = adjust_key_parity(key_in) start_operation = _raw_des3_lib.DES3_start_operation stop_operation = _raw_des3_lib.DES3_stop_operation cipher = VoidPointer() result = start_operation(key, c_size_t(len(key)), cipher.address_of()) if result: raise ValueError("Error %X while instantiating the TDES cipher" % result) return SmartPointer(cipher.get(), stop_operation)
This method instantiates and returns a handle to a low-level base cipher. It will absorb named parameters in the process.
_create_base_cipher
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/DES3.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/DES3.py
MIT
def __init__(self, key, hashAlgo, mgfunc, label, randfunc): """Initialize this PKCS#1 OAEP cipher object. :Parameters: key : an RSA key object If a private half is given, both encryption and decryption are possible. If a public half is given, only encryption is possible. hashAlgo : hash object The hash function to use. This can be a module under `Cryptodome.Hash` or an existing hash object created from any of such modules. If not specified, `Cryptodome.Hash.SHA1` is used. mgfunc : callable A mask generation function that accepts two parameters: a string to use as seed, and the lenth of the mask to generate, in bytes. If not specified, the standard MGF1 is used (a safe choice). label : byte string A label to apply to this particular encryption. If not specified, an empty string is used. Specifying a label does not improve security. randfunc : callable A function that returns random bytes. :attention: Modify the mask generation function only if you know what you are doing. Sender and receiver must use the same one. """ self._key = key if hashAlgo: self._hashObj = hashAlgo else: self._hashObj = Cryptodome.Hash.SHA1 if mgfunc: self._mgf = mgfunc else: self._mgf = lambda x,y: MGF1(x,y,self._hashObj) self._label = label self._randfunc = randfunc
Initialize this PKCS#1 OAEP cipher object. :Parameters: key : an RSA key object If a private half is given, both encryption and decryption are possible. If a public half is given, only encryption is possible. hashAlgo : hash object The hash function to use. This can be a module under `Cryptodome.Hash` or an existing hash object created from any of such modules. If not specified, `Cryptodome.Hash.SHA1` is used. mgfunc : callable A mask generation function that accepts two parameters: a string to use as seed, and the lenth of the mask to generate, in bytes. If not specified, the standard MGF1 is used (a safe choice). label : byte string A label to apply to this particular encryption. If not specified, an empty string is used. Specifying a label does not improve security. randfunc : callable A function that returns random bytes. :attention: Modify the mask generation function only if you know what you are doing. Sender and receiver must use the same one.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/PKCS1_OAEP.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/PKCS1_OAEP.py
MIT
def encrypt(self, message): """Produce the PKCS#1 OAEP encryption of a message. This function is named ``RSAES-OAEP-ENCRYPT``, and is specified in section 7.1.1 of RFC3447. :Parameters: message : byte string The message to encrypt, also known as plaintext. It can be of variable length, but not longer than the RSA modulus (in bytes) minus 2, minus twice the hash output size. :Return: A byte string, the ciphertext in which the message is encrypted. It is as long as the RSA modulus (in bytes). :Raise ValueError: If the RSA key length is not sufficiently long to deal with the given message. """ # TODO: Verify the key is RSA # See 7.1.1 in RFC3447 modBits = Cryptodome.Util.number.size(self._key.n) k = ceil_div(modBits,8) # Convert from bits to bytes hLen = self._hashObj.digest_size mLen = len(message) # Step 1b ps_len = k-mLen-2*hLen-2 if ps_len<0: raise ValueError("Plaintext is too long.") # Step 2a lHash = self._hashObj.new(self._label).digest() # Step 2b ps = bchr(0x00)*ps_len # Step 2c db = lHash + ps + bchr(0x01) + message # Step 2d ros = self._randfunc(hLen) # Step 2e dbMask = self._mgf(ros, k-hLen-1) # Step 2f maskedDB = strxor(db, dbMask) # Step 2g seedMask = self._mgf(maskedDB, hLen) # Step 2h maskedSeed = strxor(ros, seedMask) # Step 2i em = bchr(0x00) + maskedSeed + maskedDB # Step 3a (OS2IP) em_int = bytes_to_long(em) # Step 3b (RSAEP) m_int = self._key._encrypt(em_int) # Step 3c (I2OSP) c = long_to_bytes(m_int, k) return c
Produce the PKCS#1 OAEP encryption of a message. This function is named ``RSAES-OAEP-ENCRYPT``, and is specified in section 7.1.1 of RFC3447. :Parameters: message : byte string The message to encrypt, also known as plaintext. It can be of variable length, but not longer than the RSA modulus (in bytes) minus 2, minus twice the hash output size. :Return: A byte string, the ciphertext in which the message is encrypted. It is as long as the RSA modulus (in bytes). :Raise ValueError: If the RSA key length is not sufficiently long to deal with the given message.
encrypt
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/PKCS1_OAEP.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/PKCS1_OAEP.py
MIT
def decrypt(self, ct): """Decrypt a PKCS#1 OAEP ciphertext. This function is named ``RSAES-OAEP-DECRYPT``, and is specified in section 7.1.2 of RFC3447. :Parameters: ct : byte string The ciphertext that contains the message to recover. :Return: A byte string, the original message. :Raise ValueError: If the ciphertext length is incorrect, or if the decryption does not succeed. :Raise TypeError: If the RSA key has no private half. """ # See 7.1.2 in RFC3447 modBits = Cryptodome.Util.number.size(self._key.n) k = ceil_div(modBits,8) # Convert from bits to bytes hLen = self._hashObj.digest_size # Step 1b and 1c if len(ct) != k or k<hLen+2: raise ValueError("Ciphertext with incorrect length.") # Step 2a (O2SIP) ct_int = bytes_to_long(ct) # Step 2b (RSADP) m_int = self._key._decrypt(ct_int) # Complete step 2c (I2OSP) em = long_to_bytes(m_int, k) # Step 3a lHash = self._hashObj.new(self._label).digest() # Step 3b y = em[0] # y must be 0, but we MUST NOT check it here in order not to # allow attacks like Manger's (http://dl.acm.org/citation.cfm?id=704143) maskedSeed = em[1:hLen+1] maskedDB = em[hLen+1:] # Step 3c seedMask = self._mgf(maskedDB, hLen) # Step 3d seed = strxor(maskedSeed, seedMask) # Step 3e dbMask = self._mgf(seed, k-hLen-1) # Step 3f db = strxor(maskedDB, dbMask) # Step 3g valid = 1 one = db[hLen:].find(bchr(0x01)) lHash1 = db[:hLen] if lHash1!=lHash: valid = 0 if one<0: valid = 0 if bord(y)!=0: valid = 0 if not valid: raise ValueError("Incorrect decryption.") # Step 4 return db[hLen+one+1:]
Decrypt a PKCS#1 OAEP ciphertext. This function is named ``RSAES-OAEP-DECRYPT``, and is specified in section 7.1.2 of RFC3447. :Parameters: ct : byte string The ciphertext that contains the message to recover. :Return: A byte string, the original message. :Raise ValueError: If the ciphertext length is incorrect, or if the decryption does not succeed. :Raise TypeError: If the RSA key has no private half.
decrypt
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/PKCS1_OAEP.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/PKCS1_OAEP.py
MIT
def new(key, hashAlgo=None, mgfunc=None, label=b(''), randfunc=None): """Return a cipher object `PKCS1OAEP_Cipher` that can be used to perform PKCS#1 OAEP encryption or decryption. :Parameters: key : RSA key object The key to use to encrypt or decrypt the message. This is a `Cryptodome.PublicKey.RSA` object. Decryption is only possible if *key* is a private RSA key. hashAlgo : hash object The hash function to use. This can be a module under `Cryptodome.Hash` or an existing hash object created from any of such modules. If not specified, `Cryptodome.Hash.SHA1` is used. mgfunc : callable A mask generation function that accepts two parameters: a string to use as seed, and the lenth of the mask to generate, in bytes. If not specified, the standard MGF1 is used (a safe choice). label : byte string A label to apply to this particular encryption. If not specified, an empty string is used. Specifying a label does not improve security. randfunc : callable A function that returns random bytes. The default is `Random.get_random_bytes`. :attention: Modify the mask generation function only if you know what you are doing. Sender and receiver must use the same one. """ if randfunc is None: randfunc = Random.get_random_bytes return PKCS1OAEP_Cipher(key, hashAlgo, mgfunc, label, randfunc)
Return a cipher object `PKCS1OAEP_Cipher` that can be used to perform PKCS#1 OAEP encryption or decryption. :Parameters: key : RSA key object The key to use to encrypt or decrypt the message. This is a `Cryptodome.PublicKey.RSA` object. Decryption is only possible if *key* is a private RSA key. hashAlgo : hash object The hash function to use. This can be a module under `Cryptodome.Hash` or an existing hash object created from any of such modules. If not specified, `Cryptodome.Hash.SHA1` is used. mgfunc : callable A mask generation function that accepts two parameters: a string to use as seed, and the lenth of the mask to generate, in bytes. If not specified, the standard MGF1 is used (a safe choice). label : byte string A label to apply to this particular encryption. If not specified, an empty string is used. Specifying a label does not improve security. randfunc : callable A function that returns random bytes. The default is `Random.get_random_bytes`. :attention: Modify the mask generation function only if you know what you are doing. Sender and receiver must use the same one.
new
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/PKCS1_OAEP.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/PKCS1_OAEP.py
MIT
def __init__(self, key, randfunc): """Initialize this PKCS#1 v1.5 cipher object. :Parameters: key : an RSA key object If a private half is given, both encryption and decryption are possible. If a public half is given, only encryption is possible. randfunc : callable Function that returns random bytes. """ self._key = key self._randfunc = randfunc
Initialize this PKCS#1 v1.5 cipher object. :Parameters: key : an RSA key object If a private half is given, both encryption and decryption are possible. If a public half is given, only encryption is possible. randfunc : callable Function that returns random bytes.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/PKCS1_v1_5.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/PKCS1_v1_5.py
MIT
def encrypt(self, message): """Produce the PKCS#1 v1.5 encryption of a message. This function is named ``RSAES-PKCS1-V1_5-ENCRYPT``, and is specified in section 7.2.1 of RFC3447. For a complete example see `Cryptodome.Cipher.PKCS1_v1_5`. :Parameters: message : byte string The message to encrypt, also known as plaintext. It can be of variable length, but not longer than the RSA modulus (in bytes) minus 11. :Return: A byte string, the ciphertext in which the message is encrypted. It is as long as the RSA modulus (in bytes). :Raise ValueError: If the RSA key length is not sufficiently long to deal with the given message. """ # See 7.2.1 in RFC3447 modBits = Cryptodome.Util.number.size(self._key.n) k = ceil_div(modBits,8) # Convert from bits to bytes mLen = len(message) # Step 1 if mLen > k-11: raise ValueError("Plaintext is too long.") # Step 2a ps = [] while len(ps) != k - mLen - 3: new_byte = self._randfunc(1) if bord(new_byte[0]) == 0x00: continue ps.append(new_byte) ps = b("").join(ps) assert(len(ps) == k - mLen - 3) # Step 2b em = b('\x00\x02') + ps + bchr(0x00) + message # Step 3a (OS2IP) em_int = bytes_to_long(em) # Step 3b (RSAEP) m_int = self._key._encrypt(em_int) # Step 3c (I2OSP) c = long_to_bytes(m_int, k) return c
Produce the PKCS#1 v1.5 encryption of a message. This function is named ``RSAES-PKCS1-V1_5-ENCRYPT``, and is specified in section 7.2.1 of RFC3447. For a complete example see `Cryptodome.Cipher.PKCS1_v1_5`. :Parameters: message : byte string The message to encrypt, also known as plaintext. It can be of variable length, but not longer than the RSA modulus (in bytes) minus 11. :Return: A byte string, the ciphertext in which the message is encrypted. It is as long as the RSA modulus (in bytes). :Raise ValueError: If the RSA key length is not sufficiently long to deal with the given message.
encrypt
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/PKCS1_v1_5.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/PKCS1_v1_5.py
MIT
def new(key, randfunc=None): """Return a cipher object `PKCS115_Cipher` that can be used to perform PKCS#1 v1.5 encryption or decryption. :Parameters: key : RSA key object The key to use to encrypt or decrypt the message. This is a `Cryptodome.PublicKey.RSA` object. Decryption is only possible if *key* is a private RSA key. randfunc : callable Function that return random bytes. The default is `Cryptodome.Random.get_random_bytes`. """ if randfunc is None: randfunc = Random.get_random_bytes return PKCS115_Cipher(key, randfunc)
Return a cipher object `PKCS115_Cipher` that can be used to perform PKCS#1 v1.5 encryption or decryption. :Parameters: key : RSA key object The key to use to encrypt or decrypt the message. This is a `Cryptodome.PublicKey.RSA` object. Decryption is only possible if *key* is a private RSA key. randfunc : callable Function that return random bytes. The default is `Cryptodome.Random.get_random_bytes`.
new
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/PKCS1_v1_5.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/PKCS1_v1_5.py
MIT
def __init__(self, key, nonce): """Initialize a Salsa20 cipher object See also `new()` at the module level.""" if len(key) not in key_size: raise ValueError("Incorrect key length for Salsa20 (%d bytes)" % len(key)) if len(nonce) != 8: raise ValueError("Incorrect nonce length for Salsa20 (%d bytes)" % len(nonce)) #: Nonce self.nonce = nonce expect_byte_string(key) expect_byte_string(nonce) self._state = VoidPointer() result = _raw_salsa20_lib.Salsa20_stream_init( key, c_size_t(len(key)), nonce, c_size_t(len(nonce)), self._state.address_of()) if result: raise ValueError("Error %d instantiating a Salsa20 cipher") self._state = SmartPointer(self._state.get(), _raw_salsa20_lib.Salsa20_stream_destroy) self.block_size = 1 self.key_size = len(key)
Initialize a Salsa20 cipher object See also `new()` at the module level.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/Salsa20.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/Salsa20.py
MIT
def new(key, nonce=None): """Create a new Salsa20 cipher :Parameters: key : byte string The secret key to use in the symmetric cipher. It must be 16 or 32 bytes long. nonce : byte string A value that must never be reused for any other encryption. It must be 8 bytes long. If not provided, a random byte string will be generated (you can read it back via the ``nonce`` attribute). :Return: an `Salsa20Cipher` object """ if nonce is None: nonce = get_random_bytes(8) return Salsa20Cipher(key, nonce)
Create a new Salsa20 cipher :Parameters: key : byte string The secret key to use in the symmetric cipher. It must be 16 or 32 bytes long. nonce : byte string A value that must never be reused for any other encryption. It must be 8 bytes long. If not provided, a random byte string will be generated (you can read it back via the ``nonce`` attribute). :Return: an `Salsa20Cipher` object
new
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/Salsa20.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/Salsa20.py
MIT
def __init__(self, block_cipher, iv): """Create a new block cipher, configured in CBC mode. :Parameters: block_cipher : C pointer A smart pointer to the low-level block cipher instance. iv : byte string The initialization vector to use for encryption or decryption. It is as long as the cipher block. **The IV must be unpredictable**. Ideally it is picked randomly. Reusing the *IV* for encryptions performed with the same key compromises confidentiality. """ expect_byte_string(iv) self._state = VoidPointer() result = raw_cbc_lib.CBC_start_operation(block_cipher.get(), iv, c_size_t(len(iv)), self._state.address_of()) if result: raise ValueError("Error %d while instatiating the CBC mode" % result) # Ensure that object disposal of this Python object will (eventually) # free the memory allocated by the raw library for the cipher mode self._state = SmartPointer(self._state.get(), raw_cbc_lib.CBC_stop_operation) # Memory allocated for the underlying block cipher is now owed # by the cipher mode block_cipher.release() self.block_size = len(iv) """The block size of the underlying cipher, in bytes.""" self.iv = iv """The Initialization Vector originally used to create the object. The value does not change.""" self.IV = iv """Alias for `iv`""" self._next = [ self.encrypt, self.decrypt ]
Create a new block cipher, configured in CBC mode. :Parameters: block_cipher : C pointer A smart pointer to the low-level block cipher instance. iv : byte string The initialization vector to use for encryption or decryption. It is as long as the cipher block. **The IV must be unpredictable**. Ideally it is picked randomly. Reusing the *IV* for encryptions performed with the same key compromises confidentiality.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_cbc.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_cbc.py
MIT
def encrypt(self, plaintext): """Encrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have encrypted a message you cannot encrypt (or decrypt) another message using the same object. The data to encrypt can be broken up in two or more pieces and `encrypt` can be called multiple times. That is, the statement: >>> c.encrypt(a) + c.encrypt(b) is equivalent to: >>> c.encrypt(a+b) That also means that you cannot reuse an object for encrypting or decrypting other data with the same key. This function does not add any padding to the plaintext. :Parameters: plaintext : byte string The piece of data to encrypt. Its lenght must be multiple of the cipher block size. :Return: the encrypted data, as a byte string. It is as long as *plaintext*. """ if self.encrypt not in self._next: raise TypeError("encrypt() cannot be called after decrypt()") self._next = [ self.encrypt ] expect_byte_string(plaintext) ciphertext = create_string_buffer(len(plaintext)) result = raw_cbc_lib.CBC_encrypt(self._state.get(), plaintext, ciphertext, c_size_t(len(plaintext))) if result: raise ValueError("Error %d while encrypting in CBC mode" % result) return get_raw_buffer(ciphertext)
Encrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have encrypted a message you cannot encrypt (or decrypt) another message using the same object. The data to encrypt can be broken up in two or more pieces and `encrypt` can be called multiple times. That is, the statement: >>> c.encrypt(a) + c.encrypt(b) is equivalent to: >>> c.encrypt(a+b) That also means that you cannot reuse an object for encrypting or decrypting other data with the same key. This function does not add any padding to the plaintext. :Parameters: plaintext : byte string The piece of data to encrypt. Its lenght must be multiple of the cipher block size. :Return: the encrypted data, as a byte string. It is as long as *plaintext*.
encrypt
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_cbc.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_cbc.py
MIT
def decrypt(self, ciphertext): """Decrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have decrypted a message you cannot decrypt (or encrypt) another message with the same object. The data to decrypt can be broken up in two or more pieces and `decrypt` can be called multiple times. That is, the statement: >>> c.decrypt(a) + c.decrypt(b) is equivalent to: >>> c.decrypt(a+b) This function does not remove any padding from the plaintext. :Parameters: ciphertext : byte string The piece of data to decrypt. Its length must be multiple of the cipher block size. :Return: the decrypted data (byte string). """ if self.decrypt not in self._next: raise TypeError("decrypt() cannot be called after encrypt()") self._next = [ self.decrypt ] expect_byte_string(ciphertext) plaintext = create_string_buffer(len(ciphertext)) result = raw_cbc_lib.CBC_decrypt(self._state.get(), ciphertext, plaintext, c_size_t(len(ciphertext))) if result: raise ValueError("Error %d while decrypting in CBC mode" % result) return get_raw_buffer(plaintext)
Decrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have decrypted a message you cannot decrypt (or encrypt) another message with the same object. The data to decrypt can be broken up in two or more pieces and `decrypt` can be called multiple times. That is, the statement: >>> c.decrypt(a) + c.decrypt(b) is equivalent to: >>> c.decrypt(a+b) This function does not remove any padding from the plaintext. :Parameters: ciphertext : byte string The piece of data to decrypt. Its length must be multiple of the cipher block size. :Return: the decrypted data (byte string).
decrypt
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_cbc.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_cbc.py
MIT
def _create_cbc_cipher(factory, **kwargs): """Instantiate a cipher object that performs CBC encryption/decryption. :Parameters: factory : module The underlying block cipher, a module from ``Cryptodome.Cipher``. :Keywords: iv : byte string The IV to use for CBC. IV : byte string Alias for ``iv``. Any other keyword will be passed to the underlying block cipher. See the relevant documentation for details (at least ``key`` will need to be present). """ cipher_state = factory._create_base_cipher(kwargs) iv = kwargs.pop("IV", None) IV = kwargs.pop("iv", None) if (None, None) == (iv, IV): iv = get_random_bytes(factory.block_size) if iv is not None: if IV is not None: raise TypeError("You must either use 'iv' or 'IV', not both") else: iv = IV if kwargs: raise TypeError("Unknown parameters for CBC: %s" % str(kwargs)) return CbcMode(cipher_state, iv)
Instantiate a cipher object that performs CBC encryption/decryption. :Parameters: factory : module The underlying block cipher, a module from ``Cryptodome.Cipher``. :Keywords: iv : byte string The IV to use for CBC. IV : byte string Alias for ``iv``. Any other keyword will be passed to the underlying block cipher. See the relevant documentation for details (at least ``key`` will need to be present).
_create_cbc_cipher
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_cbc.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_cbc.py
MIT
def _update(self, assoc_data_pt=b("")): """Update the MAC with associated data or plaintext (without FSM checks)""" if self._mac_status == MacStatus.NOT_STARTED: self._cache.append(assoc_data_pt) return assert(byte_string(self._cache)) assert(len(self._cache) < self.block_size) if len(self._cache) > 0: filler = min(self.block_size - len(self._cache), len(assoc_data_pt)) self._cache += assoc_data_pt[:filler] assoc_data_pt = assoc_data_pt[filler:] if len(self._cache) < self.block_size: return # The cache is exactly one block self._t = self._mac.encrypt(self._cache) self._cache = b("") update_len = len(assoc_data_pt) // self.block_size * self.block_size self._cache = assoc_data_pt[update_len:] if update_len > 0: self._t = self._mac.encrypt(assoc_data_pt[:update_len])[-16:]
Update the MAC with associated data or plaintext (without FSM checks)
_update
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_ccm.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_ccm.py
MIT
def encrypt(self, plaintext): """Encrypt data with the key set at initialization. A cipher object is stateful: once you have encrypted a message you cannot encrypt (or decrypt) another message using the same object. This method can be called only **once** if ``msg_len`` was not passed at initialization. If ``msg_len`` was given, the data to encrypt can be broken up in two or more pieces and `encrypt` can be called multiple times. That is, the statement: >>> c.encrypt(a) + c.encrypt(b) is equivalent to: >>> c.encrypt(a+b) This function does not add any padding to the plaintext. :Parameters: plaintext : byte string The piece of data to encrypt. It can be of any length. :Return: the encrypted data, as a byte string. It is as long as *plaintext*. """ if self.encrypt not in self._next: raise TypeError("encrypt() can only be called after" " initialization or an update()") self._next = [self.encrypt, self.digest] # No more associated data allowed from now if self._assoc_len is None: assert(isinstance(self._cache, list)) self._assoc_len = sum([len(x) for x in self._cache]) if self._msg_len is not None: self._start_mac() else: if self._cumul_assoc_len < self._assoc_len: raise ValueError("Associated data is too short") # Only once piece of plaintext accepted if message length was # not declared in advance if self._msg_len is None: self._msg_len = len(plaintext) self._start_mac() self._next = [self.digest] self._cumul_msg_len += len(plaintext) if self._cumul_msg_len > self._msg_len: raise ValueError("Message is too long") if self._mac_status == MacStatus.PROCESSING_AUTH_DATA: # Associated data is concatenated with the least number # of zero bytes (possibly none) to reach alignment to # the 16 byte boundary (A.2.3) self._pad_cache_and_update() self._mac_status = MacStatus.PROCESSING_PLAINTEXT self._update(plaintext) return self._cipher.encrypt(plaintext)
Encrypt data with the key set at initialization. A cipher object is stateful: once you have encrypted a message you cannot encrypt (or decrypt) another message using the same object. This method can be called only **once** if ``msg_len`` was not passed at initialization. If ``msg_len`` was given, the data to encrypt can be broken up in two or more pieces and `encrypt` can be called multiple times. That is, the statement: >>> c.encrypt(a) + c.encrypt(b) is equivalent to: >>> c.encrypt(a+b) This function does not add any padding to the plaintext. :Parameters: plaintext : byte string The piece of data to encrypt. It can be of any length. :Return: the encrypted data, as a byte string. It is as long as *plaintext*.
encrypt
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_ccm.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_ccm.py
MIT
def decrypt(self, ciphertext): """Decrypt data with the key set at initialization. A cipher object is stateful: once you have decrypted a message you cannot decrypt (or encrypt) another message with the same object. This method can be called only **once** if ``msg_len`` was not passed at initialization. If ``msg_len`` was given, the data to decrypt can be broken up in two or more pieces and `decrypt` can be called multiple times. That is, the statement: >>> c.decrypt(a) + c.decrypt(b) is equivalent to: >>> c.decrypt(a+b) This function does not remove any padding from the plaintext. :Parameters: ciphertext : byte string The piece of data to decrypt. It can be of any length. :Return: the decrypted data (byte string). """ if self.decrypt not in self._next: raise TypeError("decrypt() can only be called" " after initialization or an update()") self._next = [self.decrypt, self.verify] # No more associated data allowed from now if self._assoc_len is None: assert(isinstance(self._cache, list)) self._assoc_len = sum([len(x) for x in self._cache]) if self._msg_len is not None: self._start_mac() else: if self._cumul_assoc_len < self._assoc_len: raise ValueError("Associated data is too short") # Only once piece of ciphertext accepted if message length was # not declared in advance if self._msg_len is None: self._msg_len = len(ciphertext) self._start_mac() self._next = [self.verify] self._cumul_msg_len += len(ciphertext) if self._cumul_msg_len > self._msg_len: raise ValueError("Message is too long") if self._mac_status == MacStatus.PROCESSING_AUTH_DATA: # Associated data is concatenated with the least number # of zero bytes (possibly none) to reach alignment to # the 16 byte boundary (A.2.3) self._pad_cache_and_update() self._mac_status = MacStatus.PROCESSING_PLAINTEXT # Encrypt is equivalent to decrypt with the CTR mode plaintext = self._cipher.encrypt(ciphertext) self._update(plaintext) return plaintext
Decrypt data with the key set at initialization. A cipher object is stateful: once you have decrypted a message you cannot decrypt (or encrypt) another message with the same object. This method can be called only **once** if ``msg_len`` was not passed at initialization. If ``msg_len`` was given, the data to decrypt can be broken up in two or more pieces and `decrypt` can be called multiple times. That is, the statement: >>> c.decrypt(a) + c.decrypt(b) is equivalent to: >>> c.decrypt(a+b) This function does not remove any padding from the plaintext. :Parameters: ciphertext : byte string The piece of data to decrypt. It can be of any length. :Return: the decrypted data (byte string).
decrypt
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_ccm.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_ccm.py
MIT
def digest(self): """Compute the *binary* MAC tag. The caller invokes this function at the very end. This method returns the MAC that shall be sent to the receiver, together with the ciphertext. :Return: the MAC, as a byte string. """ if self.digest not in self._next: raise TypeError("digest() cannot be called when decrypting" " or validating a message") self._next = [self.digest] return self._digest()
Compute the *binary* MAC tag. The caller invokes this function at the very end. This method returns the MAC that shall be sent to the receiver, together with the ciphertext. :Return: the MAC, as a byte string.
digest
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_ccm.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_ccm.py
MIT
def verify(self, received_mac_tag): """Validate the *binary* MAC tag. The caller invokes this function at the very end. This method checks if the decrypted message is indeed valid (that is, if the key is correct) and it has not been tampered with while in transit. :Parameters: received_mac_tag : byte string This is the *binary* MAC, as received from the sender. :Raises ValueError: if the MAC does not match. The message has been tampered with or the key is incorrect. """ if self.verify not in self._next: raise TypeError("verify() cannot be called" " when encrypting a message") self._next = [self.verify] self._digest() secret = get_random_bytes(16) mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=self._mac_tag) mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=received_mac_tag) if mac1.digest() != mac2.digest(): raise ValueError("MAC check failed")
Validate the *binary* MAC tag. The caller invokes this function at the very end. This method checks if the decrypted message is indeed valid (that is, if the key is correct) and it has not been tampered with while in transit. :Parameters: received_mac_tag : byte string This is the *binary* MAC, as received from the sender. :Raises ValueError: if the MAC does not match. The message has been tampered with or the key is incorrect.
verify
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_ccm.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_ccm.py
MIT
def decrypt_and_verify(self, ciphertext, received_mac_tag): """Perform decrypt() and verify() in one step. :Parameters: ciphertext : byte string The piece of data to decrypt. received_mac_tag : byte string This is the *binary* MAC, as received from the sender. :Return: the decrypted data (byte string). :Raises ValueError: if the MAC does not match. The message has been tampered with or the key is incorrect. """ plaintext = self.decrypt(ciphertext) self.verify(received_mac_tag) return plaintext
Perform decrypt() and verify() in one step. :Parameters: ciphertext : byte string The piece of data to decrypt. received_mac_tag : byte string This is the *binary* MAC, as received from the sender. :Return: the decrypted data (byte string). :Raises ValueError: if the MAC does not match. The message has been tampered with or the key is incorrect.
decrypt_and_verify
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_ccm.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_ccm.py
MIT
def _create_ccm_cipher(factory, **kwargs): """Create a new block cipher, configured in CCM mode. :Parameters: factory : module A symmetric cipher module from `Cryptodome.Cipher` (like `Cryptodome.Cipher.AES`). :Keywords: key : byte string The secret key to use in the symmetric cipher. nonce : byte string A value that must never be reused for any other encryption. Its length must be in the range ``[7..13]``. 11 or 12 bytes are reasonable values in general. Bear in mind that with CCM there is a trade-off between nonce length and maximum message size. If not specified, a 11 byte long random string is used. mac_len : integer Length of the MAC, in bytes. It must be even and in the range ``[4..16]``. The default is 16. msg_len : integer Length of the message to (de)cipher. If not specified, ``encrypt`` or ``decrypt`` may only be called once. assoc_len : integer Length of the associated data. If not specified, all data is internally buffered. """ try: key = key = kwargs.pop("key") except KeyError, e: raise TypeError("Missing parameter: " + str(e)) nonce = kwargs.pop("nonce", None) # N if nonce is None: nonce = get_random_bytes(11) mac_len = kwargs.pop("mac_len", factory.block_size) msg_len = kwargs.pop("msg_len", None) # p assoc_len = kwargs.pop("assoc_len", None) # a cipher_params = dict(kwargs) return CcmMode(factory, key, nonce, mac_len, msg_len, assoc_len, cipher_params)
Create a new block cipher, configured in CCM mode. :Parameters: factory : module A symmetric cipher module from `Cryptodome.Cipher` (like `Cryptodome.Cipher.AES`). :Keywords: key : byte string The secret key to use in the symmetric cipher. nonce : byte string A value that must never be reused for any other encryption. Its length must be in the range ``[7..13]``. 11 or 12 bytes are reasonable values in general. Bear in mind that with CCM there is a trade-off between nonce length and maximum message size. If not specified, a 11 byte long random string is used. mac_len : integer Length of the MAC, in bytes. It must be even and in the range ``[4..16]``. The default is 16. msg_len : integer Length of the message to (de)cipher. If not specified, ``encrypt`` or ``decrypt`` may only be called once. assoc_len : integer Length of the associated data. If not specified, all data is internally buffered.
_create_ccm_cipher
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_ccm.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_ccm.py
MIT
def __init__(self, block_cipher, iv, segment_size): """Create a new block cipher, configured in CFB mode. :Parameters: block_cipher : C pointer A smart pointer to the low-level block cipher instance. iv : byte string The initialization vector to use for encryption or decryption. It is as long as the cipher block. **The IV must be unpredictable**. Ideally it is picked randomly. Reusing the *IV* for encryptions performed with the same key compromises confidentiality. segment_size : integer The number of bytes the plaintext and ciphertext are segmented in. """ expect_byte_string(iv) self._state = VoidPointer() result = raw_cfb_lib.CFB_start_operation(block_cipher.get(), iv, c_size_t(len(iv)), c_size_t(segment_size), self._state.address_of()) if result: raise ValueError("Error %d while instatiating the CFB mode" % result) # Ensure that object disposal of this Python object will (eventually) # free the memory allocated by the raw library for the cipher mode self._state = SmartPointer(self._state.get(), raw_cfb_lib.CFB_stop_operation) # Memory allocated for the underlying block cipher is now owed # by the cipher mode block_cipher.release() self.block_size = len(iv) """The block size of the underlying cipher, in bytes.""" self.iv = iv """The Initialization Vector originally used to create the object. The value does not change.""" self.IV = iv """Alias for `iv`""" self._next = [ self.encrypt, self.decrypt ]
Create a new block cipher, configured in CFB mode. :Parameters: block_cipher : C pointer A smart pointer to the low-level block cipher instance. iv : byte string The initialization vector to use for encryption or decryption. It is as long as the cipher block. **The IV must be unpredictable**. Ideally it is picked randomly. Reusing the *IV* for encryptions performed with the same key compromises confidentiality. segment_size : integer The number of bytes the plaintext and ciphertext are segmented in.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_cfb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_cfb.py
MIT
def encrypt(self, plaintext): """Encrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have encrypted a message you cannot encrypt (or decrypt) another message using the same object. The data to encrypt can be broken up in two or more pieces and `encrypt` can be called multiple times. That is, the statement: >>> c.encrypt(a) + c.encrypt(b) is equivalent to: >>> c.encrypt(a+b) This function does not add any padding to the plaintext. :Parameters: plaintext : byte string The piece of data to encrypt. It can be of any length. :Return: the encrypted data, as a byte string. It is as long as *plaintext*. """ if self.encrypt not in self._next: raise TypeError("encrypt() cannot be called after decrypt()") self._next = [ self.encrypt ] expect_byte_string(plaintext) ciphertext = create_string_buffer(len(plaintext)) result = raw_cfb_lib.CFB_encrypt(self._state.get(), plaintext, ciphertext, c_size_t(len(plaintext))) if result: raise ValueError("Error %d while encrypting in CFB mode" % result) return get_raw_buffer(ciphertext)
Encrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have encrypted a message you cannot encrypt (or decrypt) another message using the same object. The data to encrypt can be broken up in two or more pieces and `encrypt` can be called multiple times. That is, the statement: >>> c.encrypt(a) + c.encrypt(b) is equivalent to: >>> c.encrypt(a+b) This function does not add any padding to the plaintext. :Parameters: plaintext : byte string The piece of data to encrypt. It can be of any length. :Return: the encrypted data, as a byte string. It is as long as *plaintext*.
encrypt
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_cfb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_cfb.py
MIT
def decrypt(self, ciphertext): """Decrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have decrypted a message you cannot decrypt (or encrypt) another message with the same object. The data to decrypt can be broken up in two or more pieces and `decrypt` can be called multiple times. That is, the statement: >>> c.decrypt(a) + c.decrypt(b) is equivalent to: >>> c.decrypt(a+b) This function does not remove any padding from the plaintext. :Parameters: ciphertext : byte string The piece of data to decrypt. It can be of any length. :Return: the decrypted data (byte string). """ if self.decrypt not in self._next: raise TypeError("decrypt() cannot be called after encrypt()") self._next = [ self.decrypt ] expect_byte_string(ciphertext) plaintext = create_string_buffer(len(ciphertext)) result = raw_cfb_lib.CFB_decrypt(self._state.get(), ciphertext, plaintext, c_size_t(len(ciphertext))) if result: raise ValueError("Error %d while decrypting in CFB mode" % result) return get_raw_buffer(plaintext)
Decrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have decrypted a message you cannot decrypt (or encrypt) another message with the same object. The data to decrypt can be broken up in two or more pieces and `decrypt` can be called multiple times. That is, the statement: >>> c.decrypt(a) + c.decrypt(b) is equivalent to: >>> c.decrypt(a+b) This function does not remove any padding from the plaintext. :Parameters: ciphertext : byte string The piece of data to decrypt. It can be of any length. :Return: the decrypted data (byte string).
decrypt
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_cfb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_cfb.py
MIT
def _create_cfb_cipher(factory, **kwargs): """Instantiate a cipher object that performs CFB encryption/decryption. :Parameters: factory : module The underlying block cipher, a module from ``Cryptodome.Cipher``. :Keywords: iv : byte string The IV to use for CFB. IV : byte string Alias for ``iv``. segment_size : integer The number of bit the plaintext and ciphertext are segmented in. If not present, the default is 8. Any other keyword will be passed to the underlying block cipher. See the relevant documentation for details (at least ``key`` will need to be present). """ cipher_state = factory._create_base_cipher(kwargs) iv = kwargs.pop("IV", None) IV = kwargs.pop("iv", None) if (None, None) == (iv, IV): iv = get_random_bytes(factory.block_size) if iv is not None: if IV is not None: raise TypeError("You must either use 'iv' or 'IV', not both") else: iv = IV segment_size_bytes, rem = divmod(kwargs.pop("segment_size", 8), 8) if segment_size_bytes == 0 or rem != 0: raise ValueError("'segment_size' must be positive and multiple of 8 bits") if kwargs: raise TypeError("Unknown parameters for CFB: %s" % str(kwargs)) return CfbMode(cipher_state, iv, segment_size_bytes)
Instantiate a cipher object that performs CFB encryption/decryption. :Parameters: factory : module The underlying block cipher, a module from ``Cryptodome.Cipher``. :Keywords: iv : byte string The IV to use for CFB. IV : byte string Alias for ``iv``. segment_size : integer The number of bit the plaintext and ciphertext are segmented in. If not present, the default is 8. Any other keyword will be passed to the underlying block cipher. See the relevant documentation for details (at least ``key`` will need to be present).
_create_cfb_cipher
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_cfb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_cfb.py
MIT
def __init__(self, block_cipher, initial_counter_block, prefix_len, counter_len, little_endian): """Create a new block cipher, configured in CTR mode. :Parameters: block_cipher : C pointer A smart pointer to the low-level block cipher instance. initial_counter_block : byte string The initial plaintext to use to generate the key stream. It is as large as the cipher block, and it embeds the initial value of the counter. This value must not be reused. It shall contain a nonce or a random component. Reusing the *initial counter block* for encryptions performed with the same key compromises confidentiality. prefix_len : integer The amount of bytes at the beginning of the counter block that never change. counter_len : integer The length in bytes of the counter embedded in the counter block. little_endian : boolean True if the counter in the counter block is an integer encoded in little endian mode. If False, it is big endian. """ if len(initial_counter_block) == prefix_len + counter_len: self.nonce = initial_counter_block[:prefix_len] """Nonce; not available if there is a fixed suffix""" expect_byte_string(initial_counter_block) self._state = VoidPointer() result = raw_ctr_lib.CTR_start_operation(block_cipher.get(), initial_counter_block, c_size_t(len(initial_counter_block)), c_size_t(prefix_len), counter_len, little_endian, self._state.address_of()) if result: raise ValueError("Error %X while instatiating the CTR mode" % result) # Ensure that object disposal of this Python object will (eventually) # free the memory allocated by the raw library for the cipher mode self._state = SmartPointer(self._state.get(), raw_ctr_lib.CTR_stop_operation) # Memory allocated for the underlying block cipher is now owed # by the cipher mode block_cipher.release() self.block_size = len(initial_counter_block) """The block size of the underlying cipher, in bytes.""" self._next = [self.encrypt, self.decrypt]
Create a new block cipher, configured in CTR mode. :Parameters: block_cipher : C pointer A smart pointer to the low-level block cipher instance. initial_counter_block : byte string The initial plaintext to use to generate the key stream. It is as large as the cipher block, and it embeds the initial value of the counter. This value must not be reused. It shall contain a nonce or a random component. Reusing the *initial counter block* for encryptions performed with the same key compromises confidentiality. prefix_len : integer The amount of bytes at the beginning of the counter block that never change. counter_len : integer The length in bytes of the counter embedded in the counter block. little_endian : boolean True if the counter in the counter block is an integer encoded in little endian mode. If False, it is big endian.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_ctr.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_ctr.py
MIT
def _create_ctr_cipher(factory, **kwargs): """Instantiate a cipher object that performs CTR encryption/decryption. :Parameters: factory : module The underlying block cipher, a module from ``Cryptodome.Cipher``. :Keywords: nonce : binary string The fixed part at the beginning of the counter block - the rest is the counter number that gets increased when processing the next block. The nonce must be such that no two messages are encrypted under the same key and the same nonce. The nonce must be shorter than the block size (it can have zero length). If this parameter is not present, a random nonce will be created with length equal to half the block size. No random nonce shorter than 64 bits will be created though - you must really think through all security consequences of using such a short block size. initial_value : posive integer The initial value for the counter. If not present, the cipher will start counting from 0. The value is incremented by one for each block. The counter number is encoded in big endian mode. counter : object Instance of ``Cryptodome.Util.Counter``, which allows full customization of the counter block. This parameter is incompatible to both ``nonce`` and ``initial_value``. Any other keyword will be passed to the underlying block cipher. See the relevant documentation for details (at least ``key`` will need to be present). """ cipher_state = factory._create_base_cipher(kwargs) counter = kwargs.pop("counter", None) nonce = kwargs.pop("nonce", None) initial_value = kwargs.pop("initial_value", None) if kwargs: raise TypeError("Invalid parameters for CTR mode: %s" % str(kwargs)) if counter is not None and (nonce, initial_value) != (None, None): raise TypeError("'counter' and 'nonce'/'initial_value'" " are mutually exclusive") if counter is None: # Cryptodome.Util.Counter is not used if nonce is None: if factory.block_size < 16: raise TypeError("Impossible to create a safe nonce for short" " block sizes") nonce = get_random_bytes(factory.block_size // 2) if initial_value is None: initial_value = 0 if len(nonce) >= factory.block_size: raise ValueError("Nonce is too long") counter_len = factory.block_size - len(nonce) if (1 << (counter_len * 8)) - 1 < initial_value: raise ValueError("Initial counter value is too large") return CtrMode(cipher_state, # initial_counter_block nonce + long_to_bytes(initial_value, counter_len), len(nonce), # prefix counter_len, False) # little_endian # Cryptodome.Util.Counter is used # 'counter' used to be a callable object, but now it is # just a dictionary for backward compatibility. _counter = dict(counter) try: counter_len = _counter.pop("counter_len") prefix = _counter.pop("prefix") suffix = _counter.pop("suffix") initial_value = _counter.pop("initial_value") little_endian = _counter.pop("little_endian") except KeyError: raise TypeError("Incorrect counter object" " (use Cryptodome.Util.Counter.new)") # Compute initial counter block words = [] while initial_value > 0: words.append(bchr(initial_value & 255)) initial_value >>= 8 words += [bchr(0)] * max(0, counter_len - len(words)) if not little_endian: words.reverse() initial_counter_block = prefix + b("").join(words) + suffix if len(initial_counter_block) != factory.block_size: raise ValueError("Size of the counter block (% bytes) must match" " block size (%d)" % (len(initial_counter_block), factory.block_size)) return CtrMode(cipher_state, initial_counter_block, len(prefix), counter_len, little_endian)
Instantiate a cipher object that performs CTR encryption/decryption. :Parameters: factory : module The underlying block cipher, a module from ``Cryptodome.Cipher``. :Keywords: nonce : binary string The fixed part at the beginning of the counter block - the rest is the counter number that gets increased when processing the next block. The nonce must be such that no two messages are encrypted under the same key and the same nonce. The nonce must be shorter than the block size (it can have zero length). If this parameter is not present, a random nonce will be created with length equal to half the block size. No random nonce shorter than 64 bits will be created though - you must really think through all security consequences of using such a short block size. initial_value : posive integer The initial value for the counter. If not present, the cipher will start counting from 0. The value is incremented by one for each block. The counter number is encoded in big endian mode. counter : object Instance of ``Cryptodome.Util.Counter``, which allows full customization of the counter block. This parameter is incompatible to both ``nonce`` and ``initial_value``. Any other keyword will be passed to the underlying block cipher. See the relevant documentation for details (at least ``key`` will need to be present).
_create_ctr_cipher
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_ctr.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_ctr.py
MIT
def verify(self, received_mac_tag): """Validate the *binary* MAC tag. The caller invokes this function at the very end. This method checks if the decrypted message is indeed valid (that is, if the key is correct) and it has not been tampered with while in transit. :Parameters: received_mac_tag : byte string This is the *binary* MAC, as received from the sender. :Raises MacMismatchError: if the MAC does not match. The message has been tampered with or the key is incorrect. """ if self.verify not in self._next: raise TypeError("verify() cannot be called" " when encrypting a message") self._next = [self.verify] if not self._mac_tag: tag = bchr(0) * self.block_size for i in xrange(3): tag = strxor(tag, self._omac[i].digest()) self._mac_tag = tag[:self._mac_len] secret = get_random_bytes(16) mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=self._mac_tag) mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=received_mac_tag) if mac1.digest() != mac2.digest(): raise ValueError("MAC check failed")
Validate the *binary* MAC tag. The caller invokes this function at the very end. This method checks if the decrypted message is indeed valid (that is, if the key is correct) and it has not been tampered with while in transit. :Parameters: received_mac_tag : byte string This is the *binary* MAC, as received from the sender. :Raises MacMismatchError: if the MAC does not match. The message has been tampered with or the key is incorrect.
verify
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_eax.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_eax.py
MIT
def decrypt_and_verify(self, ciphertext, received_mac_tag): """Perform decrypt() and verify() in one step. :Parameters: ciphertext : byte string The piece of data to decrypt. received_mac_tag : byte string This is the *binary* MAC, as received from the sender. :Return: the decrypted data (byte string). :Raises MacMismatchError: if the MAC does not match. The message has been tampered with or the key is incorrect. """ pt = self.decrypt(ciphertext) self.verify(received_mac_tag) return pt
Perform decrypt() and verify() in one step. :Parameters: ciphertext : byte string The piece of data to decrypt. received_mac_tag : byte string This is the *binary* MAC, as received from the sender. :Return: the decrypted data (byte string). :Raises MacMismatchError: if the MAC does not match. The message has been tampered with or the key is incorrect.
decrypt_and_verify
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_eax.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_eax.py
MIT
def _create_eax_cipher(factory, **kwargs): """Create a new block cipher, configured in EAX mode. :Parameters: factory : module A symmetric cipher module from `Cryptodome.Cipher` (like `Cryptodome.Cipher.AES`). :Keywords: key : byte string The secret key to use in the symmetric cipher. nonce : byte string A value that must never be reused for any other encryption. There are no restrictions on its length, but it is recommended to use at least 16 bytes. The nonce shall never repeat for two different messages encrypted with the same key, but it does not need to be random. If not specified, a 16 byte long random string is used. mac_len : integer Length of the MAC, in bytes. It must be no larger than the cipher block bytes (which is the default). """ try: key = kwargs.pop("key") nonce = kwargs.pop("nonce", None) if nonce is None: nonce = get_random_bytes(16) mac_len = kwargs.pop("mac_len", factory.block_size) except KeyError, e: raise TypeError("Missing parameter: " + str(e)) return EaxMode(factory, key, nonce, mac_len, kwargs)
Create a new block cipher, configured in EAX mode. :Parameters: factory : module A symmetric cipher module from `Cryptodome.Cipher` (like `Cryptodome.Cipher.AES`). :Keywords: key : byte string The secret key to use in the symmetric cipher. nonce : byte string A value that must never be reused for any other encryption. There are no restrictions on its length, but it is recommended to use at least 16 bytes. The nonce shall never repeat for two different messages encrypted with the same key, but it does not need to be random. If not specified, a 16 byte long random string is used. mac_len : integer Length of the MAC, in bytes. It must be no larger than the cipher block bytes (which is the default).
_create_eax_cipher
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_eax.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_eax.py
MIT
def __init__(self, block_cipher): """Create a new block cipher, configured in ECB mode. :Parameters: block_cipher : C pointer A smart pointer to the low-level block cipher instance. """ self._state = VoidPointer() result = raw_ecb_lib.ECB_start_operation(block_cipher.get(), self._state.address_of()) if result: raise ValueError("Error %d while instatiating the ECB mode" % result) # Ensure that object disposal of this Python object will (eventually) # free the memory allocated by the raw library for the cipher # mode self._state = SmartPointer(self._state.get(), raw_ecb_lib.ECB_stop_operation) # Memory allocated for the underlying block cipher is now owned # by the cipher mode block_cipher.release()
Create a new block cipher, configured in ECB mode. :Parameters: block_cipher : C pointer A smart pointer to the low-level block cipher instance.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_ecb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_ecb.py
MIT
def encrypt(self, plaintext): """Encrypt data with the key set at initialization. The data to encrypt can be broken up in two or more pieces and `encrypt` can be called multiple times. That is, the statement: >>> c.encrypt(a) + c.encrypt(b) is equivalent to: >>> c.encrypt(a+b) This function does not add any padding to the plaintext. :Parameters: plaintext : byte string The piece of data to encrypt. The length must be multiple of the cipher block length. :Return: the encrypted data, as a byte string. It is as long as *plaintext*. """ expect_byte_string(plaintext) ciphertext = create_string_buffer(len(plaintext)) result = raw_ecb_lib.ECB_encrypt(self._state.get(), plaintext, ciphertext, c_size_t(len(plaintext))) if result: raise ValueError("Error %d while encrypting in ECB mode" % result) return get_raw_buffer(ciphertext)
Encrypt data with the key set at initialization. The data to encrypt can be broken up in two or more pieces and `encrypt` can be called multiple times. That is, the statement: >>> c.encrypt(a) + c.encrypt(b) is equivalent to: >>> c.encrypt(a+b) This function does not add any padding to the plaintext. :Parameters: plaintext : byte string The piece of data to encrypt. The length must be multiple of the cipher block length. :Return: the encrypted data, as a byte string. It is as long as *plaintext*.
encrypt
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_ecb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_ecb.py
MIT
def decrypt(self, ciphertext): """Decrypt data with the key set at initialization. The data to decrypt can be broken up in two or more pieces and `decrypt` can be called multiple times. That is, the statement: >>> c.decrypt(a) + c.decrypt(b) is equivalent to: >>> c.decrypt(a+b) This function does not remove any padding from the plaintext. :Parameters: ciphertext : byte string The piece of data to decrypt. The length must be multiple of the cipher block length. :Return: the decrypted data (byte string). It is as long as *ciphertext*. """ expect_byte_string(ciphertext) plaintext = create_string_buffer(len(ciphertext)) result = raw_ecb_lib.ECB_decrypt(self._state.get(), ciphertext, plaintext, c_size_t(len(ciphertext))) if result: raise ValueError("Error %d while decrypting in ECB mode" % result) return get_raw_buffer(plaintext)
Decrypt data with the key set at initialization. The data to decrypt can be broken up in two or more pieces and `decrypt` can be called multiple times. That is, the statement: >>> c.decrypt(a) + c.decrypt(b) is equivalent to: >>> c.decrypt(a+b) This function does not remove any padding from the plaintext. :Parameters: ciphertext : byte string The piece of data to decrypt. The length must be multiple of the cipher block length. :Return: the decrypted data (byte string). It is as long as *ciphertext*.
decrypt
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_ecb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_ecb.py
MIT
def _create_ecb_cipher(factory, **kwargs): """Instantiate a cipher object that performs ECB encryption/decryption. :Parameters: factory : module The underlying block cipher, a module from ``Cryptodome.Cipher``. All keywords are passed to the underlying block cipher. See the relevant documentation for details (at least ``key`` will need to be present""" cipher_state = factory._create_base_cipher(kwargs) if kwargs: raise TypeError("Unknown parameters for ECB: %s" % str(kwargs)) return EcbMode(cipher_state)
Instantiate a cipher object that performs ECB encryption/decryption. :Parameters: factory : module The underlying block cipher, a module from ``Cryptodome.Cipher``. All keywords are passed to the underlying block cipher. See the relevant documentation for details (at least ``key`` will need to be present
_create_ecb_cipher
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_ecb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_ecb.py
MIT
def digest(self): """Compute the *binary* MAC tag in an AEAD mode. The caller invokes this function at the very end. This method returns the MAC that shall be sent to the receiver, together with the ciphertext. :Return: the MAC, as a byte string. """ if self.digest not in self._next: raise TypeError("digest() cannot be called when decrypting" " or validating a message") self._next = [self.digest] return self._compute_mac()
Compute the *binary* MAC tag in an AEAD mode. The caller invokes this function at the very end. This method returns the MAC that shall be sent to the receiver, together with the ciphertext. :Return: the MAC, as a byte string.
digest
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_gcm.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_gcm.py
MIT
def _compute_mac(self): """Compute MAC without any FSM checks.""" if self._tag: return self._tag # Step 5 in NIST SP 800-38D, Algorithm 4 - Compute S self._pad_cache_and_update() self._update(long_to_bytes(8 * self._auth_len, 8)) self._update(long_to_bytes(8 * self._msg_len, 8)) s_tag = self._signer.digest() # Step 6 - Compute T self._tag = self._tag_cipher.encrypt(s_tag)[:self._mac_len] return self._tag
Compute MAC without any FSM checks.
_compute_mac
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_gcm.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_gcm.py
MIT
def _create_gcm_cipher(factory, **kwargs): """Create a new block cipher, configured in Galois Counter Mode (GCM). :Parameters: factory : module A block cipher module, taken from `Cryptodome.Cipher`. The cipher must have block length of 16 bytes. GCM has been only defined for `Cryptodome.Cipher.AES`. :Keywords: key : byte string The secret key to use in the symmetric cipher. It must be 16 (e.g. *AES-128*), 24 (e.g. *AES-192*) or 32 (e.g. *AES-256*) bytes long. nonce : byte string A value that must never be reused for any other encryption. There are no restrictions on its length, but it is recommended to use at least 16 bytes. The nonce shall never repeat for two different messages encrypted with the same key, but it does not need to be random. If not provided, a 16 byte nonce will be randomly created. mac_len : integer Length of the MAC, in bytes. It must be no larger than 16 bytes (which is the default). """ try: key = kwargs.pop("key") except KeyError, e: raise TypeError("Missing parameter:" + str(e)) nonce = kwargs.pop("nonce", None) if nonce is None: nonce = get_random_bytes(16) mac_len = kwargs.pop("mac_len", 16) return GcmMode(factory, key, nonce, mac_len, kwargs)
Create a new block cipher, configured in Galois Counter Mode (GCM). :Parameters: factory : module A block cipher module, taken from `Cryptodome.Cipher`. The cipher must have block length of 16 bytes. GCM has been only defined for `Cryptodome.Cipher.AES`. :Keywords: key : byte string The secret key to use in the symmetric cipher. It must be 16 (e.g. *AES-128*), 24 (e.g. *AES-192*) or 32 (e.g. *AES-256*) bytes long. nonce : byte string A value that must never be reused for any other encryption. There are no restrictions on its length, but it is recommended to use at least 16 bytes. The nonce shall never repeat for two different messages encrypted with the same key, but it does not need to be random. If not provided, a 16 byte nonce will be randomly created. mac_len : integer Length of the MAC, in bytes. It must be no larger than 16 bytes (which is the default).
_create_gcm_cipher
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_gcm.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_gcm.py
MIT
def encrypt(self, plaintext=None): """Encrypt the next piece of plaintext. After the entire plaintext has been passed (but before `digest`), you **must** call this method one last time with no arguments to collect the final piece of ciphertext. If possible, use the method `encrypt_and_digest` instead. :Parameters: plaintext : byte string The next piece of data to encrypt or ``None`` to signify that encryption has finished and that any remaining ciphertext has to be produced. :Return: the ciphertext, as a byte string. Its length may not match the length of the *plaintext*. """ if self.encrypt not in self._next: raise TypeError("encrypt() can only be called after" " initialization or an update()") if plaintext is None: self._next = [self.digest] else: self._next = [self.encrypt] return self._transcrypt(plaintext, _raw_ocb_lib.OCB_encrypt, "encrypt")
Encrypt the next piece of plaintext. After the entire plaintext has been passed (but before `digest`), you **must** call this method one last time with no arguments to collect the final piece of ciphertext. If possible, use the method `encrypt_and_digest` instead. :Parameters: plaintext : byte string The next piece of data to encrypt or ``None`` to signify that encryption has finished and that any remaining ciphertext has to be produced. :Return: the ciphertext, as a byte string. Its length may not match the length of the *plaintext*.
encrypt
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_ocb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_ocb.py
MIT
def decrypt(self, ciphertext=None): """Decrypt the next piece of ciphertext. After the entire ciphertext has been passed (but before `verify`), you **must** call this method one last time with no arguments to collect the remaining piece of plaintext. If possible, use the method `decrypt_and_verify` instead. :Parameters: ciphertext : byte string The next piece of data to decrypt or ``None`` to signify that decryption has finished and that any remaining plaintext has to be produced. :Return: the plaintext, as a byte string. Its length may not match the length of the *ciphertext*. """ if self.decrypt not in self._next: raise TypeError("decrypt() can only be called after" " initialization or an update()") if ciphertext is None: self._next = [self.verify] else: self._next = [self.decrypt] return self._transcrypt(ciphertext, _raw_ocb_lib.OCB_decrypt, "decrypt")
Decrypt the next piece of ciphertext. After the entire ciphertext has been passed (but before `verify`), you **must** call this method one last time with no arguments to collect the remaining piece of plaintext. If possible, use the method `decrypt_and_verify` instead. :Parameters: ciphertext : byte string The next piece of data to decrypt or ``None`` to signify that decryption has finished and that any remaining plaintext has to be produced. :Return: the plaintext, as a byte string. Its length may not match the length of the *ciphertext*.
decrypt
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_ocb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_ocb.py
MIT
def digest(self): """Compute the *binary* MAC tag. Call this method after the final `encrypt` (the one with no arguments) to obtain the MAC tag. The MAC tag is needed by the receiver to determine authenticity of the message. :Return: the MAC, as a byte string. """ if self.digest not in self._next: raise TypeError("digest() cannot be called now for this cipher") assert(len(self._cache_P) == 0) self._next = [self.digest] if self._mac_tag is None: self._compute_mac_tag() return self._mac_tag
Compute the *binary* MAC tag. Call this method after the final `encrypt` (the one with no arguments) to obtain the MAC tag. The MAC tag is needed by the receiver to determine authenticity of the message. :Return: the MAC, as a byte string.
digest
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_ocb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_ocb.py
MIT
def verify(self, received_mac_tag): """Validate the *binary* MAC tag. Call this method after the final `decrypt` (the one with no arguments) to check if the message is authentic and valid. :Parameters: received_mac_tag : byte string This is the *binary* MAC, as received from the sender. :Raises ValueError: if the MAC does not match. The message has been tampered with or the key is incorrect. """ if self.verify not in self._next: raise TypeError("verify() cannot be called now for this cipher") assert(len(self._cache_P) == 0) self._next = [self.verify] if self._mac_tag is None: self._compute_mac_tag() secret = get_random_bytes(16) mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=self._mac_tag) mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=received_mac_tag) if mac1.digest() != mac2.digest(): raise ValueError("MAC check failed")
Validate the *binary* MAC tag. Call this method after the final `decrypt` (the one with no arguments) to check if the message is authentic and valid. :Parameters: received_mac_tag : byte string This is the *binary* MAC, as received from the sender. :Raises ValueError: if the MAC does not match. The message has been tampered with or the key is incorrect.
verify
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_ocb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_ocb.py
MIT
def decrypt_and_verify(self, ciphertext, received_mac_tag): """Decrypted the message and verify its authenticity in one step. :Parameters: ciphertext : byte string The entire message to decrypt. received_mac_tag : byte string This is the *binary* MAC, as received from the sender. :Return: the decrypted data (byte string). :Raises ValueError: if the MAC does not match. The message has been tampered with or the key is incorrect. """ plaintext = self.decrypt(ciphertext) + self.decrypt() self.verify(received_mac_tag) return plaintext
Decrypted the message and verify its authenticity in one step. :Parameters: ciphertext : byte string The entire message to decrypt. received_mac_tag : byte string This is the *binary* MAC, as received from the sender. :Return: the decrypted data (byte string). :Raises ValueError: if the MAC does not match. The message has been tampered with or the key is incorrect.
decrypt_and_verify
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_ocb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_ocb.py
MIT
def _create_ocb_cipher(factory, **kwargs): """Create a new block cipher, configured in OCB mode. :Parameters: factory : module A symmetric cipher module from `Cryptodome.Cipher` (like `Cryptodome.Cipher.AES`). :Keywords: nonce : byte string A value that must never be reused for any other encryption. Its length can vary from 1 to 15 bytes. If not specified, a random 15 bytes long nonce is generated. mac_len : integer Length of the MAC, in bytes. It must be in the range ``[8..16]``. The default is 16 (128 bits). Any other keyword will be passed to the underlying block cipher. See the relevant documentation for details (at least ``key`` will need to be present). """ try: nonce = kwargs.pop("nonce", None) if nonce is None: nonce = get_random_bytes(15) mac_len = kwargs.pop("mac_len", 16) except KeyError, e: raise TypeError("Keyword missing: " + str(e)) return OcbMode(factory, nonce, mac_len, kwargs)
Create a new block cipher, configured in OCB mode. :Parameters: factory : module A symmetric cipher module from `Cryptodome.Cipher` (like `Cryptodome.Cipher.AES`). :Keywords: nonce : byte string A value that must never be reused for any other encryption. Its length can vary from 1 to 15 bytes. If not specified, a random 15 bytes long nonce is generated. mac_len : integer Length of the MAC, in bytes. It must be in the range ``[8..16]``. The default is 16 (128 bits). Any other keyword will be passed to the underlying block cipher. See the relevant documentation for details (at least ``key`` will need to be present).
_create_ocb_cipher
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_ocb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_ocb.py
MIT
def __init__(self, block_cipher, iv): """Create a new block cipher, configured in OFB mode. :Parameters: block_cipher : C pointer A smart pointer to the low-level block cipher instance. iv : byte string The initialization vector to use for encryption or decryption. It is as long as the cipher block. **The IV must be a nonce, to to be reused for any other message**. It shall be a nonce or a random value. Reusing the *IV* for encryptions performed with the same key compromises confidentiality. """ expect_byte_string(iv) self._state = VoidPointer() result = raw_ofb_lib.OFB_start_operation(block_cipher.get(), iv, c_size_t(len(iv)), self._state.address_of()) if result: raise ValueError("Error %d while instatiating the OFB mode" % result) # Ensure that object disposal of this Python object will (eventually) # free the memory allocated by the raw library for the cipher mode self._state = SmartPointer(self._state.get(), raw_ofb_lib.OFB_stop_operation) # Memory allocated for the underlying block cipher is now owed # by the cipher mode block_cipher.release() self.block_size = len(iv) """The block size of the underlying cipher, in bytes.""" self.iv = iv """The Initialization Vector originally used to create the object. The value does not change.""" self.IV = iv """Alias for `iv`""" self._next = [ self.encrypt, self.decrypt ]
Create a new block cipher, configured in OFB mode. :Parameters: block_cipher : C pointer A smart pointer to the low-level block cipher instance. iv : byte string The initialization vector to use for encryption or decryption. It is as long as the cipher block. **The IV must be a nonce, to to be reused for any other message**. It shall be a nonce or a random value. Reusing the *IV* for encryptions performed with the same key compromises confidentiality.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_ofb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_ofb.py
MIT
def _create_ofb_cipher(factory, **kwargs): """Instantiate a cipher object that performs OFB encryption/decryption. :Parameters: factory : module The underlying block cipher, a module from ``Cryptodome.Cipher``. :Keywords: iv : byte string The IV to use for OFB. IV : byte string Alias for ``iv``. Any other keyword will be passed to the underlying block cipher. See the relevant documentation for details (at least ``key`` will need to be present). """ cipher_state = factory._create_base_cipher(kwargs) iv = kwargs.pop("IV", None) IV = kwargs.pop("iv", None) if (None, None) == (iv, IV): iv = get_random_bytes(factory.block_size) if iv is not None: if IV is not None: raise TypeError("You must either use 'iv' or 'IV', not both") else: iv = IV if kwargs: raise TypeError("Unknown parameters for OFB: %s" % str(kwargs)) return OfbMode(cipher_state, iv)
Instantiate a cipher object that performs OFB encryption/decryption. :Parameters: factory : module The underlying block cipher, a module from ``Cryptodome.Cipher``. :Keywords: iv : byte string The IV to use for OFB. IV : byte string Alias for ``iv``. Any other keyword will be passed to the underlying block cipher. See the relevant documentation for details (at least ``key`` will need to be present).
_create_ofb_cipher
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_ofb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_ofb.py
MIT
def encrypt(self, plaintext): """Encrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have encrypted a message you cannot encrypt (or decrypt) another message using the same object. The data to encrypt can be broken up in two or more pieces and `encrypt` can be called multiple times. That is, the statement: >>> c.encrypt(a) + c.encrypt(b) is equivalent to: >>> c.encrypt(a+b) This function does not add any padding to the plaintext. :Parameters: plaintext : byte string The piece of data to encrypt. :Return: the encrypted data, as a byte string. It is as long as *plaintext* with one exception: when encrypting the first message chunk, the encypted IV is prepended to the returned ciphertext. """ res = self._cipher.encrypt(plaintext) if not self._done_first_block: res = self._encrypted_IV + res self._done_first_block = True return res
Encrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have encrypted a message you cannot encrypt (or decrypt) another message using the same object. The data to encrypt can be broken up in two or more pieces and `encrypt` can be called multiple times. That is, the statement: >>> c.encrypt(a) + c.encrypt(b) is equivalent to: >>> c.encrypt(a+b) This function does not add any padding to the plaintext. :Parameters: plaintext : byte string The piece of data to encrypt. :Return: the encrypted data, as a byte string. It is as long as *plaintext* with one exception: when encrypting the first message chunk, the encypted IV is prepended to the returned ciphertext.
encrypt
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_openpgp.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_openpgp.py
MIT
def _create_openpgp_cipher(factory, **kwargs): """Create a new block cipher, configured in OpenPGP mode. :Parameters: factory : module The module. :Keywords: key : byte string The secret key to use in the symmetric cipher. IV : byte string The initialization vector to use for encryption or decryption. For encryption, the IV must be as long as the cipher block size. For decryption, it must be 2 bytes longer (it is actually the *encrypted* IV which was prefixed to the ciphertext). """ iv = kwargs.pop("IV", None) IV = kwargs.pop("iv", None) if (None, None) == (iv, IV): iv = get_random_bytes(factory.block_size) if iv is not None: if IV is not None: raise TypeError("You must either use 'iv' or 'IV', not both") else: iv = IV try: key = kwargs.pop("key") except KeyError, e: raise TypeError("Missing component: " + str(e)) return OpenPgpMode(factory, key, iv, kwargs)
Create a new block cipher, configured in OpenPGP mode. :Parameters: factory : module The module. :Keywords: key : byte string The secret key to use in the symmetric cipher. IV : byte string The initialization vector to use for encryption or decryption. For encryption, the IV must be as long as the cipher block size. For decryption, it must be 2 bytes longer (it is actually the *encrypted* IV which was prefixed to the ciphertext).
_create_openpgp_cipher
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_openpgp.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_openpgp.py
MIT
def _create_ctr_cipher(self, mac_tag): """Create a new CTR cipher from the MAC in SIV mode""" tag_int = bytes_to_long(mac_tag) return self._factory.new( self._subkey_cipher, self._factory.MODE_CTR, initial_value=tag_int ^ (tag_int & 0x8000000080000000L), nonce=b(""), **self._cipher_params)
Create a new CTR cipher from the MAC in SIV mode
_create_ctr_cipher
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_siv.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_siv.py
MIT
def update(self, component): """Protect one associated data component For SIV, the associated data is a sequence (*vector*) of non-empty byte strings (*components*). This method consumes the next component. It must be called once for each of the components that constitue the associated data. Note that the components have clear boundaries, so that: >>> cipher.update(b"builtin") >>> cipher.update(b"securely") is not equivalent to: >>> cipher.update(b"built") >>> cipher.update(b"insecurely") If there is no associated data, this method must not be called. :Parameters: component : byte string The next associated data component. It must not be empty. """ if self.update not in self._next: raise TypeError("update() can only be called" " immediately after initialization") self._next = [self.update, self.encrypt, self.decrypt, self.digest, self.verify] return self._kdf.update(component)
Protect one associated data component For SIV, the associated data is a sequence (*vector*) of non-empty byte strings (*components*). This method consumes the next component. It must be called once for each of the components that constitue the associated data. Note that the components have clear boundaries, so that: >>> cipher.update(b"builtin") >>> cipher.update(b"securely") is not equivalent to: >>> cipher.update(b"built") >>> cipher.update(b"insecurely") If there is no associated data, this method must not be called. :Parameters: component : byte string The next associated data component. It must not be empty.
update
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_siv.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_siv.py
MIT
def encrypt(self, plaintext): """Encrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have encrypted a message you cannot encrypt (or decrypt) another message using the same object. This method can be called only **once**. You cannot reuse an object for encrypting or decrypting other data with the same key. This function does not add any padding to the plaintext. :Parameters: plaintext : byte string The piece of data to encrypt. It can be of any length, but it cannot be empty. :Return: the encrypted data, as a byte string. It is as long as *plaintext*. """ if self.encrypt not in self._next: raise TypeError("encrypt() can only be called after" " initialization or an update()") self._next = [self.digest] if self._nonce: self._kdf.update(self.nonce) self._kdf.update(plaintext) self._mac_tag = self._kdf.derive() cipher = self._create_ctr_cipher(self._mac_tag) return cipher.encrypt(plaintext)
Encrypt data with the key and the parameters set at initialization. A cipher object is stateful: once you have encrypted a message you cannot encrypt (or decrypt) another message using the same object. This method can be called only **once**. You cannot reuse an object for encrypting or decrypting other data with the same key. This function does not add any padding to the plaintext. :Parameters: plaintext : byte string The piece of data to encrypt. It can be of any length, but it cannot be empty. :Return: the encrypted data, as a byte string. It is as long as *plaintext*.
encrypt
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_siv.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_siv.py
MIT
def decrypt(self, ciphertext): """Decrypt data with the key and the parameters set at initialization. For SIV, decryption and verification must take place at the same point. This method shall not be used. Use `decrypt_and_verify` instead. """ raise TypeError("decrypt() not allowed for SIV mode." " Use decrypt_and_verify() instead.")
Decrypt data with the key and the parameters set at initialization. For SIV, decryption and verification must take place at the same point. This method shall not be used. Use `decrypt_and_verify` instead.
decrypt
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_siv.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_siv.py
MIT
def decrypt_and_verify(self, ciphertext, mac_tag): """Perform decryption and verification in one step. A cipher object is stateful: once you have decrypted a message you cannot decrypt (or encrypt) another message with the same object. You cannot reuse an object for encrypting or decrypting other data with the same key. This function does not remove any padding from the plaintext. :Parameters: ciphertext : byte string The piece of data to decrypt. It can be of any length. mac_tag : byte string This is the *binary* MAC, as received from the sender. :Return: the decrypted data (byte string). :Raises ValueError: if the MAC does not match. The message has been tampered with or the key is incorrect. """ if self.decrypt not in self._next: raise TypeError("decrypt() can only be called" " after initialization or an update()") self._next = [self.verify] # Take the MAC and start the cipher for decryption self._cipher = self._create_ctr_cipher(mac_tag) plaintext = self._cipher.decrypt(ciphertext) if self._nonce: self._kdf.update(self.nonce) if plaintext: self._kdf.update(plaintext) self.verify(mac_tag) return plaintext
Perform decryption and verification in one step. A cipher object is stateful: once you have decrypted a message you cannot decrypt (or encrypt) another message with the same object. You cannot reuse an object for encrypting or decrypting other data with the same key. This function does not remove any padding from the plaintext. :Parameters: ciphertext : byte string The piece of data to decrypt. It can be of any length. mac_tag : byte string This is the *binary* MAC, as received from the sender. :Return: the decrypted data (byte string). :Raises ValueError: if the MAC does not match. The message has been tampered with or the key is incorrect.
decrypt_and_verify
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_siv.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_siv.py
MIT
def _create_siv_cipher(factory, **kwargs): """Create a new block cipher, configured in Synthetic Initializaton Vector (SIV) mode. :Parameters: factory : object A symmetric cipher module from `Cryptodome.Cipher` (like `Cryptodome.Cipher.AES`). :Keywords: key : byte string The secret key to use in the symmetric cipher. It must be 32, 48 or 64 bytes long. If AES is the chosen cipher, the variants *AES-128*, *AES-192* and or *AES-256* will be used internally. nonce : byte string For deterministic encryption, it is not present. Otherwise, it is a value that must never be reused for encrypting message under this key. There are no restrictions on its length, but it is recommended to use at least 16 bytes. """ try: key = kwargs.pop("key") except KeyError, e: raise TypeError("Missing parameter: " + str(e)) nonce = kwargs.pop("nonce", None) return SivMode(factory, key, nonce, kwargs)
Create a new block cipher, configured in Synthetic Initializaton Vector (SIV) mode. :Parameters: factory : object A symmetric cipher module from `Cryptodome.Cipher` (like `Cryptodome.Cipher.AES`). :Keywords: key : byte string The secret key to use in the symmetric cipher. It must be 32, 48 or 64 bytes long. If AES is the chosen cipher, the variants *AES-128*, *AES-192* and or *AES-256* will be used internally. nonce : byte string For deterministic encryption, it is not present. Otherwise, it is a value that must never be reused for encrypting message under this key. There are no restrictions on its length, but it is recommended to use at least 16 bytes.
_create_siv_cipher
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Cipher/_mode_siv.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Cipher/_mode_siv.py
MIT
def update(self, data): """Continue hashing of a message by consuming the next chunk of data. Repeated calls are equivalent to a single call with the concatenation of all the arguments. In other words: >>> m.update(a); m.update(b) is equivalent to: >>> m.update(a+b) :Parameters: data : byte string The next chunk of the message being hashed. """ if self._digest_done and not self._update_after_digest: raise TypeError("You can only call 'digest' or 'hexdigest' on this object") expect_byte_string(data) result = _raw_blake2b_lib.blake2b_update(self._state.get(), data, c_size_t(len(data))) if result: raise ValueError("Error %d while hashing BLAKE2b data" % result) return self
Continue hashing of a message by consuming the next chunk of data. Repeated calls are equivalent to a single call with the concatenation of all the arguments. In other words: >>> m.update(a); m.update(b) is equivalent to: >>> m.update(a+b) :Parameters: data : byte string The next chunk of the message being hashed.
update
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Hash/BLAKE2b.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Hash/BLAKE2b.py
MIT
def digest(self): """Return the **binary** (non-printable) digest of the message that has been hashed so far. You cannot update the hash anymore after the first call to ``digest`` (or ``hexdigest``). :Return: A byte string of `digest_size` bytes. It may contain non-ASCII characters, including null bytes. """ bfr = create_string_buffer(64) result = _raw_blake2b_lib.blake2b_digest(self._state.get(), bfr) if result: raise ValueError("Error %d while creating BLAKE2b digest" % result) self._digest_done = True return get_raw_buffer(bfr)[:self.digest_size]
Return the **binary** (non-printable) digest of the message that has been hashed so far. You cannot update the hash anymore after the first call to ``digest`` (or ``hexdigest``). :Return: A byte string of `digest_size` bytes. It may contain non-ASCII characters, including null bytes.
digest
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Hash/BLAKE2b.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Hash/BLAKE2b.py
MIT
def verify(self, mac_tag): """Verify that a given **binary** MAC (computed by another party) is valid. :Parameters: mac_tag : byte string The expected MAC of the message. :Raises ValueError: if the MAC does not match. It means that the message has been tampered with or that the MAC key is incorrect. """ secret = get_random_bytes(16) mac1 = new(digest_bits=160, key=secret, data=mac_tag) mac2 = new(digest_bits=160, key=secret, data=self.digest()) if mac1.digest() != mac2.digest(): raise ValueError("MAC check failed")
Verify that a given **binary** MAC (computed by another party) is valid. :Parameters: mac_tag : byte string The expected MAC of the message. :Raises ValueError: if the MAC does not match. It means that the message has been tampered with or that the MAC key is incorrect.
verify
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Hash/BLAKE2b.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Hash/BLAKE2b.py
MIT
def new(self, **kwargs): """Return a new instance of a BLAKE2b hash object.""" if "digest_bytes" not in kwargs and "digest_bits" not in kwargs: kwargs["digest_bytes"] = self.digest_size return new(**kwargs)
Return a new instance of a BLAKE2b hash object.
new
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Hash/BLAKE2b.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Hash/BLAKE2b.py
MIT
def new(**kwargs): """Return a new instance of a BLAKE2b hash object. :Keywords: data : byte string The very first chunk of the message to hash. It is equivalent to an early call to `BLAKE2b_Hash.update()`. digest_bytes : integer The size of the digest, in bytes (1 to 64). digest_bits : integer The size of the digest, in bits (8 to 512, in steps of 8). key : byte string The key to use to compute the MAC (1 to 64 bytes). If not specified, no key will be used. update_after_digest : boolean Optional. By default, a hash object cannot be updated anymore after the digest is computed. When this flag is ``True``, such check is no longer enforced. :Return: A `BLAKE2b_Hash` object """ data = kwargs.pop("data", None) update_after_digest = kwargs.pop("update_after_digest", False) digest_bytes = kwargs.pop("digest_bytes", None) digest_bits = kwargs.pop("digest_bits", None) if None not in (digest_bytes, digest_bits): raise TypeError("Only one digest parameter must be provided") if (None, None) == (digest_bytes, digest_bits): raise TypeError("Digest size (bits, bytes) not provided") if digest_bytes is not None: if not (1 <= digest_bytes <= 64): raise ValueError("'digest_bytes' not in range 1..64") else: if not (8 <= digest_bits <= 512) or (digest_bits % 8): raise ValueError("'digest_bytes' not in range 8..512, " "with steps of 8") digest_bytes = digest_bits // 8 key = kwargs.pop("key", b("")) if len(key) > 64: raise ValueError("BLAKE2s key cannot exceed 64 bytes") if kwargs: raise TypeError("Unknown parameters: " + str(kwargs)) return BLAKE2b_Hash(data, key, digest_bytes, update_after_digest)
Return a new instance of a BLAKE2b hash object. :Keywords: data : byte string The very first chunk of the message to hash. It is equivalent to an early call to `BLAKE2b_Hash.update()`. digest_bytes : integer The size of the digest, in bytes (1 to 64). digest_bits : integer The size of the digest, in bits (8 to 512, in steps of 8). key : byte string The key to use to compute the MAC (1 to 64 bytes). If not specified, no key will be used. update_after_digest : boolean Optional. By default, a hash object cannot be updated anymore after the digest is computed. When this flag is ``True``, such check is no longer enforced. :Return: A `BLAKE2b_Hash` object
new
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Hash/BLAKE2b.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Hash/BLAKE2b.py
MIT
def new(self, **kwargs): """Return a new instance of a BLAKE2s hash object.""" if "digest_bytes" not in kwargs and "digest_bits" not in kwargs: kwargs["digest_bytes"] = self.digest_size return new(**kwargs)
Return a new instance of a BLAKE2s hash object.
new
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Hash/BLAKE2s.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Hash/BLAKE2s.py
MIT
def new(**kwargs): """Return a new instance of a BLAKE2s hash object. :Keywords: data : byte string The very first chunk of the message to hash. It is equivalent to an early call to `BLAKE2s_Hash.update()`. digest_bytes : integer The size of the digest, in bytes (1 to 32). digest_bits : integer The size of the digest, in bits (8 to 256, in steps of 8). key : byte string The key to use to compute the MAC (1 to 32 bytes). If not specified, no key will be used. update_after_digest : boolean Optional. By default, a hash object cannot be updated anymore after the digest is computed. When this flag is ``True``, such check is no longer enforced. :Return: A `BLAKE2s_Hash` object """ data = kwargs.pop("data", None) update_after_digest = kwargs.pop("update_after_digest", False) digest_bytes = kwargs.pop("digest_bytes", None) digest_bits = kwargs.pop("digest_bits", None) if None not in (digest_bytes, digest_bits): raise TypeError("Only one digest parameter must be provided") if (None, None) == (digest_bytes, digest_bits): raise TypeError("Digest size (bits, bytes) not provided") if digest_bytes is not None: if not (1 <= digest_bytes <= 32): raise ValueError("'digest_bytes' not in range 1..32") else: if not (8 <= digest_bits <= 256) or (digest_bits % 8): raise ValueError("'digest_bytes' not in range 8..256, " "with steps of 8") digest_bytes = digest_bits // 8 key = kwargs.pop("key", b("")) if len(key) > 32: raise ValueError("BLAKE2s key cannot exceed 32 bytes") if kwargs: raise TypeError("Unknown parameters: " + str(kwargs)) return BLAKE2s_Hash(data, key, digest_bytes, update_after_digest)
Return a new instance of a BLAKE2s hash object. :Keywords: data : byte string The very first chunk of the message to hash. It is equivalent to an early call to `BLAKE2s_Hash.update()`. digest_bytes : integer The size of the digest, in bytes (1 to 32). digest_bits : integer The size of the digest, in bits (8 to 256, in steps of 8). key : byte string The key to use to compute the MAC (1 to 32 bytes). If not specified, no key will be used. update_after_digest : boolean Optional. By default, a hash object cannot be updated anymore after the digest is computed. When this flag is ``True``, such check is no longer enforced. :Return: A `BLAKE2s_Hash` object
new
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Hash/BLAKE2s.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Hash/BLAKE2s.py
MIT
def __init__(self, key, msg=None, ciphermod=None, cipher_params=None): """Create a new CMAC object. :Parameters: key : byte string secret key for the CMAC object. The key must be valid for the underlying cipher algorithm. For instance, it must be 16 bytes long for AES-128. msg : byte string The very first chunk of the message to authenticate. It is equivalent to an early call to `update`. Optional. ciphermod : module A cipher module from `Cryptodome.Cipher`. The cipher's block size has to be 128 bits. It is recommended to use `Cryptodome.Cipher.AES`. cipher_params : dictionary Extra keywords to use when creating a new cipher. """ if ciphermod is None: raise TypeError("ciphermod must be specified (try AES)") self._key = key self._factory = ciphermod if cipher_params is None: self._cipher_params = {} else: self._cipher_params = dict(cipher_params) # Section 5.3 of NIST SP 800 38B and Appendix B if ciphermod.block_size == 8: const_Rb = 0x1B self._max_size = 8 * (2 ** 21) elif ciphermod.block_size == 16: const_Rb = 0x87 self._max_size = 16 * (2 ** 48) else: raise TypeError("CMAC requires a cipher with a block size" "of 8 or 16 bytes, not %d" % (ciphermod.block_size,)) # Size of the final MAC tag, in bytes self.digest_size = ciphermod.block_size self._mac_tag = None # Compute sub-keys zero_block = bchr(0) * ciphermod.block_size cipher = ciphermod.new(key, ciphermod.MODE_ECB, **self._cipher_params) l = cipher.encrypt(zero_block) if bord(l[0]) & 0x80: self._k1 = _shift_bytes(l, const_Rb) else: self._k1 = _shift_bytes(l) if bord(self._k1[0]) & 0x80: self._k2 = _shift_bytes(self._k1, const_Rb) else: self._k2 = _shift_bytes(self._k1) # Initialize CBC cipher with zero IV self._cbc = ciphermod.new(key, ciphermod.MODE_CBC, zero_block, **self._cipher_params) # Cache for outstanding data to authenticate self._cache = b("") # Last two pieces of ciphertext produced self._last_ct = self._last_pt = zero_block self._before_last_ct = None # Counter for total message size self._data_size = 0 if msg: self.update(msg)
Create a new CMAC object. :Parameters: key : byte string secret key for the CMAC object. The key must be valid for the underlying cipher algorithm. For instance, it must be 16 bytes long for AES-128. msg : byte string The very first chunk of the message to authenticate. It is equivalent to an early call to `update`. Optional. ciphermod : module A cipher module from `Cryptodome.Cipher`. The cipher's block size has to be 128 bits. It is recommended to use `Cryptodome.Cipher.AES`. cipher_params : dictionary Extra keywords to use when creating a new cipher.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Hash/CMAC.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Hash/CMAC.py
MIT
def update(self, msg): """Continue authentication of a message by consuming the next chunk of data. Repeated calls are equivalent to a single call with the concatenation of all the arguments. In other words: >>> m.update(a); m.update(b) is equivalent to: >>> m.update(a+b) :Parameters: msg : byte string The next chunk of the message being authenticated """ self._data_size += len(msg) if len(self._cache) > 0: filler = min(self.digest_size - len(self._cache), len(msg)) self._cache += msg[:filler] if len(self._cache) < self.digest_size: return self msg = msg[filler:] self._update(self._cache) self._cache = b("") update_len, remain = divmod(len(msg), self.digest_size) update_len *= self.digest_size if remain > 0: self._update(msg[:update_len]) self._cache = msg[update_len:] else: self._update(msg) self._cache = b("") return self
Continue authentication of a message by consuming the next chunk of data. Repeated calls are equivalent to a single call with the concatenation of all the arguments. In other words: >>> m.update(a); m.update(b) is equivalent to: >>> m.update(a+b) :Parameters: msg : byte string The next chunk of the message being authenticated
update
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Hash/CMAC.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Hash/CMAC.py
MIT
def _update(self, data_block): """Update a block aligned to the block boundary""" if len(data_block) == 0: return assert len(data_block) % self.digest_size == 0 ct = self._cbc.encrypt(data_block) if len(data_block) == self.digest_size: self._before_last_ct = self._last_ct else: self._before_last_ct = ct[-self.digest_size * 2:-self.digest_size] self._last_ct = ct[-self.digest_size:] self._last_pt = data_block[-self.digest_size:]
Update a block aligned to the block boundary
_update
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Hash/CMAC.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Hash/CMAC.py
MIT
def copy(self): """Return a copy ("clone") of the MAC object. The copy will have the same internal state as the original MAC object. This can be used to efficiently compute the MAC of strings that share a common initial substring. :Returns: A `CMAC` object """ obj = CMAC(self._key, ciphermod=self._factory, cipher_params=self._cipher_params) obj._cbc = self._factory.new(self._key, self._factory.MODE_CBC, self._last_ct, **self._cipher_params) for m in ['_mac_tag', '_last_ct', '_before_last_ct', '_cache', '_data_size', '_max_size']: setattr(obj, m, getattr(self, m)) return obj
Return a copy ("clone") of the MAC object. The copy will have the same internal state as the original MAC object. This can be used to efficiently compute the MAC of strings that share a common initial substring. :Returns: A `CMAC` object
copy
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Hash/CMAC.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Hash/CMAC.py
MIT
def digest(self): """Return the **binary** (non-printable) MAC of the message that has been authenticated so far. This method does not change the state of the MAC object. You can continue updating the object after calling this function. :Return: A byte string of `digest_size` bytes. It may contain non-ASCII characters, including null bytes. """ if self._mac_tag is not None: return self._mac_tag if self._data_size > self._max_size: raise ValueError("MAC is unsafe for this message") if len(self._cache) == 0 and self._before_last_ct is not None: ## Last block was full pt = strxor(strxor(self._before_last_ct, self._k1), self._last_pt) else: ## Last block is partial (or message length is zero) ext = self._cache + bchr(0x80) +\ bchr(0) * (self.digest_size - len(self._cache) - 1) pt = strxor(strxor(self._last_ct, self._k2), ext) cipher = self._factory.new(self._key, self._factory.MODE_ECB, **self._cipher_params) self._mac_tag = cipher.encrypt(pt) return self._mac_tag
Return the **binary** (non-printable) MAC of the message that has been authenticated so far. This method does not change the state of the MAC object. You can continue updating the object after calling this function. :Return: A byte string of `digest_size` bytes. It may contain non-ASCII characters, including null bytes.
digest
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Hash/CMAC.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Hash/CMAC.py
MIT
def hexdigest(self): """Return the **printable** MAC of the message that has been authenticated so far. This method does not change the state of the MAC object. :Return: A string of 2* `digest_size` bytes. It contains only hexadecimal ASCII digits. """ return "".join(["%02x" % bord(x) for x in tuple(self.digest())])
Return the **printable** MAC of the message that has been authenticated so far. This method does not change the state of the MAC object. :Return: A string of 2* `digest_size` bytes. It contains only hexadecimal ASCII digits.
hexdigest
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Hash/CMAC.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Hash/CMAC.py
MIT
def __init__(self, key, msg=b(""), digestmod=None): """Create a new HMAC object. :Parameters: key : byte string secret key for the MAC object. It must be long enough to match the expected security level of the MAC. However, there is no benefit in using keys longer than the `digest_size` of the underlying hash algorithm. msg : byte string The very first chunk of the message to authenticate. It is equivalent to an early call to `update()`. Optional. :Parameter digestmod: The hash algorithm the HMAC is based on. Default is `Cryptodome.Hash.MD5`. :Type digestmod: A hash module or object instantiated from `Cryptodome.Hash` """ if digestmod is None: digestmod = MD5 if msg is None: msg = b("") #: Size of the MAC tag self.digest_size = digestmod.digest_size self._digestmod = digestmod try: if len(key) <= digestmod.block_size: # Step 1 or 2 key_0 = key + bchr(0) * (digestmod.block_size - len(key)) else: # Step 3 hash_k = digestmod.new(key).digest() key_0 = hash_k + bchr(0) * (digestmod.block_size - len(hash_k)) except AttributeError: # Not all hash types have "block_size" raise ValueError("Hash type incompatible to HMAC") # Step 4 key_0_ipad = strxor(key_0, bchr(0x36) * len(key_0)) # Start step 5 and 6 self._inner = digestmod.new(key_0_ipad) self._inner.update(msg) # Step 7 key_0_opad = strxor(key_0, bchr(0x5c) * len(key_0)) # Start step 8 and 9 self._outer = digestmod.new(key_0_opad)
Create a new HMAC object. :Parameters: key : byte string secret key for the MAC object. It must be long enough to match the expected security level of the MAC. However, there is no benefit in using keys longer than the `digest_size` of the underlying hash algorithm. msg : byte string The very first chunk of the message to authenticate. It is equivalent to an early call to `update()`. Optional. :Parameter digestmod: The hash algorithm the HMAC is based on. Default is `Cryptodome.Hash.MD5`. :Type digestmod: A hash module or object instantiated from `Cryptodome.Hash`
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Hash/HMAC.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Hash/HMAC.py
MIT
def copy(self): """Return a copy ("clone") of the MAC object. The copy will have the same internal state as the original MAC object. This can be used to efficiently compute the MAC of strings that share a common initial substring. :Returns: An `HMAC` object """ new_hmac = HMAC(b("fake key"), digestmod=self._digestmod) # Syncronize the state new_hmac._inner = self._inner.copy() new_hmac._outer = self._outer.copy() return new_hmac
Return a copy ("clone") of the MAC object. The copy will have the same internal state as the original MAC object. This can be used to efficiently compute the MAC of strings that share a common initial substring. :Returns: An `HMAC` object
copy
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Hash/HMAC.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Hash/HMAC.py
MIT
def digest(self): """Return the **binary** (non-printable) MAC of the message that has been authenticated so far. This method does not change the state of the MAC object. You can continue updating the object after calling this function. :Return: A byte string of `digest_size` bytes. It may contain non-ASCII characters, including null bytes. """ frozen_outer_hash = self._outer.copy() frozen_outer_hash.update(self._inner.digest()) return frozen_outer_hash.digest()
Return the **binary** (non-printable) MAC of the message that has been authenticated so far. This method does not change the state of the MAC object. You can continue updating the object after calling this function. :Return: A byte string of `digest_size` bytes. It may contain non-ASCII characters, including null bytes.
digest
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Hash/HMAC.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Hash/HMAC.py
MIT
def digest(self): """Return the **binary** (non-printable) digest of the message that has been hashed so far. You cannot update the hash anymore after the first call to ``digest`` (or ``hexdigest``). :Return: A byte string of `digest_size` bytes. It may contain non-ASCII characters, including null bytes. """ self._digest_done = True bfr = create_string_buffer(self.digest_size) result = _raw_keccak_lib.keccak_digest(self._state.get(), bfr, c_size_t(self.digest_size)) if result: raise ValueError("Error %d while squeezing keccak" % result) return get_raw_buffer(bfr)
Return the **binary** (non-printable) digest of the message that has been hashed so far. You cannot update the hash anymore after the first call to ``digest`` (or ``hexdigest``). :Return: A byte string of `digest_size` bytes. It may contain non-ASCII characters, including null bytes.
digest
python
mchristopher/PokemonGo-DesktopMap
app/pylibs/osx64/Cryptodome/Hash/keccak.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/Cryptodome/Hash/keccak.py
MIT