MCPcopy Create free account
hub / github.com/attermann/microReticulum / decrypt

Method decrypt

src/microReticulum/Identity.cpp:494–540  ·  view source on GitHub ↗

Decrypts information for the identity. :param ciphertext: The ciphertext to be decrypted as *bytes*. :returns: Plaintext as *bytes*, or *None* if decryption fails. :raises: *KeyError* if the instance does not hold a private key. */

Source from the content-addressed store, hash-verified

492:raises: *KeyError* if the instance does not hold a private key.
493*/
494const Bytes Identity::decrypt(const Bytes& ciphertext_token) const {
495 assert(_object);
496 TRACE("Identity::decrypt: decrypting data...");
497 if (!_object->_prv) {
498 throw std::runtime_error("Decryption failed because identity does not hold a private key");
499 }
500 if (ciphertext_token.size() <= Type::Identity::KEYSIZE/8/2) {
501 DEBUGF("Decryption failed because the token size %lu was invalid.", ciphertext_token.size());
502 return {Bytes::NONE};
503 }
504 Bytes plaintext;
505 try {
506 //peer_pub_bytes = ciphertext_token[:Identity.KEYSIZE//8//2]
507 Bytes peer_pub_bytes = ciphertext_token.left(Type::Identity::KEYSIZE/8/2);
508 //peer_pub = X25519PublicKey.from_public_bytes(peer_pub_bytes)
509 //Cryptography::X25519PublicKey::Ptr peer_pub = Cryptography::X25519PublicKey::from_public_bytes(peer_pub_bytes);
510 TRACEF("Identity::decrypt: peer public key: %s", peer_pub_bytes.toHex().c_str());
511
512
513 // CRYPTO: create shared key for key exchange using peer public key
514 //shared_key = _object->_prv->exchange(peer_pub);
515 Bytes shared_key = _object->_prv->exchange(peer_pub_bytes);
516 TRACEF("Identity::decrypt: shared key: %s", shared_key.toHex().c_str());
517
518 Bytes derived_key = Cryptography::hkdf(
519 DERIVED_KEY_LENGTH,
520 shared_key,
521 get_salt(),
522 get_context()
523 );
524 TRACEF("Identity::decrypt: derived key: %s", derived_key.toHex().c_str());
525
526 Cryptography::Token token(derived_key);
527 //ciphertext = ciphertext_token[Identity.KEYSIZE//8//2:]
528 Bytes ciphertext(ciphertext_token.mid(Type::Identity::KEYSIZE/8/2));
529 TRACEF("Identity::decrypt: Token decrypting data of length %lu", ciphertext.size());
530 TRACEF("Identity::decrypt: ciphertext: %s", ciphertext.toHex().c_str());
531 plaintext = token.decrypt(ciphertext);
532 TRACEF("Identity::decrypt: plaintext: %s", plaintext.toHex().c_str());
533 //TRACEF("Identity::decrypt: Token decrypted data of length %lu", plaintext.size());
534 }
535 catch (const std::exception& e) {
536 DEBUGF("Decryption by %s failed: %s", toString().c_str(), e.what());
537 }
538
539 return plaintext;
540}
541
542/*
543Signs information by the identity.

Callers

nothing calls this directly

Calls 5

leftMethod · 0.80
toHexMethod · 0.80
exchangeMethod · 0.80
midMethod · 0.80
sizeMethod · 0.45

Tested by

no test coverage detected