本文整理汇总了Python中pysodium.randombytes函数的典型用法代码示例。如果您正苦于以下问题:Python randombytes函数的具体用法?Python randombytes怎么用?Python randombytes使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了randombytes函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: randrange
def randrange(n):
a = (n.bit_length() + 7) // 8 # number of bytes to store n
b = 8 * a - n.bit_length() # number of shifts to have good bit number
r = int.from_bytes(randombytes(a), byteorder='big') >> b
while r >= n:
r = int.from_bytes(randombytes(a), byteorder='big') >> b
return r
开发者ID:Lapin0t,项目名称:py-swirld,代码行数:7,代码来源:utils.py
示例2: _3user
def _3user():
eA = nacl.randombytes(nacl.crypto_scalarmult_curve25519_BYTES)
pA = nacl.crypto_scalarmult_curve25519_base(eA)
print "A public: \t%s\nA exp: \t%s" % (b85encode(pA), b85encode(eA))
eB = nacl.randombytes(nacl.crypto_scalarmult_curve25519_BYTES)
pB = nacl.crypto_scalarmult_curve25519_base(eB)
print "B public: \t%s\nB exp: \t%s" % (b85encode(pB), b85encode(eB))
eC = nacl.randombytes(nacl.crypto_scalarmult_curve25519_BYTES)
pC = nacl.crypto_scalarmult_curve25519_base(eC)
print "C public: \t%s\nC exp: \t%s" % (b85encode(pC), b85encode(eC))
print
pAB = nacl.crypto_scalarmult_curve25519(eB, pA)
print "public AB", b85encode(pAB)
pBA = nacl.crypto_scalarmult_curve25519(eA, pB)
print "public BA", b85encode(pBA)
pCA = nacl.crypto_scalarmult_curve25519(eA, pC)
print "public CA", b85encode(pCA)
print
key = nacl.crypto_scalarmult_curve25519(eB, pCA)
print "key: \t%s" % (b85encode(key))
key = nacl.crypto_scalarmult_curve25519(eC, pBA)
print "key: \t%s" % (b85encode(key))
key = nacl.crypto_scalarmult_curve25519(eC, pAB)
print "key: \t%s" % (b85encode(key))
开发者ID:TLINDEN,项目名称:pbp,代码行数:28,代码来源:dhdemo-nacl.py
示例3: send
def send(self,plain):
# update context
if self.peer_pub != (b'\0' * nacl.crypto_scalarmult_curve25519_BYTES):
# calculate a new incoming key, and finish that DH, start a new for
# outgoing keys.
# only do this directly after receiving a packet, not on later sends
# without receiving any acks before, we reset peer_pub to signal, that
# an incoming request has been already once processed like this.
self.e_in = nacl.randombytes(nacl.crypto_scalarmult_curve25519_BYTES)
self.in_prev = self.in_k
self.in_k = nacl.crypto_scalarmult_curve25519(self.e_in, self.peer_pub)
self.peer_pub = (b'\0' * nacl.crypto_scalarmult_curve25519_BYTES)
# generate e_out
self.e_out = nacl.randombytes(nacl.crypto_scalarmult_curve25519_BYTES)
elif self.out_k == (b'\0' * nacl.crypto_secretbox_KEYBYTES):
# only for the very first packet necessary
# we explicitly need to generate e_out
self.e_out = nacl.randombytes(nacl.crypto_scalarmult_curve25519_BYTES)
#else: # axolotlize
# print 'axolotl!'
# self.out_k = nacl.crypto_generichash(self.out_k,
# nacl.crypto_scalarmult_curve25519(self.me_id.cs, self.peer_id.cp),
# nacl.crypto_scalarmult_curve25519_BYTES)
# compose packet
dh1 = nacl.crypto_scalarmult_curve25519_base(self.e_out)
dh2 = (nacl.crypto_scalarmult_curve25519_base(self.e_in)
if self.e_in != (b'\0' * nacl.crypto_scalarmult_curve25519_BYTES)
else (b'\0' * nacl.crypto_scalarmult_curve25519_BYTES))
plain = b''.join((dh1, dh2, plain))
# encrypt the whole packet
return self.encrypt(plain)
开发者ID:stef,项目名称:pbp,代码行数:35,代码来源:chaining.py
示例4: encrypt
def encrypt(self,plain):
if self.out_k == (b'\0' * nacl.crypto_scalarmult_curve25519_BYTES):
# encrypt using public key
nonce = nacl.randombytes(nacl.crypto_box_NONCEBYTES)
cipher= nacl.crypto_box(plain, nonce, self.peer_id.cp, self.me_id.cs)
else:
# encrypt using chaining mode
nonce = nacl.randombytes(nacl.crypto_secretbox_NONCEBYTES)
cipher = nacl.crypto_secretbox(plain, nonce, self.out_k)
return cipher, nonce
开发者ID:stef,项目名称:pbp,代码行数:11,代码来源:chaining.py
示例5: make_keypair
def make_keypair():
public_key, private_key = pysodium.crypto_sign_keypair()
print 'Do you wish to encrypt the private key under a password? (y/n)'
answer = raw_input().lower()
if answer not in ['y', 'n']: raise SystemExit('Invalid answer')
if answer == 'y':
salt = pysodium.randombytes(pysodium.crypto_pwhash_SALTBYTES)
key = hash_password(prompt_for_new_password(), salt)
nonce = pysodium.randombytes(pysodium.crypto_box_NONCEBYTES)
cyphertext = pysodium.crypto_secretbox(private_key, nonce, key)
private_key = b'y' + salt + nonce + cyphertext
else:
private_key = b'n' + private_key
return base64.b64encode(private_key), base64.b64encode(public_key)
开发者ID:robehickman,项目名称:simple-http-file-sync,代码行数:15,代码来源:crypto.py
示例6: _2user
def _2user():
# 1st user
exp1 = nacl.randombytes(nacl.crypto_scalarmult_curve25519_BYTES)
public1 = nacl.crypto_scalarmult_curve25519_base(exp1)
# print "public1: \t%s\nexp1: \t%s" % (b85encode(public1), b85encode(exp1))
print
# 2nd user
exp2 = nacl.randombytes(nacl.crypto_scalarmult_curve25519_BYTES)
public2 = nacl.crypto_scalarmult_curve25519_base(exp2)
key = nacl.crypto_scalarmult_curve25519(exp2, public1)
print "key: \t%s" % (b85encode(key))
# print "public2: \t%s\nkey: \t%s" % (b85encode(public2), b85encode(key))
print
# 1st user completing DH
key = nacl.crypto_scalarmult_curve25519(exp1, public2)
print "key: \t%s" % (b85encode(key))
开发者ID:TLINDEN,项目名称:pbp,代码行数:16,代码来源:dhdemo-nacl.py
示例7: savesecretekey
def savesecretekey(self, ext, key):
fname = get_sk_filename(self.basedir, self.name, ext)
k = pbp.getkey(nacl.crypto_secretbox_KEYBYTES, empty=True, text="Master" if ext == "mk" else "Subkey")
nonce = nacl.randombytes(nacl.crypto_secretbox_NONCEBYTES)
with open(fname, "w") as fd:
fd.write(nonce)
fd.write(nacl.crypto_secretbox(key, nonce, k))
开发者ID:TLINDEN,项目名称:pbp,代码行数:7,代码来源:publickey.py
示例8: dh2_handler
def dh2_handler(peer):
# provides a high level interface to receive a DH key exchange
# request peer contains the public component generated by the peer
# when initiating an DH exchange
exp = nacl.randombytes(nacl.crypto_scalarmult_curve25519_BYTES)
public = nacl.crypto_scalarmult_curve25519_base(exp)
secret = nacl.crypto_scalarmult_curve25519(exp, b85decode(peer))
return (public, secret)
开发者ID:fpletz,项目名称:pbp,代码行数:8,代码来源:pbp.py
示例9: encrypt
def encrypt(plaintext, password):
"""Encrypts the given plaintext using libsodium secretbox, key is generated using scryptsalsa208sha256 with a random salt and nonce (we can not guarantee the incrementing anyway). Note that any str objects are assumed to be in utf-8."""
salt = pysodium.randombytes(pysodium.crypto_pwhash_scryptsalsa208sha256_SALTBYTES)
memlimit = pysodium.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_INTERACTIVE
opslimit = pysodium.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_INTERACTIVE
if isinstance(password, str): password = password.encode("utf-8")
key = pysodium.crypto_pwhash_scryptsalsa208sha256(pysodium.crypto_secretbox_KEYBYTES, password, salt, memlimit, opslimit)
nonce = pysodium.randombytes(pysodium.crypto_secretbox_NONCEBYTES)
if isinstance(plaintext, str): plaintext = plaintext.encode("utf-8")
cyphertext = pysodium.crypto_secretbox(plaintext, nonce, key)
data = (1).to_bytes(1, "little")
data += memlimit.to_bytes(4, "little")
data += opslimit.to_bytes(4, "little")
data += salt
data += nonce
data += cyphertext
return base64.b64encode(data)
开发者ID:tyrylu,项目名称:orgedit,代码行数:17,代码来源:sodium_utils.py
示例10: encrypt_handler
def encrypt_handler(infile=None, outfile=None, recipient=None, self=None, basedir=None):
# provides a high level function to do encryption of files
# infile specifies the filename of the input file,
# if '-' or not specified it uses stdin
# outfile specifies the filename of the output file, if not specified
# it uses the same filename with '.pbp' appended
# recipient specifies the name of the recipient for using public key crypto
# self specifies the sender for signing the message using pk crypto
# basedir provides a root for the keystores needed for pk crypto
# if both self and recipient is specified pk crypto is used, otherwise symmetric
# this function also handles buffering.
fd = inputfd(infile)
outfd = outputfd(outfile or (infile+'.pbp' if infile not in [None,'-'] else '-'))
if recipient and self:
# let's do public key encryption
key = nacl.randombytes(nacl.crypto_secretbox_KEYBYTES)
me = publickey.Identity(self, basedir=basedir)
size = struct.pack('>H',len(recipient))
# write out encrypted message key (nonce, c(key+recplen)) for each recipient
for r in recipient:
r = publickey.Identity(r, basedir=basedir, publicOnly=True)
nonce = nacl.randombytes(nacl.crypto_box_NONCEBYTES)
outfd.write(nonce)
outfd.write(nacl.crypto_box(key+size, nonce, r.cp, me.cs))
me.clear()
else:
# let's do symmetric crypto
key = getkey(nacl.crypto_secretbox_KEYBYTES)
buf = fd.read(BLOCK_SIZE)
if buf:
nonce, cipher = encrypt(buf, k=key)
outfd.write(nonce)
outfd.write(cipher)
buf = fd.read(BLOCK_SIZE)
while buf:
nonce = inc_nonce(nonce)
nonce, cipher = encrypt(buf, k=key, nonce=nonce)
outfd.write(cipher)
buf = fd.read(BLOCK_SIZE)
clearmem(key)
key=None
if fd != sys.stdin: fd.close()
if outfd != sys.stdout: outfd.close()
开发者ID:stef,项目名称:pbp,代码行数:46,代码来源:pbp.py
示例11: test_crypto_box_open_detached
def test_crypto_box_open_detached(self):
pk, sk = pysodium.crypto_box_keypair()
n = pysodium.randombytes(pysodium.crypto_box_NONCEBYTES)
c, mac = pysodium.crypto_box_detached("howdy", n, pk, sk)
r = pysodium.crypto_box_open_detached(c, mac, n, pk, sk)
self.assertEqual(r, b"howdy")
changed = "\0"*len(c)
self.assertRaises(ValueError, pysodium.crypto_box_open_detached,changed, mac, n, pk, sk)
开发者ID:jvarho,项目名称:pysodium,代码行数:8,代码来源:test_pysodium.py
示例12: savesecretekey
def savesecretekey(self, ext, key):
fname = get_sk_filename(self.basedir, self.name, ext)
k = getkey(nacl.crypto_secretbox_KEYBYTES,
empty=True,
text='Master' if ext == 'mk' else 'Subkey')
nonce = nacl.randombytes(nacl.crypto_secretbox_NONCEBYTES)
with open(fname,'wb') as fd:
fd.write(nonce)
fd.write(nacl.crypto_secretbox(key, nonce, k))
开发者ID:stef,项目名称:pbp,代码行数:9,代码来源:publickey.py
示例13: test_AsymCrypto_With_Seeded_Keypair
def test_AsymCrypto_With_Seeded_Keypair(self):
msg = b"correct horse battery staple"
nonce = pysodium.randombytes(pysodium.crypto_box_NONCEBYTES)
pk, sk = pysodium.crypto_box_seed_keypair(b"\x00" * pysodium.crypto_box_SEEDBYTES)
c = pysodium.crypto_box(msg, nonce, pk, sk)
m = pysodium.crypto_box_open(c, nonce, pk, sk)
self.assertEqual(msg, m)
开发者ID:stef,项目名称:pysodium,代码行数:9,代码来源:test_pysodium.py
示例14: test_AsymCrypto_With_Seeded_Keypair
def test_AsymCrypto_With_Seeded_Keypair(self):
msg = "correct horse battery staple"
nonce = pysodium.randombytes(pysodium.crypto_box_NONCEBYTES)
pk, sk = pysodium.crypto_box_seed_keypair("howdy")
c = pysodium.crypto_box_easy(msg, nonce, pk, sk)
m = pysodium.crypto_box_open_easy(c, nonce, pk, sk)
self.assertEqual(msg, m)
开发者ID:apsyxyz,项目名称:pysodium,代码行数:9,代码来源:test_pysodium.py
示例15: encrypt_message
def encrypt_message(identity, payload):
version = 1
nonce = pysodium.randombytes(pysodium.crypto_secretbox_NONCEBYTES)
pubkeyhash, encryption_key = expand_handle(identity.handle)
if not validate_pubkey(identity.pk, pubkeyhash):
raise PubkeyError()
decrypted = generate_innerbox(identity.pk, identity.sk, payload, version)
encrypted = pysodium.crypto_secretbox(decrypted, nonce, encryption_key)
return outer_pack.pack(version, nonce, encrypted)
开发者ID:nickodell,项目名称:dhtdns,代码行数:9,代码来源:crypto.py
示例16: do_create_channel
def do_create_channel(self, line):
"""
Create a random channel name (hex number) and set the new channel in
the configuration.
"""
channel = base64.b16encode(pysodium.randombytes(16)).lower()
self.config[b'channel'] = channel
save_data(CONFIG, self.config)
print('[+] Channel ID {0} added to configuration.'.format(channel))
开发者ID:carriercomm,项目名称:zkm,代码行数:10,代码来源:client.py
示例17: authenticate
def authenticate():
""" This does two things, either validate a pre-existing session token
or create a new one from a signed authentication token. """
client_ip = request.environ['REMOTE_ADDR']
repository = request.headers['repository']
if repository not in config['repositories']: return fail(no_such_repo_msg)
# ==
repository_path = config['repositories'][repository]['path']
conn = auth_db_connect(cpjoin(repository_path, 'auth_transient.db')); gc_tokens(conn)
gc_tokens(conn)
# Allow resume of an existing session
if 'session_token' in request.headers:
session_token = request.headers['session_token']
conn.execute("delete from session_tokens where expires < ?", (time.time(),)); conn.commit()
res = conn.execute("select * from session_tokens where token = ? and ip = ?", (session_token, client_ip)).fetchall()
if res != []: return success({'session_token' : session_token})
else: return fail(user_auth_fail_msg)
# Create a new session
else:
user = request.headers['user']
auth_token = request.headers['auth_token']
signiture = request.headers['signature']
try:
public_key = config['users'][user]['public_key']
# signature
pysodium.crypto_sign_verify_detached(base64.b64decode(signiture), auth_token, base64.b64decode(public_key))
# check token was previously issued by this system and is still valid
res = conn.execute("select * from tokens where token = ? and ip = ? ", (auth_token, client_ip)).fetchall()
# Validate token matches one we sent
if res == [] or len(res) > 1: return fail(user_auth_fail_msg)
# Does the user have permission to use this repository?
if repository not in config['users'][user]['uses_repositories']: return fail(user_auth_fail_msg)
# Everything OK
conn.execute("delete from tokens where token = ?", (auth_token,)); conn.commit()
# generate a session token and send it to the client
session_token = base64.b64encode(pysodium.randombytes(35))
conn.execute("insert into session_tokens (token, expires, ip, username) values (?,?,?, ?)",
(session_token, time.time() + extend_session_duration, client_ip, user))
conn.commit()
return success({'session_token' : session_token})
except Exception: # pylint: disable=broad-except
return fail(user_auth_fail_msg)
开发者ID:robehickman,项目名称:simple-http-file-sync,代码行数:55,代码来源:server.py
示例18: udpServe
def udpServe(key=b'this is my key value!',addr=('localhost',8080)) :
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
nonce = pysodium.randombytes(8)
ciphertext = pysodium.crypto_aead_chacha20poly1305_encrypt(b'this is my key value!',None,nonce,key)
plaintext = pysodium.crypto_aead_chacha20poly1305_decrypt(ciphertext,None,nonce,key)
print(plaintext)
print(ciphertext)
print(reprlib.repr(ciphertext))
print(nonce)
print(ciphertext+nonce)
s.sendto(ciphertext+nonce,addr)
s.close()
开发者ID:xiaobagou,项目名称:echo,代码行数:12,代码来源:echo_client.py
示例19: encrypt
def encrypt(msg, pwd=None, k=None):
# encrypts a message symmetrically using crypto_secretbox
# k specifies an encryption key, which if not supplied, is derived from
# pwd which is queried from the user, if also not specified.
# returns a (nonce, ciphertext) tuple
nonce = nacl.randombytes(nacl.crypto_secretbox_NONCEBYTES)
cleark = (k is None)
if not k:
k = getkey(nacl.crypto_secretbox_KEYBYTES, pwd=pwd)
ciphertext = nacl.crypto_secretbox(msg, nonce, k)
if cleark: clearmem(k)
return (nonce, ciphertext)
开发者ID:fpletz,项目名称:pbp,代码行数:12,代码来源:pbp.py
示例20: send
def send(self, msg):
"""
as per https://github.com/trevp/axolotl/wiki/newversion (Nov 19, 2013 · 41 revisions)
Sending messages
-----------------
Local variables:
MK : message key
if DHRs == <none>:
DHRs = generateECDH()
MK = HASH(CKs || "0")
msg = Enc(HKs, Ns || PNs || DHRs) || Enc(MK, plaintext)
Ns = Ns + 1
CKs = HASH(CKs || "1")
return msg
"""
if self.DHRs == None:
self.DHRs = Key().new()
self.PNs = self.Ns # wtf: not in spec, but seems needed
self.Ns = 0 # wtf: not in spec, but seems needed
mk = nacl.crypto_generichash(self.CKs, 'MK', nacl.crypto_secretbox_KEYBYTES)
hnonce = nacl.randombytes(nacl.crypto_secretbox_NONCEBYTES)
mnonce = nacl.randombytes(nacl.crypto_secretbox_NONCEBYTES)
msg = ''.join((hnonce,
mnonce,
nacl.crypto_secretbox(
''.join((struct.pack('>I',self.Ns),
struct.pack('>I',self.PNs),
self.DHRs.pk)),
hnonce, self.HKs),
nacl.crypto_secretbox(msg, mnonce, mk)))
clearmem(mk)
mk = None
self.Ns += 1
self.CKs = nacl.crypto_generichash(self.CKs, "CK", nacl.crypto_secretbox_KEYBYTES)
return msg
开发者ID:stef,项目名称:saxolotl,代码行数:38,代码来源:axolotl.py
注:本文中的pysodium.randombytes函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论