From fb7a728aa4222ffc4a2552547f66da86a805b618 Mon Sep 17 00:00:00 2001 From: tsousa111 Date: Fri, 19 Apr 2024 19:52:23 +0100 Subject: [PATCH] [PD1] decryptMessageContent implemented needs testing --- .../internal/utils/cryptoUtils/cryptoUtils.go | 40 ++++++++++++++----- 1 file changed, 31 insertions(+), 9 deletions(-) diff --git a/Projs/PD1/internal/utils/cryptoUtils/cryptoUtils.go b/Projs/PD1/internal/utils/cryptoUtils/cryptoUtils.go index 58a0fbe..86b147c 100644 --- a/Projs/PD1/internal/utils/cryptoUtils/cryptoUtils.go +++ b/Projs/PD1/internal/utils/cryptoUtils/cryptoUtils.go @@ -95,8 +95,8 @@ func (k *KeyStore) GetServerTLSConfig() *tls.Config { } tlsConfig.ClientCAs = caCertPool //Request one valid or invalid certificate - //FIX: SERVER ACCEPTS CONNECTIONS WITH UNMATCHING OR - // NO CERTIFICATE, NEEDS TO BE CHANGED SOMEHOW + // FIX: SERVER ACCEPTS CONNECTIONS WITH UNMATCHING OR + // NO CERTIFICATE, NEEDS TO BE CHANGED SOMEHOW tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert return tlsConfig } @@ -121,18 +121,18 @@ func (k *KeyStore) GetClientTLSConfig() *tls.Config { if err != nil { return err } - oidMap := ExtractAllOIDValues(cert) + oidMap := ExtractAllOIDValues(cert) // Check if the certificate is signed by the specified CA _, err = cert.Verify(opts) if err != nil { - return errors.New("certificate not signed by trusted CA") + return errors.New("certificate not signed by trusted CA") } - //Check if the pseudonym field is set to "SERVER" - if oidMap["2.5.4.65"] != "SERVER"{ - return errors.New("peer isn't the server") - } + //Check if the pseudonym field is set to "SERVER" + if oidMap["2.5.4.65"] != "SERVER" { + return errors.New("peer isn't the server") + } } return nil } @@ -179,8 +179,30 @@ func (k KeyStore) EncryptMessageContent(receiverCert *x509.Certificate, content } func (k KeyStore) DecryptMessageContent(senderCert *x509.Certificate, cipherContent []byte) []byte { + encryptedDataKey, encryptedMsg := unPair(cipherContent) + dataKey, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, k.GetPrivKey(), encryptedDataKey, nil) + if err != nil { + log.Panicln("Could not decrypt dataKey: ", err) + } + // decrypt ciphertext + cipher, err := chacha20poly1305.New(dataKey) + if err != nil { + log.Panicln("Could not create cipher: ", err) + } - return nil + nonce, ciphertext := encryptedMsg[:cipher.NonceSize()], encryptedMsg[cipher.NonceSize():] + contentAndSig, err := cipher.Open(nil, nonce, ciphertext, nil) + if err != nil { + log.Panicln("Could not decrypt ciphertext: ", err) + } + // check signature with sender public key + content, signature := unPair(contentAndSig) + hashedContent := sha256.Sum256(content) + senderKey := senderCert.PublicKey.(*rsa.PublicKey) + if err := rsa.VerifyPKCS1v15(senderKey, crypto.SHA256, hashedContent[:], signature); err != nil { + log.Panicln("Signature is not valid: ", err) + } + return content } func pair(l []byte, r []byte) []byte {