本文整理匯總了Python中Crypto.PublicKey.RSA.construct方法的典型用法代碼示例。如果您正苦於以下問題:Python RSA.construct方法的具體用法?Python RSA.construct怎麽用?Python RSA.construct使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類Crypto.PublicKey.RSA
的用法示例。
在下文中一共展示了RSA.construct方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: testSign1
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import construct [as 別名]
def testSign1(self):
for i in range(len(self._testData)):
# Build the key
comps = [ long(rws(self._testData[i][0][x]),16) for x in ('n','e','d') ]
key = MyKey(RSA.construct(comps))
# Hash function
h = self._testData[i][4].new()
# Data to sign
h.update(t2b(self._testData[i][1]))
# Salt
test_salt = t2b(self._testData[i][3])
key._randfunc = lambda N: test_salt
# The real test
signer = PKCS.new(key)
self.failUnless(signer.can_sign())
s = signer.sign(h)
self.assertEqual(s, t2b(self._testData[i][2]))
示例2: testVerify1
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import construct [as 別名]
def testVerify1(self):
for i in range(len(self._testData)):
# Build the key
comps = [ long(rws(self._testData[i][0][x]),16) for x in ('n','e') ]
key = MyKey(RSA.construct(comps))
# Hash function
h = self._testData[i][4].new()
# Data to sign
h.update(t2b(self._testData[i][1]))
# Salt
test_salt = t2b(self._testData[i][3])
# The real test
key._randfunc = lambda N: test_salt
verifier = PKCS.new(key)
self.failIf(verifier.can_sign())
result = verifier.verify(h, t2b(self._testData[i][2]))
self.failUnless(result)
示例3: testSign1
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import construct [as 別名]
def testSign1(self):
for i in range(len(self._testData)):
row = self._testData[i]
# Build the key
if isStr(row[0]):
key = RSA.importKey(row[0])
else:
comps = [ long(rws(row[0][x]),16) for x in ('n','e','d') ]
key = RSA.construct(comps)
h = row[3].new()
# Data to sign can either be in hex form or not
try:
h.update(t2b(row[1]))
except:
h.update(b(row[1]))
# The real test
signer = PKCS.new(key)
self.failUnless(signer.can_sign())
s = signer.sign(h)
self.assertEqual(s, t2b(row[2]))
示例4: testVerify1
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import construct [as 別名]
def testVerify1(self):
for i in range(len(self._testData)):
row = self._testData[i]
# Build the key
if isStr(row[0]):
key = RSA.importKey(row[0]).publickey()
else:
comps = [ long(rws(row[0][x]),16) for x in ('n','e') ]
key = RSA.construct(comps)
h = row[3].new()
# Data to sign can either be in hex form or not
try:
h.update(t2b(row[1]))
except:
h.update(b(row[1]))
# The real test
verifier = PKCS.new(key)
self.failIf(verifier.can_sign())
result = verifier.verify(h, t2b(row[2]))
self.failUnless(result)
示例5: testEncrypt1
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import construct [as 別名]
def testEncrypt1(self):
# Verify encryption using all test vectors
for test in self._testData:
# Build the key
comps = [ long(rws(test[0][x]),16) for x in ('n','e') ]
key = RSA.construct(comps)
# RNG that takes its random numbers from a pool given
# at initialization
class randGen:
def __init__(self, data):
self.data = data
self.idx = 0
def __call__(self, N):
r = self.data[self.idx:N]
self.idx += N
return r
# The real test
key._randfunc = randGen(t2b(test[3]))
cipher = PKCS.new(key, test[4])
ct = cipher.encrypt(t2b(test[1]))
self.assertEqual(ct, t2b(test[2]))
示例6: encryptPassword
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import construct [as 別名]
def encryptPassword(email, password):
gdpk = "AAAAgMom/1a/v0lblO2Ubrt60J2gcuXSljGFQXgcyZWveWLEwo6prwgi3iJIZdodyhKZQrNWp5nKJ3srRXcUW+F1BD3baEVGcmEgqaLZUNBjm057pKRI16kB0YppeGx5qIQ5QjKzsR8ETQbKLNWgRY0QRNVz34kMJR3P/LgHax/6rmf5AAAAAwEAAQ=="
binaryKey = b64decode(gdpk).encode('hex')
half = binaryKey[8:264]
modulus = long(half, 16)
half = binaryKey[272:278]
exponent = long(half, 16)
sha1hash = sha1(b64decode(gdpk)).digest()
signature = "00" + sha1hash[:4].encode('hex')
key = RSA.construct((modulus, exponent))
cipher = PKCS1_OAEP.new(key)
plain = email + "\x00" + password
encrypted = cipher.encrypt(plain).encode('hex')
ste = signature + encrypted
output = unhexlify(ste)
encryptedPassword = b64encode(output).encode('ascii').replace("+","-").replace("/","_")
return encryptedPassword
示例7: getDSAKey
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import construct [as 別名]
def getDSAKey(self):
"""
Return a PyCrypto DSA key to support the tests.
@return: The DSA key to support the tests.
@rtype: C{Crypto.PublicKey.DSA}
"""
# Use lazy import as PyCrypto will be deprecated.
from Crypto.PublicKey import DSA
return DSA.construct((
keydata.DSAData['y'],
keydata.DSAData['g'],
keydata.DSAData['p'],
keydata.DSAData['q'],
keydata.DSAData['x'],
))
示例8: test_keyObjectSetRSAPublic
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import construct [as 別名]
def test_keyObjectSetRSAPublic(self):
"""
Setting the L{keys.Key.keyObject} property to a PyCrypto public RSA key
instance updates the internal key.
"""
key = keys.Key.fromString(keydata.publicDSA_openssh)
newPyCryptoKey = Crypto.PublicKey.RSA.construct((
keydata.RSAData['n'],
keydata.RSAData['e'],
))
self.assertEqual('DSA', key.type())
key.keyObject = newPyCryptoKey
[warning] = self.flushWarnings([
KeyKeyObjectTests.test_keyObjectSetRSAPublic])
self.assertIs(warning['category'], DeprecationWarning)
self.assertEqual('RSA', key.type())
self.assertEqual({
'n': keydata.RSAData['n'],
'e': keydata.RSAData['e'],
},
key.data())
示例9: test_keyObjectSetDSAPublic
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import construct [as 別名]
def test_keyObjectSetDSAPublic(self):
"""
Setting the L{keys.Key.keyObject} property to a PyCrypto public DSA key
instance updates the internal key.
"""
key = keys.Key.fromString(keydata.publicRSA_openssh)
newPyCryptoKey = Crypto.PublicKey.DSA.construct((
keydata.DSAData['y'],
keydata.DSAData['g'],
keydata.DSAData['p'],
keydata.DSAData['q'],
))
self.assertEqual('RSA', key.type())
key.keyObject = newPyCryptoKey
self.assertEqual('DSA', key.type())
self.assertEqual({
'y': keydata.DSAData['y'],
'g': keydata.DSAData['g'],
'p': keydata.DSAData['p'],
'q': keydata.DSAData['q'],
},
key.data())
示例10: test_constructorPyCrypto
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import construct [as 別名]
def test_constructorPyCrypto(self):
"""
Passing a PyCrypto key object to L{keys.Key} is deprecated.
"""
pycryptoKey = Crypto.PublicKey.RSA.construct((
keydata.RSAData['n'],
keydata.RSAData['e']))
key = self.callDeprecated(
(Version('Twisted', 16, 0, 0),
'passing a cryptography key object'),
keys.Key,
pycryptoKey)
self.assertEqual('RSA', key.type())
self.assertEqual({
'n': keydata.RSAData['n'],
'e': keydata.RSAData['e'],
},
key.data())
示例11: signer
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import construct [as 別名]
def signer(M):
message = M
p = getPrime(512)
q = getPrime(512)
n = p*q
phin = (p-1)*(q-1)
e = 65537
assert GCD(e, phin) == 1
key = RSA.construct((long(n), long(e)))
h = MD5.new(M)
M = PKCS1_v1_5.EMSA_PKCS1_V1_5_ENCODE(h, size(key.n)/8)
print "Padded M: ", M.encode("hex")
M = bytes_to_long(M)
d = inverse(e, phin)
s = pow(M, d, n)
s = long_to_bytes(s)
return (key, s, message)
示例12: auth_digital
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import construct [as 別名]
def auth_digital(self, title_id, title_version, device_token, ticket):
self.verify_ticket(ticket, title_id)
plain_key = get_random_bytes(16)
aes = AES.new(plain_key, AES.MODE_CBC, iv=bytes(16))
encrypted_ticket = aes.encrypt(pad(ticket, 16))
rsa_key = RSA.construct((RSA_MODULUS, RSA_EXPONENT))
rsa = PKCS1_OAEP.new(rsa_key, SHA256)
encrypted_key = rsa.encrypt(plain_key)
req = HTTPRequest.post("/v3/application_auth_token")
req.form["application_id"] = "%016x" %title_id
req.form["application_version"] = "%08x" %title_version
req.form["device_auth_token"] = device_token
req.form["media_type"] = "DIGITAL"
req.form["cert"] = b64encode(encrypted_ticket)
req.form["cert_key"] = b64encode(encrypted_key)
response = self.request(req, True)
return response.json
示例13: construct_private_key
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import construct [as 別名]
def construct_private_key(
n: int, e: int, d: int, format: str = "PEM", passphrase: str = None
) -> str: # pragma: no cover
"""Construct a private key given n, e and d
Args:
n (int): n
e (int): e
d (int): d
format (str, optional): Supports PEM, DER and OpenSSH. Defaults to "PEM".
passphrase (str, optional): [description]. Defaults to None.
Returns:
str: Private key
"""
valid_formats = ["PEM", "DER", "OpenSSH"]
assert format in valid_formats, "Valid formats are {}".format(
" ".join(valid_formats)
)
priv = RSA.construct((n, e, d))
return priv.export_key(format=format, passphrase=passphrase)
示例14: common_primes
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import construct [as 別名]
def common_primes(keys):
"""Find common prime in keys modules
Args:
keys(list): RSAKeys
Returns:
list: RSAKeys for which factorization of n was found
"""
priv_keys = []
for pair in itertools.combinations(keys, 2):
prime = gmpy2.gcd(pair[0].n, pair[1].n)
if prime != 1:
log.success("Found common prime in: {}, {}".format(pair[0].identifier, pair[1].identifier))
for key_no in range(2):
if pair[key_no] not in priv_keys:
d = int(invmod(pair[key_no].e, (prime - 1) * (pair[key_no].n // prime - 1)))
new_key = RSAKey.construct(int(pair[key_no].n), int(pair[key_no].e), int(d),
identifier=pair[key_no].identifier + '-private')
new_key.texts = pair[key_no].texts[:]
priv_keys.append(new_key)
else:
log.debug("Key {} already in priv_keys".format(pair[key_no].identifier))
return priv_keys
示例15: wiener
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import construct [as 別名]
def wiener(key):
"""Wiener small private exponent attack
If d < (1/3)*(N**(1/4)), d can be effectively recovered using continuous fractions
Args:
key(RSAKey): public rsa key to break
Returns:
NoneType/RSAKey: None if didn't break key, private key otherwise
"""
en_fractions = continued_fractions(key.e, key.n)
for k, d in convergents(en_fractions):
if k != 0 and (key.e * d - 1) % k == 0:
phi = (key.e * d - 1) // k
""" p**2 - p*(n - phi + 1) + n == 0 """
b = key.n - phi + 1
delta = b * b - 4 * key.n
if delta > 0:
sqrt_delta = gmpy2.isqrt(delta)
if sqrt_delta * sqrt_delta == delta and sqrt_delta % 2 == 0:
log.debug("Found private key (d={}) for {}".format(d, key.identifier))
new_key = RSAKey.construct(key.n, key.e, d, identifier=key.identifier + '-private')
new_key.texts = key.texts[:]
return new_key
return None