pynacl公私钥加解密

# @author: 逸轩
# @file: pynacl_2.py
# @time: 2021/1/28
# @desc: python pynacl 加解密

try:
    from nacl.encoding import HexEncoder, Base64Encoder
    from nacl.public import Box, PrivateKey, PublicKey
except ImportError:
    raise ImportWarning('python环境中未找到nacl,请先执行 pip install pynacl 进行安装')

from cryptography import fernet
from nacl.utils import EncryptedMessage, StringFixer, random
from nacl import exceptions as exc
from nacl import encoding
import nacl.bindings


def encrypt(public_key: str, private_key: str, nonce: str, plain_text: str):
    """
    加密
    :param public_key: 公钥
    :param private_key: 私钥
    :param nonce: 随机码
    :param plain_text: 加密文本
    :return:加密后的密文,str 类型
    """
    if len(public_key) != 64:
        raise ValueError('public_key 长度必须为64')
    if len(private_key) != 64:
        raise ValueError('private_key 长度必须为64')
    if len(nonce) != 32:
        raise ValueError('nonce 长度必须为32')

    # 公钥转 bytes,注意encoder指定HexEncoder
    public = PublicKey(
        public_key.encode(),
        encoder=HexEncoder,
    )

    # 私钥转 bytes,注意encoder指定HexEncoder
    private = PrivateKey(
        private_key.encode(),
        encoder=HexEncoder,
    )

    # 生成 box
    box = Box(private, public)

    # 随机码先转成 bytes,再 base64 decode
    nonce_bytes = Base64Encoder.decode(nonce.encode())
    encrypted = box.encrypt(
        plain_text.encode(),
        nonce_bytes
    )
    ciphertext = Base64Encoder.encode(encrypted.ciphertext)
    return str(ciphertext, encoding="utf8")


def decrypt(public_key: str, private_key: str, nonce: str, ciphertext: str):
    """
    解密
    :param public_key: 公钥
    :param private_key: 私钥
    :param nonce: 随机码
    :param ciphertext: 密文
    :return: 解密后的文本,str 类型
    """
    if len(public_key) != 64:
        raise ValueError('public_key 长度必须为64')
    if len(private_key) != 64:
        raise ValueError('private_key 长度必须为64')
    if len(nonce) != 32:
        raise ValueError('nonce 长度必须为32')
    public = PublicKey(
        public_key.encode(),
        encoder=HexEncoder,
    )
    private = PrivateKey(
        private_key.encode(),
        encoder=HexEncoder,
    )
    box = Box(private, public)
    nonce_bytes = Base64Encoder.decode(nonce.encode())
    ciphertextByte = Base64Encoder.decode(ciphertext.encode())
    decrypted = box.decrypt(ciphertextByte, nonce_bytes)
    return str(decrypted, encoding='utf-8')


class PublicKey(encoding.Encodable, StringFixer, object):
    """
    The public key counterpart to an Curve25519 :class:`nacl.public.PrivateKey`
    for encrypting messages.

    :param public_key: [:class:`bytes`] Encoded Curve25519 public key
    :param encoder: A class that is able to decode the `public_key`

    :cvar SIZE: The size that the public key is required to be
    """

    SIZE = nacl.bindings.crypto_box_PUBLICKEYBYTES

    def __init__(self, public_key, encoder=encoding.RawEncoder):
        self._public_key = encoder.decode(public_key)
        if not isinstance(self._public_key, bytes):
            raise exc.TypeError("PublicKey must be created from 32 bytes")

        if len(self._public_key) != self.SIZE:
            raise exc.ValueError(
                "The public key must be exactly {0} bytes long".format(
                    self.SIZE
                )
            )

    def __bytes__(self):
        return self._public_key

    def __hash__(self):
        return hash(bytes(self))

    def __eq__(self, other):
        if not isinstance(other, self.__class__):
            return False
        return nacl.bindings.sodium_memcmp(bytes(self), bytes(other))

    def __ne__(self, other):
        return not (self == other)


class PrivateKey(encoding.Encodable, StringFixer, object):
    """
    Private key for decrypting messages using the Curve25519 algorithm.

    .. warning:: This **must** be protected and remain secret. Anyone who
        knows the value of your :class:`~nacl.public.PrivateKey` can decrypt
        any message encrypted by the corresponding
        :class:`~nacl.public.PublicKey`

    :param private_key: The private key used to decrypt messages
    :param encoder: The encoder class used to decode the given keys

    :cvar SIZE: The size that the private key is required to be
    :cvar SEED_SIZE: The size that the seed used to generate the
                     private key is required to be
    """

    SIZE = nacl.bindings.crypto_box_SECRETKEYBYTES
    SEED_SIZE = nacl.bindings.crypto_box_SEEDBYTES

    def __init__(self, private_key, encoder=encoding.RawEncoder):
        # Decode the secret_key
        private_key = encoder.decode(private_key)
        # verify the given secret key type and size are correct
        if not (
            isinstance(private_key, bytes) and len(private_key) == self.SIZE
        ):
            raise exc.TypeError(
                (
                    "PrivateKey must be created from a {0} "
                    "bytes long raw secret key"
                ).format(self.SIZE)
            )

        raw_public_key = nacl.bindings.crypto_scalarmult_base(private_key)

        self._private_key = private_key
        self.public_key = PublicKey(raw_public_key)

    @classmethod
    def from_seed(cls, seed, encoder=encoding.RawEncoder):
        """
        Generate a PrivateKey using a deterministic construction
        starting from a caller-provided seed

        .. warning:: The seed **must** be high-entropy; therefore,
            its generator **must** be a cryptographic quality
            random function like, for example, :func:`~nacl.utils.random`.

        .. warning:: The seed **must** be protected and remain secret.
            Anyone who knows the seed is really in possession of
            the corresponding PrivateKey.

        :param seed: The seed used to generate the private key
        :rtype: :class:`~nacl.public.PrivateKey`
        """
        # decode the seed
        seed = encoder.decode(seed)
        # Verify the given seed type and size are correct
        if not (isinstance(seed, bytes) and len(seed) == cls.SEED_SIZE):
            raise exc.TypeError(
                (
                    "PrivateKey seed must be a {0} bytes long "
                    "binary sequence"
                ).format(cls.SEED_SIZE)
            )
        # generate a raw keypair from the given seed
        raw_pk, raw_sk = nacl.bindings.crypto_box_seed_keypair(seed)
        # construct a instance from the raw secret key
        return cls(raw_sk)

    def __bytes__(self):
        return self._private_key

    def __hash__(self):
        return hash((type(self), bytes(self.public_key)))

    def __eq__(self, other):
        if not isinstance(other, self.__class__):
            return False
        return self.public_key == other.public_key

    def __ne__(self, other):
        return not (self == other)

    @classmethod
    def generate(cls):
        """
        Generates a random :class:`~nacl.public.PrivateKey` object

        :rtype: :class:`~nacl.public.PrivateKey`
        """
        return cls(random(PrivateKey.SIZE), encoder=encoding.RawEncoder)


class Box(encoding.Encodable, StringFixer, object):
    """
    The Box class boxes and unboxes messages between a pair of keys

    The ciphertexts generated by :class:`~nacl.public.Box` include a 16
    byte authenticator which is checked as part of the decryption. An invalid
    authenticator will cause the decrypt function to raise an exception. The
    authenticator is not a signature. Once you've decrypted the message you've
    demonstrated the ability to create arbitrary valid message, so messages you
    send are repudiable. For non-repudiable messages, sign them after
    encryption.

    :param private_key: :class:`~nacl.public.PrivateKey` used to encrypt and
        decrypt messages
    :param public_key: :class:`~nacl.public.PublicKey` used to encrypt and
        decrypt messages

    :cvar NONCE_SIZE: The size that the nonce is required to be.
    """

    NONCE_SIZE = nacl.bindings.crypto_box_NONCEBYTES

    def __init__(self, private_key, public_key):
        if private_key and public_key:
            if not isinstance(private_key, PrivateKey) or not isinstance(
                public_key, PublicKey
            ):
                raise exc.TypeError(
                    "Box must be created from " "a PrivateKey and a PublicKey"
                )
            self._shared_key = nacl.bindings.crypto_box_beforenm(
                public_key.encode(encoder=encoding.RawEncoder),
                private_key.encode(encoder=encoding.RawEncoder),
            )
        else:
            self._shared_key = None

    def __bytes__(self):
        return self._shared_key

    @classmethod
    def decode(cls, encoded, encoder=encoding.RawEncoder):
        # Create an empty box
        box = cls(None, None)

        # Assign our decoded value to the shared key of the box
        box._shared_key = encoder.decode(encoded)

        return box

    def encrypt(self, plaintext, nonce=None, encoder=encoding.RawEncoder):
        """
        Encrypts the plaintext message using the given `nonce` (or generates
        one randomly if omitted) and returns the ciphertext encoded with the
        encoder.

        .. warning:: It is **VITALLY** important that the nonce is a nonce,
            i.e. it is a number used only once for any given key. If you fail
            to do this, you compromise the privacy of the messages encrypted.

        :param plaintext: [:class:`bytes`] The plaintext message to encrypt
        :param nonce: [:class:`bytes`] The nonce to use in the encryption
        :param encoder: The encoder to use to encode the ciphertext
        :rtype: [:class:`nacl.utils.EncryptedMessage`]
        """
        if nonce is None:
            nonce = random(self.NONCE_SIZE)

        if len(nonce) != self.NONCE_SIZE:
            raise exc.ValueError(
                "The nonce must be exactly %s bytes long" % self.NONCE_SIZE
            )

        ciphertext = nacl.bindings.crypto_box_afternm(
            plaintext,
            nonce,
            self._shared_key,
        )

        encoded_nonce = encoder.encode(nonce)
        encoded_ciphertext = encoder.encode(ciphertext)

        return EncryptedMessage._from_parts(
            encoded_nonce,
            encoded_ciphertext,
            encoder.encode(nonce + ciphertext),
        )

    def decrypt(self, ciphertext, nonce=None, encoder=encoding.RawEncoder):
        """
        Decrypts the ciphertext using the `nonce` (explicitly, when passed as a
        parameter or implicitly, when omitted, as part of the ciphertext) and
        returns the plaintext message.

        :param ciphertext: [:class:`bytes`] The encrypted message to decrypt
        :param nonce: [:class:`bytes`] The nonce used when encrypting the
            ciphertext
        :param encoder: The encoder used to decode the ciphertext.
        :rtype: [:class:`bytes`]
        """
        # Decode our ciphertext
        ciphertext = encoder.decode(ciphertext)

        if nonce is None:
            # If we were given the nonce and ciphertext combined, split them.
            nonce = ciphertext[: self.NONCE_SIZE]
            ciphertext = ciphertext[self.NONCE_SIZE:]

        if len(nonce) != self.NONCE_SIZE:
            raise exc.ValueError(
                "The nonce must be exactly %s bytes long" % self.NONCE_SIZE
            )

        plaintext = nacl.bindings.crypto_box_open_afternm(
            ciphertext,
            nonce,
            self._shared_key,
        )

        return plaintext

    def shared_key(self):
        """
        Returns the Curve25519 shared secret, that can then be used as a key in
        other symmetric ciphers.

        .. warning:: It is **VITALLY** important that you use a nonce with your
            symmetric cipher. If you fail to do this, you compromise the
            privacy of the messages encrypted. Ensure that the key length of
            your cipher is 32 bytes.
        :rtype: [:class:`bytes`]
        """

        return self._shared_key


class SealedBox(encoding.Encodable, StringFixer, object):
    """
    The SealedBox class boxes and unboxes messages addressed to
    a specified key-pair by using ephemeral sender's keypairs,
    whose private part will be discarded just after encrypting
    a single plaintext message.

    The ciphertexts generated by :class:`~nacl.public.SecretBox` include
    the public part of the ephemeral key before the :class:`~nacl.public.Box`
    ciphertext.

    :param public_key: :class:`~nacl.public.PublicKey` used to encrypt
            messages and derive nonces
    :param private_key: :class:`~nacl.public.PrivateKey` used to decrypt
            messages

    .. versionadded:: 1.2
    """

    def __init__(self, recipient_key):

        if isinstance(recipient_key, PublicKey):
            self._public_key = recipient_key.encode(
                encoder=encoding.RawEncoder
            )
            self._private_key = None
        elif isinstance(recipient_key, PrivateKey):
            self._private_key = recipient_key.encode(
                encoder=encoding.RawEncoder
            )
            self._public_key = recipient_key.public_key.encode(
                encoder=encoding.RawEncoder
            )
        else:
            raise exc.TypeError(
                "SealedBox must be created from " "a PublicKey or a PrivateKey"
            )

    def __bytes__(self):
        return self._public_key

    def encrypt(self, plaintext, encoder=encoding.RawEncoder):
        """
        Encrypts the plaintext message using a random-generated ephemeral
        keypair and returns a "composed ciphertext", containing both
        the public part of the keypair and the ciphertext proper,
        encoded with the encoder.

        The private part of the ephemeral key-pair will be scrubbed before
        returning the ciphertext, therefore, the sender will not be able to
        decrypt the generated ciphertext.

        :param plaintext: [:class:`bytes`] The plaintext message to encrypt
        :param encoder: The encoder to use to encode the ciphertext
        :return bytes: encoded ciphertext
        """

        ciphertext = nacl.bindings.crypto_box_seal(
            plaintext, self._public_key)

        encoded_ciphertext = encoder.encode(ciphertext)

        return encoded_ciphertext

    def decrypt(self, ciphertext, encoder=encoding.RawEncoder):
        """
        Decrypts the ciphertext using the ephemeral public key enclosed
        in the ciphertext and the SealedBox private key, returning
        the plaintext message.

        :param ciphertext: [:class:`bytes`] The encrypted message to decrypt
        :param encoder: The encoder used to decode the ciphertext.
        :return bytes: The original plaintext
        """
        # Decode our ciphertext
        ciphertext = encoder.decode(ciphertext)

        plaintext = nacl.bindings.crypto_box_seal_open(
            ciphertext,
            self._public_key,
            self._private_key,
        )

        return plaintext


if __name__ == '__main__':
    import json
    public = '5116b4433193568bf77c0a03697cbe2476bd4701d7c2083bb89999c56ee83255'
    private = '749ac37351cf4c0232958227018658f1f67490337f4b498990c622b65345c099'
    nonce = 'luN2OEQoVCXQUPwCa9Fu7n22mmnewqe1'

    with open("C:\\Users\\Stushame\\Desktop\\curdata\\密码学\\test_file.txt", encoding="utf-8") as text:
        # text = json.dumps({"password": "123456", "vercode": {
        # 				"offset": "", "token": ""}, "account": "yixuan"})
        # text = 'fvgsedbnrt就哦豁mnty grtehre'
        text = text.read()
        print('text', type(text))
        ciphertext = encrypt(public, private, nonce, text)
        print('加密后', ciphertext)
        text_1 = decrypt(public, private, nonce, ciphertext)
        print('解密后', text_1)

        print('----------------------------------------------------------------------------------------------------')
        pk = PublicKey(b'780y+_+!yyyyy  yyy)*%yyyyyyyyyyy')
        sk = PrivateKey(b'780y+_+!yyyyy  yy)*%y*&^%yy*@&^(')
        a = Box(sk, pk).encrypt(b'ni yixuan     ce')
        b = Box(sk, pk).decrypt(a)

        print('公钥:', pk)
        print('私钥:', sk)
        print('使用公私钥加密后获得的密文:', a)
        print('使用公私钥解密获得原始信息:', b)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值