valueerror: signal number 32 out of range
时间: 2023-06-05 16:47:21 浏览: 344
这个错误是由于信号编号超出了范围所引起的。信号编号是一个整数,用于在进程之间传递信息。在Python中,信号编号通常是一个小于等于31的整数。如果信号编号超出了这个范围,就会出现这个错误。可能的原因包括使用了错误的信号编号或者信号编号被修改了。要解决这个问题,可以检查代码中使用的信号编号是否正确,并确保不会修改信号编号。
相关问题
修改代码from Crypto.Util.number import * from Crypto.PublicKey import RSA from hashlib import sha256 import random, os, signal, string def proof_of_work(): random.seed(os.urandom(8)) proof = ''.join([random.choice(string.ascii_letters+string.digits) for _ in range(20)]) _hexdigest = sha256(proof.encode()).hexdigest() print(f"sha256(XXXX+{proof[4:]}) == {_hexdigest}") print('Give me XXXX: ') x = input() if len(x) != 4 or sha256(x.encode()+proof[4:].encode()).hexdigest() != _hexdigest: print('Wrong PoW') return False return True if not proof_of_work(): exit(1) signal.alarm(10) print("Give me a bad RSA keypair.") try: p = int(input('p = ')) q = int(input('q = ')) assert p > 0 assert q > 0 assert p != q assert p.bit_length() == 512 assert q.bit_length() == 512 assert isPrime(p) assert isPrime(q) n = p * q e = 65537 assert p % e != 1 assert q % e != 1 d = inverse(e, (p-1)*(q-1)) except: print("Invalid params") exit(2) try: key = RSA.construct([n,e,d,p,q]) print("This is not a bad RSA keypair.") exit(3) except KeyboardInterrupt: print("Hacker detected.") exit(4) except ValueError: print("How could this happen?") from secret import flag print(flag)
为了修复这个程序的漏洞,可以加入一个时间限制,如果用户输入的参数过大导致程序运行时间过长,程序会自动退出。代码如下所示:
```python
from Crypto.Util.number import *
from Crypto.PublicKey import RSA
from hashlib import sha256
import random, os, signal, string
def proof_of_work():
random.seed(os.urandom(8))
proof = ''.join([random.choice(string.ascii_letters+string.digits) for _ in range(20)])
_hexdigest = sha256(proof.encode()).hexdigest()
print(f"sha256(XXXX+{proof[4:]}) == {_hexdigest}")
print('Give me XXXX: ')
x = input()
if len(x) != 4 or sha256(x.encode()+proof[4:].encode()).hexdigest() != _hexdigest:
print('Wrong PoW')
return False
return True
if not proof_of_work():
exit(1)
signal.alarm(10)
print("Give me a bad RSA keypair.")
try:
p = int(input('p = '))
q = int(input('q = '))
assert p > 0
assert q > 0
assert p != q
assert p.bit_length() == 512
assert q.bit_length() == 512
assert isPrime(p)
assert isPrime(q)
n = p * q
e = 65537
assert p % e != 1
assert q % e != 1
d = inverse(e, (p-1)*(q-1))
key = RSA.construct([n,e,d,p,q])
print("This is not a bad RSA keypair.")
exit(3)
except AssertionError:
print("Invalid params")
exit(2)
except KeyboardInterrupt:
print("Time limit exceeded")
exit(4)
except ValueError:
print("How could this happen?")
from secret import flag
print(flag)
```
在新代码中,我们使用了 signal 库中的 alarm 函数,将程序的运行时间限制在 10 秒钟内。当用户输入的参数过大导致程序运行时间超过 10 秒时,程序会自动退出,并输出 "Time limit exceeded"。
matlab代码function probeData(varargin)if (nargin == 1) settings = deal(varargin{1}); fileNameStr = settings.fileName; elseif (nargin == 2) [fileNameStr, settings] = deal(varargin{1:2}); if ~ischar(fileNameStr) error('File name must be a string'); end else error('Incorect number of arguments'); end[fid, message] = fopen(fileNameStr, 'rb'); if (fid > 0) % Move the starting point of processing. Can be used to start the % signal processing at any point in the data record (e.g. for long % records). fseek(fid, settings.skipNumberOfBytes, 'bof'); % Find number of samples per spreading code samplesPerCode = round(settings.samplingFreq / ... (settings.codeFreqBasis / settings.codeLength)); if (settings.fileType==1) dataAdaptCoeff=1; else dataAdaptCoeff=2; end % Read 100ms of signal [data, count] = fread(fid, [1, dataAdaptCoeff100samplesPerCode], settings.dataType); fclose(fid); if (count < dataAdaptCoeff100samplesPerCode) % The file is to short error('Could not read enough data from the data file.'); end %--- Initialization --------------------------------------------------- figure(100); clf(100); timeScale = 0 : 1/settings.samplingFreq : 5e-3; %--- Time domain plot ------------------------------------------------- if (settings.fileType==1) subplot(2, 2, 3); plot(1000 * timeScale(1:round(samplesPerCode/2)), ... data(1:round(samplesPerCode/2))); axis tight; grid on; title ('Time domain plot'); xlabel('Time (ms)'); ylabel('Amplitude'); else data=data(1:2:end) + 1i .* data(2:2:end); subplot(3, 2, 4); plot(1000 * timeScale(1:round(samplesPerCode/2)), ... real(data(1:round(samplesPerCode/2)))); axis tight; grid on; title ('Time domain plot (I)'); xlabel('Time (ms)'); ylabel('Amplitude'); subplot(3, 2, 3); plot(1000 * timeScale(1:round(samplesPerCode/2)), ... imag(data(1:round(samplesPerCode/2)))); axis tight; grid on; title ('Time domain plot (Q)'); xlabel('Time (ms)'); ylabel('Amplitude'); end %--- Frequency domain plot -------------------------------------------- if (settings.fileType==1) %Real Data subplot(2,2,1:2); pwelch(data, 32768, 2048, 32768, settings.samplingFreq/1e6) else % I/Q Data subplot(3,2,1:2); [sigspec,freqv]=pwelch(data, 32768, 2048, 32768, settings.samplingFreq,'twosided'); plot(([-(freqv(length(freqv)/2:-1:1));freqv(1:length(freqv)/2)])/1e6, ... 10*log10([sigspec(length(freqv)/2+1:end); sigspec(1:length(freqv)/2)])); end axis tight; grid on; title ('Frequency domain plot'); xlabel('Frequency (MHz)'); ylabel('Magnitude'); %--- Histogram -------------------------------------------------------- if (settings.fileType == 1) subplot(2, 2, 4); hist(data, -128:128) dmax = max(abs(data)) + 1; axis tight; adata = axis; axis([-dmax dmax adata(3) adata(4)]); grid on; title ('Histogram'); xlabel('Bin'); ylabel('Number in bin'); else subplot(3, 2, 6); hist(real(data), -128:128) dmax = max(abs(data)) + 1; axis tight; adata = axis; axis([-dmax dmax adata(3) adata(4)]); grid on; title ('Histogram (I)'); xlabel('Bin'); ylabel('Number in bin'); subplot(3, 2, 5); hist(imag(data), -128:128) dmax = max(abs(data)) + 1; axis tight; adata = axis; axis([-dmax dmax adata(3) adata(4)]); grid on; title ('Histogram (Q)'); xlabel('Bin'); ylabel('Number in bin'); end else %=== Error while opening the data file ================================ error('Unable to read file %s: %s.', fileNameStr, message); end % if (fid > 0)翻译成python
抱歉,由于MATLAB和Python的语法和结构有所不同,将MATLAB代码翻译成Python代码需要对代码进行一定程度的重构和修改。以下是一个可能的Python代码实现,仅供参考:
```python
import numpy as np
import matplotlib.pyplot as plt
def probeData(*args):
if len(args) == 1:
settings = args[0]
fileNameStr = settings['fileName']
elif len(args) == 2:
fileNameStr, settings = args
if not isinstance(fileNameStr, str):
raise ValueError('File name must be a string')
else:
raise ValueError('Incorrect number of arguments')
with open(fileNameStr, 'rb') as fid:
# Move the starting point of processing.
# Can be used to start the signal processing at any point in the data record (e.g. for long records).
fid.seek(settings['skipNumberOfBytes'], 0)
# Find number of samples per spreading code
samplesPerCode = round(settings['samplingFreq'] / (settings['codeFreqBasis'] / settings['codeLength']))
if settings['fileType'] == 1:
dataAdaptCoeff = 1
else:
dataAdaptCoeff = 2
# Read 100ms of signal
data = np.fromfile(fid, dtype=settings['dataType'], count=dataAdaptCoeff*100*samplesPerCode)
fid.close()
if len(data) < dataAdaptCoeff*100*samplesPerCode:
# The file is too short
raise ValueError('Could not read enough data from the data file.')
#--- Initialization ---------------------------------------------------
plt.figure(100)
plt.clf()
timeScale = np.arange(0, 5e-3, 1/settings['samplingFreq'])
#--- Time domain plot -------------------------------------------------
if settings['fileType'] == 1:
plt.subplot(2, 2, 3)
plt.plot(1000*timeScale[:round(samplesPerCode/2)], data[:round(samplesPerCode/2)])
plt.axis('tight')
plt.grid(True)
plt.title('Time domain plot')
plt.xlabel('Time (ms)')
plt.ylabel('Amplitude')
else:
data = data[::2] + 1j*data[1::2]
plt.subplot(3, 2, 4)
plt.plot(1000*timeScale[:round(samplesPerCode/2)], np.real(data[:round(samplesPerCode/2)]))
plt.axis('tight')
plt.grid(True)
plt.title('Time domain plot (I)')
plt.xlabel('Time (ms)')
plt.ylabel('Amplitude')
plt.subplot(3, 2, 3)
plt.plot(1000*timeScale[:round(samplesPerCode/2)], np.imag(data[:round(samplesPerCode/2)]))
plt.axis('tight')
plt.grid(True)
plt.title('Time domain plot (Q)')
plt.xlabel('Time (ms)')
plt.ylabel('Amplitude')
#--- Frequency domain plot --------------------------------------------
if settings['fileType'] == 1:
#Real Data
plt.subplot(2, 2, 1)
plt.subplot(2, 2, 2)
f, Pxx = signal.welch(data, fs=settings['samplingFreq'], nperseg=32768, noverlap=2048, nfft=32768)
plt.plot(f/1e6, 10*np.log10(Pxx))
else:
# I/Q Data
plt.subplot(3, 2, 1)
plt.subplot(3, 2, 2)
f, Pxx = signal.welch(data, fs=settings['samplingFreq'], nperseg=32768, noverlap=2048, nfft=32768, return_onesided=False)
plt.plot((np.concatenate((-f[len(f)//2:], f[:len(f)//2])))/1e6, 10*np.log10(np.concatenate((Pxx[len(Pxx)//2:], Pxx[:len(Pxx)//2]))))
plt.axis('tight')
plt.grid(True)
plt.title('Frequency domain plot')
plt.xlabel('Frequency (MHz)')
plt.ylabel('Magnitude')
#--- Histogram --------------------------------------------------------
if settings['fileType'] == 1:
plt.subplot(2, 2, 4)
plt.hist(data, bins=np.arange(-128, 129))
dmax = np.max(np.abs(data)) + 1
plt.axis([-dmax, dmax, *plt.axis()[2:]])
plt.grid(True)
plt.title('Histogram')
plt.xlabel('Bin')
plt.ylabel('Number in bin')
else:
plt.subplot(3, 2, 6)
plt.hist(np.real(data), bins=np.arange(-128, 129))
dmax = np.max(np.abs(data)) + 1
plt.axis([-dmax, dmax, *plt.axis()[2:]])
plt.grid(True)
plt.title('Histogram (I)')
plt.xlabel('Bin')
plt.ylabel('Number in bin')
plt.subplot(3, 2, 5)
plt.hist(np.imag(data), bins=np.arange(-128, 129))
dmax = np.max(np.abs(data)) + 1
plt.axis([-dmax, dmax, *plt.axis()[2:]])
plt.grid(True)
plt.title('Histogram (Q)')
plt.xlabel('Bin')
plt.ylabel('Number in bin')
```
阅读全文