예제 #1
0
 def test_aead_chacha20poly1305_ietf(self):
     if not pysodium.sodium_version_check(1, 0, 4): return
     key = binascii.unhexlify(b"4290bcb154173531f314af57f3be3b5006da371ece272afa1b5dbdd1100a1007")
     input_ = binascii.unhexlify(b"86d09974840bded2a5ca")
     nonce = binascii.unhexlify(b"cd7cf67be39c794acd7cf67b")
     for ad in [binascii.unhexlify(b"87e229d4500845a079c0"), None]:
         output = pysodium.crypto_aead_chacha20poly1305_ietf_encrypt(input_, ad, nonce, key)
         output = pysodium.crypto_aead_chacha20poly1305_ietf_decrypt(output, ad, nonce, key)
         self.assertEqual(output, input_)
예제 #2
0
 def test_aead_chacha20poly1305_ietf(self):
     if not pysodium.sodium_version_check(1, 0, 4): return
     key = binascii.unhexlify(b"4290bcb154173531f314af57f3be3b5006da371ece272afa1b5dbdd1100a1007")
     input_ = binascii.unhexlify(b"86d09974840bded2a5ca")
     nonce = binascii.unhexlify(b"cd7cf67be39c794a")
     ad = binascii.unhexlify(b"87e229d4500845a079c0")
     output = pysodium.crypto_aead_chacha20poly1305_ietf_encrypt(input_, ad, nonce, key)
     output = pysodium.crypto_aead_chacha20poly1305_ietf_decrypt(output, ad, nonce, key)
     self.assertEqual(output, input_)
def decrypt_plaintext(ciphertext: bytes, recips_bin: bytes, nonce: bytes,
                      key: bytes) -> str:
    """
    Decrypt the payload of a packed message.

    Args:
        ciphertext:
        recips_bin:
        nonce:
        key:

    Returns:
        The decrypted string

    """
    output = pysodium.crypto_aead_chacha20poly1305_ietf_decrypt(
        ciphertext, recips_bin, nonce, key)
    return output.decode("ascii")
예제 #4
0
    def deconstructSTSResponse(self, data, addr):
        # TODO verification
        # m = None
        decrypData = None
        addrStr = sts_utility.addrToString(addr)
        if addrStr in STS.STSConnectionStates.keys():
            cp = 0
            m = struct.pack('>B', data[cp])
            # if data[cp] == 2:
            cp += 1
            nonce_length = data[cp:cp + 4]
            length = struct.unpack('>I', nonce_length)[0]
            m += nonce_length
            cp += 4
            nonce = data[cp:cp + length]
            cp += length
            encrypData = data[cp:]
            if STS.STSConnectionStates[addrStr][
                    'cSuite'] == 1 or STS.STSConnectionStates[addrStr][
                        'cSuite'] == 4:
                try:
                    decrypData = pysodium.crypto_aead_chacha20poly1305_ietf_decrypt(
                        encrypData, m, nonce,
                        STS.STSConnectionStates[addrStr]['session_key'][:32])
                except:
                    decrypData = None

            # TODO suites 2 or 5
            elif STS.STSConnectionStates[addrStr][
                    'cSuite'] == 2 or STS.STSConnectionStates[addrStr][
                        'cSuite'] == 5:
                try:
                    decrypData = pysodium.crypto_aead_chacha20poly1305_decrypt(
                        encrypData, m, nonce,
                        STS.STSConnectionStates[addrStr]['session_key'][:32])
                except:
                    decrypData = None

        return decrypData
예제 #5
0
    def decode_msg(self, data):
        """Decode incoming Json data and De-Ciphering
        :param data: data received from the multicast bus
        :type data: json
        :return: xAAL msg
        :rtype: Message
        """
        # Decode json incoming data
        try:
            data_rx = json.loads(data)
        except:
            raise MessageParserError("Unable to parse JSON data")

        # Instanciate Message
        msg = Message()
        try:
            msg.targets = json.loads(data_rx['targets'])
            msg.version = data_rx['version']
            msg_time = data_rx['timestamp'][0]
        except (KeyError, IndexError):
            raise MessageParserError("Bad Message, wrong fields")

        # Replay attack, window fixed to CIPHER_WINDOW in seconds
        now = build_timestamp()[0]  # test done only on seconds ...

        if msg_time < (now - config.cipher_window):
            raise MessageParserError(
                "Potential replay attack, message too old")

        if msg_time > (now + config.cipher_window):
            raise MessageParserError(
                "Potential replay attack, message too young")

        # Payload De-Ciphering
        ad = data_rx['targets'].encode("utf8")  # Additional Data
        nonce = build_nonce(data_rx['timestamp'])

        # base64 decoding
        if 'payload' in data_rx:
            ciph = base64.b64decode(data_rx['payload'])
        else:
            raise MessageParserError("Bad Message, no payload found!")

        # chacha20 deciphering
        try:
            pjson = pysodium.crypto_aead_chacha20poly1305_ietf_decrypt(
                ciph, ad, nonce, self.cipher_key)
        except:
            raise MessageParserError("Unable to decrypt msg")

        # Decode Json
        try:
            payload = json.loads(pjson)
        except:
            raise MessageParserError(
                "Unable to parse JSON data in payload after decrypt")

        # Message unpacking header
        if 'header' in payload:
            head = {}
            for (name, value) in payload["header"].items():
                head[name] = value
            msg.header = head
        else:
            raise MessageParserError(
                "Bad Message, none header found in payload!")

        # Message unpacking body
        if 'body' in payload:
            body = {}
            for (name, value) in payload["body"].items():
                body[name] = value
            msg.body = body

        return msg
예제 #6
0
import binascii as ba
import pysodium as nacl
import msgpack
from struct import unpack
import sys

key = sys.argv[1]
msg = sys.argv[2]

mp = ba.unhexlify(msg)
frame = msgpack.loads(mp)
print(frame)
cipher = frame[b'data']
print(len(cipher))
print(ba.hexlify(cipher))
nonce = frame[b'nonce']
print(len(nonce))
print(ba.hexlify(nonce))
data = nacl.crypto_aead_chacha20poly1305_ietf_decrypt(cipher, None, nonce, key)
print(ba.hexlify(data))
print(unpack('hHHH', data))
예제 #7
0
tag, nonce = decoder.read()
ensure_tag(decoder, asn1.Numbers.Integer)
tag, interval = decoder.read()
decoder.leave()
ensure_tag(decoder, asn1.Numbers.OctetString)
tag, ctext = decoder.read()

# re-write additional data into a single DER structure
encoder = asn1.Encoder()
encoder.start()
encoder.enter(asn1.Numbers.Sequence)
encoder.write(enckey, asn1.Numbers.OctetString)
encoder.write(nonce, asn1.Numbers.OctetString)
encoder.write(interval, asn1.Numbers.Integer)
encoder.leave()
AD = encoder.output()

try:
    e = privkey.decrypt(enckey, interval)
except ValueError:
    print("<Error>: Unable to derive key for interval")
    sys.exit(1)
chachakey = sha256(e.to_bytes()).digest()

message = pysodium.crypto_aead_chacha20poly1305_ietf_decrypt(ciphertext=ctext,
                                                             ad=AD,
                                                             nonce=nonce,
                                                             key=chachakey)

print(message.decode(), end='')