当前位置: 首页>>代码示例>>Python>>正文


Python ffi.new函数代码示例

本文整理汇总了Python中nacl._sodium.ffi.new函数的典型用法代码示例。如果您正苦于以下问题:Python new函数的具体用法?Python new怎么用?Python new使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了new函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: crypto_aead_aes256gcm_decrypt

def crypto_aead_aes256gcm_decrypt(
        cipher, tag, nonce, key,
        additional_data, additional_data_len):
    if len(key) != crypto_aead_aes256gcm_KEYBYTES:
        raise ValueError("Invalid key")

    if len(nonce) != crypto_aead_aes256gcm_NPUBBYTES:
        raise ValueError("Invalid nonce")

    plaintext = ffi.new("unsigned char[]", len(cipher))
    decrypted_len = ffi.new("unsigned long long *")

    ciphertext = cipher + tag

    if additional_data is None:
        additional_data = ffi.NULL

    if (lib.crypto_aead_aes256gcm_decrypt(
            plaintext, decrypted_len, ffi.NULL, ciphertext,
            len(ciphertext), additional_data,
            additional_data_len, nonce, key) != 0):
        raise CryptoError("Decryption failed. Ciphertext failed verification")

    plaintext = ffi.buffer(plaintext, len(cipher))
    return plaintext
开发者ID:xueyumusic,项目名称:pynacl,代码行数:25,代码来源:crypto_aead_aes256gcm.py

示例2: sodium_add

def sodium_add(a, b):
    """
    Given a couple of *same-sized* byte sequences, interpreted as the
    little-endian representation of two unsigned integers, compute
    the modular addition of the represented values, in constant time for
    a given common length of the byte sequences.

    :param a: input bytes buffer
    :type a: bytes
    :param b: input bytes buffer
    :type b: bytes
    :return: a byte-sequence representing, as a little-endian big integer,
             the integer value of ``(to_int(a) + to_int(b)) mod 2^(8*len(a))``
    :rtype: bytes
    """
    ensure(isinstance(a, bytes),
           raising=exc.TypeError)
    ensure(isinstance(b, bytes),
           raising=exc.TypeError)
    ln = len(a)
    ensure(len(b) == ln,
           raising=exc.TypeError)

    buf_a = ffi.new("unsigned char []", ln)
    buf_b = ffi.new("unsigned char []", ln)

    ffi.memmove(buf_a, a, ln)
    ffi.memmove(buf_b, b, ln)

    lib.sodium_add(buf_a, buf_b, ln)

    return ffi.buffer(buf_a, ln)[:]
开发者ID:lmctv,项目名称:pynacl,代码行数:32,代码来源:utils.py

示例3: sodium_pad

def sodium_pad(s, blocksize):
    """
    Pad the input bytearray ``s`` to a multiple of ``blocksize``
    using the ISO/IEC 7816-4 algorithm

    :param s: input bytes string
    :type s: bytes
    :param blocksize:
    :type blocksize: int
    :return: padded string
    :rtype: bytes
    """
    ensure(isinstance(s, bytes),
           raising=exc.TypeError)
    ensure(isinstance(blocksize, integer_types),
           raising=exc.TypeError)
    if blocksize <= 0:
        raise exc.ValueError
    s_len = len(s)
    m_len = s_len + blocksize
    buf = ffi.new("unsigned char []", m_len)
    p_len = ffi.new("size_t []", 1)
    ffi.memmove(buf, s, s_len)
    rc = lib.sodium_pad(p_len, buf, s_len, blocksize, m_len)
    ensure(rc == 0, "Padding failure", raising=exc.CryptoError)
    return ffi.buffer(buf, p_len[0])[:]
开发者ID:lmctv,项目名称:pynacl,代码行数:26,代码来源:utils.py

示例4: generichash_blake2b_salt_personal

def generichash_blake2b_salt_personal(data,
                                      digest_size=crypto_generichash_BYTES,
                                      key=b'', salt=b'', person=b''):
    """One shot hash interface

    :param data: the input data to the hash function
    :param digest_size: must be at most
                        :py:data:`.crypto_generichash_BYTES_MAX`;
                        the default digest size is
                        :py:data:`.crypto_generichash_BYTES`
    :type digest_size: int
    :param key: must be at most
                :py:data:`.crypto_generichash_KEYBYTES_MAX` long
    :type key: bytes
    :param salt: must be at most
                 :py:data:`.crypto_generichash_SALTBYTES` long;
                 will be zero-padded if needed
    :type salt: bytes
    :param person: must be at most
                   :py:data:`.crypto_generichash_PERSONALBYTES` long:
                   will be zero-padded if needed
    :type person: bytes
    :return: digest_size long digest
    :rtype: bytes
    """

    _checkparams(digest_size, key, salt, person)

    ensure(isinstance(data, bytes),
           'Input data must be a bytes sequence',
           raising=exc.TypeError)

    digest = ffi.new("unsigned char[]", digest_size)

    # both _salt and _personal must be zero-padded to the correct length
    _salt = ffi.new("unsigned char []", crypto_generichash_SALTBYTES)
    _person = ffi.new("unsigned char []", crypto_generichash_PERSONALBYTES)

    ffi.memmove(_salt, salt, len(salt))
    ffi.memmove(_person, person, len(person))

    rc = lib.crypto_generichash_blake2b_salt_personal(digest, digest_size,
                                                      data, len(data),
                                                      key, len(key),
                                                      _salt, _person)
    ensure(rc == 0, 'Unexpected failure',
           raising=exc.RuntimeError)

    return ffi.buffer(digest, digest_size)[:]
开发者ID:warner,项目名称:pynacl,代码行数:49,代码来源:crypto_generichash.py

示例5: crypto_kx_keypair

def crypto_kx_keypair():
    """
    Generate a keypair.
    This is a duplicate crypto_box_keypair, but
    is included for api consistency.
    :return: (public_key, secret_key)
    :rtype: (bytes, bytes)
    """
    public_key = ffi.new("unsigned char[]", crypto_kx_PUBLIC_KEY_BYTES)
    secret_key = ffi.new("unsigned char[]", crypto_kx_SECRET_KEY_BYTES)
    res = lib.crypto_kx_keypair(public_key, secret_key)
    ensure(res == 0, "Key generation failed.", raising=exc.CryptoError)

    return (ffi.buffer(public_key, crypto_kx_PUBLIC_KEY_BYTES)[:],
            ffi.buffer(secret_key, crypto_kx_SECRET_KEY_BYTES)[:])
开发者ID:lmctv,项目名称:pynacl,代码行数:15,代码来源:crypto_kx.py

示例6: crypto_box_afternm

def crypto_box_afternm(message, nonce, k):
    """
    Encrypts and returns the message ``message`` using the shared key ``k`` and
    the nonce ``nonce``.

    :param message: bytes
    :param nonce: bytes
    :param k: bytes
    :rtype: bytes
    """
    if len(nonce) != crypto_box_NONCEBYTES:
        raise exc.ValueError("Invalid nonce")

    if len(k) != crypto_box_BEFORENMBYTES:
        raise exc.ValueError("Invalid shared key")

    padded = b"\x00" * crypto_box_ZEROBYTES + message
    ciphertext = ffi.new("unsigned char[]", len(padded))

    rc = lib.crypto_box_afternm(ciphertext, padded, len(padded), nonce, k)
    ensure(rc == 0,
           'Unexpected library error',
           raising=exc.RuntimeError)

    return ffi.buffer(ciphertext, len(padded))[crypto_box_BOXZEROBYTES:]
开发者ID:maqp,项目名称:pynacl,代码行数:25,代码来源:crypto_box.py

示例7: crypto_sign

def crypto_sign(message, sk):
    """
    Signs the message ``message`` using the secret key ``sk`` and returns the
    signed message.

    :param message: bytes
    :param sk: bytes
    :rtype: bytes
    """
    signed = ffi.new("unsigned char[]", len(message) + crypto_sign_BYTES)
    signed_len = ffi.new("unsigned long long *")

    rc = lib.crypto_sign(signed, signed_len, message, len(message), sk)
    assert rc == 0

    return ffi.buffer(signed, signed_len[0])[:]
开发者ID:NegativeMjark,项目名称:pynacl,代码行数:16,代码来源:crypto_sign.py

示例8: crypto_sign_ed25519ph_final_create

def crypto_sign_ed25519ph_final_create(edph,
                                       sk):
    """
    Create a signature for the data hashed in edph
    using the secret key sk

    :param edph: the ed25519ph state for the data
                 being signed
    :type edph: crypto_sign_ed25519ph_state
    :param sk: the ed25519 secret part of the signing key
    :type sk: bytes
    :return: ed25519ph signature
    :rtype: bytes
    """
    ensure(isinstance(edph, crypto_sign_ed25519ph_state),
           'edph parameter must be a ed25519ph_state object',
           raising=exc.TypeError)
    ensure(isinstance(sk, bytes),
           'secret key parameter must be a bytes object',
           raising=exc.TypeError)
    ensure(len(sk) == crypto_sign_SECRETKEYBYTES,
           ('secret key must be {0} '
            'bytes long').format(crypto_sign_SECRETKEYBYTES),
           raising=exc.TypeError)
    signature = ffi.new("unsigned char[]", crypto_sign_BYTES)
    rc = lib.crypto_sign_ed25519ph_final_create(edph.state,
                                                signature,
                                                ffi.NULL,
                                                sk)
    ensure(rc == 0,
           'Unexpected library error',
           raising=exc.RuntimeError)

    return ffi.buffer(signature, crypto_sign_BYTES)[:]
开发者ID:lmctv,项目名称:pynacl,代码行数:34,代码来源:crypto_sign.py

示例9: crypto_core_ed25519_sub

def crypto_core_ed25519_sub(p, q):
    """
    Subtract a point from another on the edwards25519 curve.

    :param p: a :py:data:`.crypto_core_ed25519_BYTES` long bytes sequence
              representing a point on the edwards25519 curve
    :type p: bytes
    :param q: a :py:data:`.crypto_core_ed25519_BYTES` long bytes sequence
              representing a point on the edwards25519 curve
    :type q: bytes
    :return: a point on the edwards25519 curve represented as
             a :py:data:`.crypto_core_ed25519_BYTES` long bytes sequence
    :rtype: bytes
    """
    ensure(isinstance(p, bytes) and isinstance(q, bytes) and
           len(p) == crypto_core_ed25519_BYTES and
           len(q) == crypto_core_ed25519_BYTES,
           'Each point must be a {} long bytes sequence'.format(
           'crypto_core_ed25519_BYTES'),
           raising=exc.TypeError)

    r = ffi.new("unsigned char[]", crypto_core_ed25519_BYTES)

    rc = lib.crypto_core_ed25519_sub(r, p, q)
    ensure(rc == 0,
           'Unexpected library error',
           raising=exc.RuntimeError)

    return ffi.buffer(r, crypto_core_ed25519_BYTES)[:]
开发者ID:lmctv,项目名称:pynacl,代码行数:29,代码来源:crypto_core.py

示例10: crypto_box_open_afternm

def crypto_box_open_afternm(ciphertext, nonce, k):
    """
    Decrypts and returns the encrypted message ``ciphertext``, using the shared
    key ``k`` and the nonce ``nonce``.

    :param ciphertext: bytes
    :param nonce: bytes
    :param k: bytes
    :rtype: bytes
    """
    if len(nonce) != crypto_box_NONCEBYTES:
        raise exc.ValueError("Invalid nonce")

    if len(k) != crypto_box_BEFORENMBYTES:
        raise exc.ValueError("Invalid shared key")

    padded = (b"\x00" * crypto_box_BOXZEROBYTES) + ciphertext
    plaintext = ffi.new("unsigned char[]", len(padded))

    res = lib.crypto_box_open_afternm(
                plaintext, padded, len(padded), nonce, k)
    ensure(res == 0, "An error occurred trying to decrypt the message",
           raising=exc.CryptoError)

    return ffi.buffer(plaintext, len(padded))[crypto_box_ZEROBYTES:]
开发者ID:maqp,项目名称:pynacl,代码行数:25,代码来源:crypto_box.py

示例11: generichash_blake2b_state_copy

def generichash_blake2b_state_copy(statebuf):
    """Return a copy of the given blake2b hash state"""

    newstate = ffi.new("unsigned char[]", crypto_generichash_STATEBYTES)
    ffi.memmove(newstate, statebuf, crypto_generichash_STATEBYTES)

    return newstate
开发者ID:maqp,项目名称:pynacl,代码行数:7,代码来源:crypto_generichash.py

示例12: crypto_pwhash_scryptsalsa208sha256_str

def crypto_pwhash_scryptsalsa208sha256_str(
        passwd, opslimit=SCRYPT_OPSLIMIT_INTERACTIVE,
        memlimit=SCRYPT_MEMLIMIT_INTERACTIVE):
    """
    Derive a cryptographic key using the ``passwd`` and ``salt``
    given as input, returning a string representation which includes
    the salt and the tuning parameters.

    The returned string can be directly stored as a password hash.

    See :py:func:`.crypto_pwhash_scryptsalsa208sha256` for a short
    discussion about ``opslimit`` and ``memlimit`` values.

    :param bytes passwd:
    :param int opslimit:
    :param int memlimit:
    :return: serialized key hash, including salt and tuning parameters
    :rtype: bytes
    """
    buf = ffi.new("char[]", SCRYPT_STRBYTES)

    ret = lib.crypto_pwhash_scryptsalsa208sha256_str(buf, passwd,
                                                     len(passwd),
                                                     opslimit,
                                                     memlimit)

    ensure(ret == 0, 'Unexpected failure in password hashing',
           raising=exc.RuntimeError)

    return ffi.string(buf)
开发者ID:maqp,项目名称:pynacl,代码行数:30,代码来源:crypto_pwhash.py

示例13: crypto_box

def crypto_box(message, nonce, pk, sk):
    """
    Encrypts and returns a message ``message`` using the secret key ``sk``,
    public key ``pk``, and the nonce ``nonce``.

    :param message: bytes
    :param nonce: bytes
    :param pk: bytes
    :param sk: bytes
    :rtype: bytes
    """
    if len(nonce) != crypto_box_NONCEBYTES:
        raise ValueError("Invalid nonce size")

    if len(pk) != crypto_box_PUBLICKEYBYTES:
        raise ValueError("Invalid public key")

    if len(sk) != crypto_box_SECRETKEYBYTES:
        raise ValueError("Invalid secret key")

    padded = (b"\x00" * crypto_box_ZEROBYTES) + message
    ciphertext = ffi.new("unsigned char[]", len(padded))

    rc = lib.crypto_box(ciphertext, padded, len(padded), nonce, pk, sk)
    assert rc == 0

    return ffi.buffer(ciphertext, len(padded))[crypto_box_BOXZEROBYTES:]
开发者ID:NegativeMjark,项目名称:pynacl,代码行数:27,代码来源:crypto_box.py

示例14: crypto_pwhash_str_alg

def crypto_pwhash_str_alg(passwd, opslimit, memlimit, alg):
    """
    Derive a cryptographic key using the ``passwd`` given as input
    and a random ``salt``, returning a string representation which
    includes the salt, the tuning parameters and the used algorithm.

    :param passwd: The input password
    :type passwd: bytes
    :param opslimit: computational cost
    :type opslimit: int
    :param memlimit: memory cost
    :type memlimit: int
    :param alg: The algorithm to use
    :type alg: int
    :return: serialized derived key and parameters
    :rtype: bytes
    """
    ensure(isinstance(opslimit, integer_types),
           raising=TypeError)
    ensure(isinstance(memlimit, integer_types),
           raising=TypeError)
    ensure(isinstance(passwd, bytes),
           raising=TypeError)

    _check_argon2_limits_alg(opslimit, memlimit, alg)

    outbuf = ffi.new("char[]", 128)

    ret = lib.crypto_pwhash_str_alg(outbuf, passwd, len(passwd),
                                    opslimit, memlimit, alg)

    ensure(ret == 0, 'Unexpected failure in key derivation',
           raising=exc.RuntimeError)

    return ffi.string(outbuf)
开发者ID:lmctv,项目名称:pynacl,代码行数:35,代码来源:crypto_pwhash.py

示例15: crypto_auth_hmacsha512256

def crypto_auth_hmacsha512256(message, k):

    a = ffi.new("unsigned char[]", crypto_auth_hmacsha512256_BYTES)
    rc = lib.crypto_auth_hmacsha512256(a, message, len(message), k)

    assert rc == 0
    return ffi.buffer(a, crypto_auth_hmacsha512256_BYTES)[:]
开发者ID:TerRoshak,项目名称:pynacl,代码行数:7,代码来源:crypto_auth.py


注:本文中的nacl._sodium.ffi.new函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。