Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Python implementation of the spectral (discrete Fourier transform) cryptographic tests for randomness
def spectral(self, bin_data: str):
Note that this description is taken from the NIST documentation [1]
The focus of this test is the peak heights in the Discrete Fourier Transform of the sequence. The purpose of
this test is to detect periodic features (i.e., repetitive patterns that are near each other) in the tested
sequence that would indicate a deviation from the assumption of randomness. The intention is to detect whether
the number of peaks exceeding the 95 % threshold is significantly different than 5 %.
:param bin_data: a binary string
:return: the p-value from the test
n = len(bin_data)
plus_minus_one = []
for char in bin_data:
if char == '0':
elif char == '1':
# Product discrete fourier transform of plus minus one
s = sff.fft(plus_minus_one)
modulus = numpy.abs(s[0:n / 2])
tau = numpy.sqrt(numpy.log(1 / 0.05) * n)
# Theoretical number of peaks
count_n0 = 0.95 * (n / 2)
# Count the number of actual peaks m > T
count_n1 = len(numpy.where(modulus < tau)[0])
# Calculate d and return the p value statistic
d = (count_n1 - count_n0) / numpy.sqrt(n * 0.95 * 0.05 / 4)
p_val = spc.erfc(abs(d) / numpy.sqrt(2))
return p_val
Copy link

i thankfull to you for nist codes.
i have a quadtion from you. can you get me class that's contain this function?
Unfortunatly i cannot load ssf and spc modules ....

You can find spc here and ssf here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment