import VCSEC
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import hashes, serialization
def prependLength(message):
return (len(message).to_bytes(2, 'big') + message)
try:
privKeyFile = open('private_key.pem', 'rb')
privateKey = serialization.load_pem_private_key(privKeyFile.read(), None)
privKeyFile.close()
except FileNotFoundError:
privKeyFile = open('private_key.pem', 'wb')
privateKey = ec.generate_private_key(ec.SECP256R1())
privKeyFile.write(privateKey.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()))
privKeyFile.close()
publicKey = privateKey.public_key().public_bytes(serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint)
digest = hashes.Hash(hashes.SHA1())
digest.update(publicKey)
keyId = digest.finalize()[:4]
ephemeralKey = b'\x04\x79\xc0\x50\x4a\x21\x6f\xfc\x26\x46\xb7\x57\x80\x39\x9f\x1c\xe1\x23\xf4\x01\x56\x1b\x68\x5c\x31\x83\x64\xfa\x96\xcc\x3f\xe6\x7a\x5a\xc5\x04\x8c\x44\x7a\xf8\x8d\x91\x52\x86\x5a\x1e\xfc\x15\xbb\xd5\x68\x98\xdd\x2c\x46\xf7\xa1\x9b\xad\x4f\xb2\x80\x52\xc4\x60'
curve = ec.SECP256R1()
ephemeralKey = ec.EllipticCurvePublicKey.from_encoded_point(curve, ephemeralKey)
hasher = hashes.Hash(hashes.SHA1())
aesSecret = privateKey.exchange(ec.ECDH(), ephemeralKey)
hasher.update(aesSecret)
sharedKey = hasher.finalize()[:16]
closureMoveRequest = VCSEC.ClosureMoveRequest()
closureMoveRequest.frontPassengerDoor = VCSEC.ClosureMoveType_E.CLOSURE_MOVE_TYPE_OPEN
closureMoveRequest.rearTrunk = VCSEC.ClosureMoveType_E.CLOSURE_MOVE_TYPE_CLOSE
unsignedMessage = VCSEC.UnsignedMessage()
unsignedMessage.closureMoveRequest.CopyFrom(closureMoveRequest)
unsignedMessageS = unsignedMessage.SerializeToString()
print("Unsigned Message Layout:")
print(unsignedMessage)
counter = 3
nonce = int.to_bytes(counter, 4, "big")
encryptor = AESGCM(sharedKey)
try:
encryptedMsgWithTag = encryptor.encrypt(nonce, unsignedMessageS, None)
except ValueError:
print("Error: The cryptography.io library doesn't allow nonces as small as 4 bytes anymore. Please modify the if statement in the _check_params(nonce, data, associated_date) function in the cryptography.hazmat.primitives.ciphers.aead.AESGCM class to require the minimum length to be 1")
exit()
signedMessage = VCSEC.SignedMessage()
signedMessage.protobufMessageAsBytes = encryptedMsgWithTag[:-16]
signedMessage.counter = counter
signedMessage.signature = encryptedMsgWithTag[-16:]
signedMessage.keyId = keyId
toVCSECMessage = VCSEC.ToVCSECMessage()
toVCSECMessage.signedMessage.CopyFrom(signedMessage)
print("\nTo VCSEC Message Layout:")
print(toVCSECMessage)
msg = toVCSECMessage.SerializeToString()
msg = prependLength(msg)
print("\nClosure Move Request Message To Send To Vehicle:")
print(msg.hex(" "))