考虑下面的代码
SO derive key and iv from passphrase like OpenSSL for 3DES
password: cfe4ec9fcec928d51d243855a094b05ebb7bc870
salt (hex) length: 8 data: 3aa6a64f87764632
key (hex) length: 24 data: 6a8e552a81763b15ec9e1430fab774c7b5113afd89e6f03c
iv (hex) length: 8 data: de2cfc91dc61e734
代码主要做的是首先创建一个大小为 2 乘以 12(p 乘以 T)的矩阵,并用零填充它。然后的目的是用相同的向量均匀地填充矩阵,即如果我们有 m=2(如代码所示),矩阵被分成 3 个不同的部分。请注意,我首先创建了一个字典 beta_b,其中包含要稍后填充的 m+1 个片段。因此,在我的玩具示例中,我有 m=2,T=12,即 3 件尺寸为 4 的件。如果我们关注 t<4 时出现的第一件,那么 # source get_key_and_iv by Tom Tang
# https://gist.github.com/tly1980/b6c2cc10bb35cb4446fb6ccf5ee5efbc
# ================================================================
# get_key_and_iv
# ================================================================
def get_key_and_iv(password, salt, klen=32, ilen=16, msgdgst='md5'):
'''
Derive the key and the IV from the given password and salt.
This is a niftier implementation than my direct transliteration of
the C++ code although I modified to support different digests.
CITATION: http://stackoverflow.com/questions/13907841/implement-openssl-aes-encryption-in-python
@param password The password to use as the seed.
@param salt The salt.
@param klen The key length.
@param ilen The initialization vector length.
@param msgdgst The message digest algorithm to use.
'''
# equivalent to:
# from hashlib import <mdi> as mdf
# from hashlib import md5 as mdf
# from hashlib import sha512 as mdf
mdf = getattr(__import__('hashlib', fromlist=[msgdgst]), msgdgst)
password = password.encode('ascii', 'ignore') # convert to ASCII
try:
maxlen = klen + ilen
keyiv = mdf(password + salt).digest()
tmp = [keyiv]
while len(tmp) < maxlen:
tmp.append( mdf(tmp[-1] + password + salt).digest() )
keyiv += tmp[-1] # append the last byte
key = keyiv[:klen]
iv = keyiv[klen:klen+ilen]
return key, iv
except UnicodeDecodeError:
return None, None
def bytesToHex(input):
return input.hex()
print("SO derive key and iv from passphrase like OpenSSL for 3DES")
password = 'cfe4ec9fcec928d51d243855a094b05ebb7bc870'
salt = bytes.fromhex('3AA6A64F87764632')
key, iv = get_key_and_iv(password, salt, 24, 8)
print("password: " + password)
print("salt (hex) length: " + str(len(salt)) + " data: " + bytesToHex(salt))
print("key (hex) length: " + str(len(key)) + " data: " + bytesToHex(key))
print("iv (hex) length: " + str(len(iv)) + " data: " + bytesToHex(iv))
直到 {{1} } 只是与 beta_1 相等。然后我们继续第二部分,它从 import numpy as np
import matplotlib.pyplot as plt
import math
p=2
T=12
n=10
m=2
beta = np.zeros((p,T))
beta_b = {}
for i in range(m+1):
beta_b["beta_" + str(i)] = np.random.normal(0,1,p)
for t in range(T):
if t < math.floor(T/(m+1)):
beta[0:p,t] = beta_b["beta_" + str(0)]
elif math.floor(T/(m+1))<=t<math.floor(2*(T/(m+1))):
beta[0:p,t] = beta_b["beta_" + str(1)]
else:
beta[0:p,t] = beta_b["beta_" + str(2)]
开始直到 beta[0:p,0]
并被均衡为 beta_2。最后一块从 beta[0:p,3]
开始直到结束,与最终的 beta_3 相等。
我的问题是,对于 beta[0:p,4]
的任意选择,有没有一种方法可以巧妙地编写代码而不必添加许多 beta[0:p,7]
语句?如果 m=4,我需要手动添加一个 beta[0:p,8]
语句告诉 python 我正在考虑哪些块。