00 JWT && RSA & AES & Cryptography & Certificates & Behind the scene - lukes8/wiki-notes GitHub Wiki

This is sample of token - authorities -> json array with json objects

Json token:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJhdXRob3JpdGllcyI6W3siYXV0aG9yaXR5IjoiUk9MRV9BRE1JTiJ9LHsiYXV0aG9yaXR5IjoiUkVBRCJ9LHsiYXV0aG9yaXR5IjoiQ1JFQVRFIn0seyJhdXRob3JpdHkiOiJERUxFVEUifV19.1mKIuxF7mx83qH3vtYGhglVtOZFByUi4GjY2131nYwY

https://jwt.io/

Output:
{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022,
  "authorities": [
  {"authority": "ROLE_ADMIN"},
  {"authority": "READ"},
  {"authority": "CREATE"},
  {"authority": "DELETE"}
  ]
}

Api gateway, centralized global security, proxy

so we can talk about it like microservices are behind the proxy or behind the firewall right? This is common situation in most of companies who wants their staff cannot visit behind proxy to internet. As proxy serves as a way to protect their private network from outside world. The same case we can use in case of Agatha down. Microservices are behind the proxy and still protected even we dont have implemented security rules directly in them.
ChatGPT
Exactly! That's a great analogy. Just like how companies often use proxies or firewalls to protect their internal networks from unauthorized access from the internet, microservices can be similarly protected behind a proxy, in this case, the API Gateway (Agatha).

Even if the API Gateway is down for some reason, the microservices remain protected behind the proxy, ensuring that they are not directly exposed to the internet and unauthorized access is prevented by network security measures such as firewalls.

This architecture provides an additional layer of security and isolation for the microservices, allowing organizations to enforce security policies, monitor traffic, and control access to their services effectively. It also ensures that even if the central security component (Agatha) experiences downtime, the underlying microservices remain shielded from external threats.

Fine-grained security level method, preauthorize, roles, authorities, global auth and authorization

Bob Controller with Combined Role and Authority Access

@RestController
@RequestMapping("/bob")
public class BobController {

    // Endpoints accessible based on roles
    @PreAuthorize("hasRole('ROLE_USER')")
    @GetMapping("/role/user/data")
    public ResponseEntity<String> getUserRoleData() {
        return ResponseEntity.ok("Data accessible by users with ROLE_USER");
    }

    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/role/admin/data")
    public ResponseEntity<String> getAdminRoleData() {
        return ResponseEntity.ok("Data accessible by users with ROLE_ADMIN");
    }

    // Endpoints accessible based on authorities
    @PreAuthorize("hasAuthority('READ_PRIVILEGE')")
    @GetMapping("/authority/user/data")
    public ResponseEntity<String> getUserAuthorityData() {
        return ResponseEntity.ok("Data accessible by users with READ_PRIVILEGE");
    }

    @PreAuthorize("hasAuthority('WRITE_PRIVILEGE')")
    @GetMapping("/authority/admin/data")
    public ResponseEntity<String> getAdminAuthorityData() {
        return ResponseEntity.ok("Data accessible by users with WRITE_PRIVILEGE");
    }

    // Endpoints accessible based on both role and authority
    @PreAuthorize("hasRole('ROLE_USER') and hasAuthority('READ_PRIVILEGE')")
    @GetMapping("/role-and-authority/user/data")
    public ResponseEntity<String> getUserRoleAndAuthorityData() {
        return ResponseEntity.ok("Data accessible by users with ROLE_USER and READ_PRIVILEGE");
    }

    @PreAuthorize("hasRole('ROLE_ADMIN') and hasAuthority('WRITE_PRIVILEGE')")
    @GetMapping("/role-and-authority/admin/data")
    public ResponseEntity<String> getAdminRoleAndAuthorityData() {
        return ResponseEntity.ok("Data accessible by users with ROLE_ADMIN and WRITE_PRIVILEGE");
    }

    // Public endpoint accessible by everyone
    @PermitAll
    @GetMapping("/public/data")
    public ResponseEntity<String> getPublicData() {
        return ResponseEntity.ok("Public data accessible by everyone");
    }
}

How JWT token looks like, base64, #signature

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Header: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
This part is Base64 encoded. When decoded, it represents the header JSON data.

Payload: eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ
This part is also Base64 encoded. When decoded, it represents the payload JSON data.

Signature: SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
This part is not Base64 encoded. It represents the signature, which is a hash generated from the concatenated and encoded header and payload using a cryptographic algorithm and a secret key.

To extract the actual header and payload JSON data, you would need to decode these parts using a Base64 decoder. The signature remains in its hashed form and does not require decoding.

JWT token, hashing, #just_hash_code, #token_data, #secret

A JWT (JSON Web Token) consists of three parts separated by dots: header, payload, and signature. Here's a breakdown of each part:

Header: Contains metadata about the token, such as the type of token (JWT) and the hashing algorithm used for the signature. The header is typically encoded using Base64.

Payload: Contains the claims or statements about the user or entity, such as user ID, role, or any other relevant information. The payload is also encoded using Base64.

Signature: Generated by hashing the concatenated header and payload with a secret key using a cryptographic hashing algorithm, such as HMAC (Hash-based Message Authentication Code). The signature provides integrity protection for the token and allows the recipient to verify its authenticity.

The signature is indeed a hash code calculated using the token data (header and payload) and a secret key. It serves as a digital signature, ensuring that the token has not been tampered with and was generated by a trusted source.

On the server side, the signature can be verified by recalculating it using the same secret key and comparing it with the signature included in the token. If the recalculated signature matches the signature in the token, it confirms the token's authenticity and integrity, allowing the server to trust the information contained in the token.

What is checksum, hash code, base64, differences, encryption,

Checksums:
Used for detecting errors or ensuring data integrity during transmission or storage.
Calculated using simple algorithms to quickly verify that the data has not been corrupted or tampered with during transit.
Help detect errors but don't provide guarantees against intentional tampering by an attacker.

Hash Codes:
Used for a broader range of security and integrity purposes, including data integrity verification, digital signatures, password hashing, and data indexing.
Generated using cryptographic hash functions, offering stronger guarantees of data integrity and security.
Possess cryptographic properties such as collision resistance and the avalanche effect, making them suitable for sensitive applications where data integrity and security are paramount.

Hashing (same as hash codes, just more info):
One-way process that converts input data into a fixed-size hash value using a hash function.
The output of a hash function is typically a fixed size, regardless of the size of the input data.
Cannot be reversed to obtain the original input data.
Designed for data integrity verification, password hashing, and digital signatures.
Examples of hashing algorithms include SHA-256, SHA-512, MD5 (Message Digest Algorithm 5), and bcrypt.

Base64:
Used for encoding binary data into printable ASCII characters.
Converts binary data into a format that is safe for transmission over text-based protocols or for storage in text-based formats like XML or JSON.
Does not provide any cryptographic properties; it's purely a representation format for binary data.


Encryption:
Reversible process that transforms plaintext data into ciphertext using an encryption algorithm and a key.
The ciphertext can be decrypted back into the original plaintext using the appropriate decryption key.
Designed to protect the confidentiality of data during transmission or storage.
Examples of encryption algorithms include AES (Advanced Encryption Standard), RSA, and Triple DES (Data Encryption Standard).



Common Hashing Methods, Common Encryption Methods

Common Hashing Methods for Certificate Signature:
SHA-256 (Secure Hash Algorithm 256-bit)
SHA-512 (Secure Hash Algorithm 512-bit)
MD5 (Message Digest Algorithm 5)
SHA-1 (Secure Hash Algorithm 1) - Deprecated due to vulnerabilities

Common Encryption Methods for Certificate Signature:
RSA (Rivest-Shamir-Adleman)
DSA (Digital Signature Algorithm)
ECDSA (Elliptic Curve Digital Signature Algorithm)
ECDH (Elliptic Curve Diffie-Hellman)
AES (Advanced Encryption Standard) - Often used for symmetric encryption alongside asymmetric algorithms for key exchange and digital signatures.

How X.509 works, certificates, story

Questions on Bob and Polly story around X.509
so when Polly wants to verify Bob certificate she just get certificate as whole. The cert contains data and digital signature. Where data can be for example public key of Bob, expiration date, info about CA authority. And signature was generated by Atagha private key. The value behind signature is basically hash code or checksum from certificate data, true? 


Certificate Contents:

When Polly wants to verify Bob's certificate, she receives the entire certificate, which includes various data fields such as:
Public key of Bob.
Expiration date of the certificate.
Information about the CA authority (Agatha).
Additionally, the certificate contains a digital signature generated by Agatha's private key.
Signature Verification:

To verify the certificate's authenticity, Polly uses Agatha's public key, which she already possesses or can obtain from a trusted source.
Polly calculates a hash value of the certificate data (excluding the signature) using a hash function.
She then decrypts the digital signature using Agatha's public key to obtain the original hash value that was signed by Agatha's private key.
If the calculated hash value matches the decrypted hash value obtained from the signature, it confirms that the certificate data has not been altered since it was signed by Agatha.
This process ensures the integrity and authenticity of the certificate.
Signature as Hash Value:

Yes, the value behind the digital signature is essentially a hash code or checksum of the certificate data.
Agatha's private key is used to create a digital signature over the hash value of the certificate data, ensuring that any changes to the certificate contents would result in a different hash value and thus invalidate the signature.
In summary, Polly verifies Bob's certificate by confirming that the digital signature on the certificate matches the calculated hash value of the certificate data, ensuring its integrity and authenticity. This process allows Polly to trust the information contained in Bob's certificate and establish a secure communication channel with him.

OpenVPN, SSL / TSL story Bob client and Polly as OpenVPN server, handshake and communication in foreign language in cyphers

so passing certificates is just first step we can say. This is pre-condition for next step which is authentication itself. 
This is like first step is handshake in some insecure collectiv of people and then second step is 
like secure communication via custom foreign cypher language to ensure that only they two Bob and Polly can understand each other. 
And noone else. The second step is used to signed or unsigned messages with keys (private/public). The communication is basically secured via RSA and AES so it is secure. 
But we need also ensure authenticity of both users as Bob want to be sure that he talks with Polly. But without second step it can be whatever passed certificate of Bob. 
It can be somebody who pretend to be Bob.

ChatGPT
Yes, you've articulated the process and importance of SSL/TLS (or any PKI-based system) quite well:

Certificate Exchange as a Precondition:

The initial exchange of certificates (client.crt from Bob and server.crt from Polly) is indeed the first step in establishing a secure connection.
This step ensures that both parties have the necessary public keys to establish a secure channel and verify identities.
Authentication and Secure Communication:

After the certificates are exchanged, the SSL/TLS handshake proceeds to authentication and negotiation of encryption parameters (like RSA and AES).
Authentication verifies the identities of both Bob and Polly:
Bob proves his identity by signing data with his private key (client.key).
Polly verifies Bob's identity using his certificate (client.crt), which includes Bob's public key and a signature from a trusted CA.
Ensuring Authenticity and Integrity:

Authenticity is crucial to prevent impersonation. The exchange of signed messages and verification of certificates ensure that only legitimate parties can participate in secure communication.
Integrity is maintained through digital signatures, ensuring that messages cannot be altered without detection.
Encryption Mechanisms (RSA and AES):

RSA is used during the SSL/TLS handshake for key exchange and digital signatures, leveraging asymmetric cryptography.
AES (or other symmetric encryption algorithms) are used for efficient encryption of data during the secure session, ensuring confidentiality.
Importance of the Second Step (Authentication):

Without proper authentication (verifying the digital signatures and certificates), there's a risk of a man-in-the-middle attack or unauthorized access.
Bob needs assurance that he is communicating securely with Polly and not an impostor.
Analogy to Handshake and Secure Communication:
Handshake Analogy:

The initial exchange of certificates is akin to an introduction or handshake in an insecure group.
It establishes identities and prepares for secure communication.
Secure Communication Analogy:

After the handshake, secure communication is like speaking in a foreign ciphered language (AES) that only Bob and Polly understand.
This ensures that their conversation remains confidential and secure from eavesdroppers.
In summary, SSL/TLS ensures both authentication (via certificates and digital signatures) and secure communication (via encryption), providing Bob and Polly with a trusted and confidential means to communicate over potentially insecure networks.

OpenVPN, ovpn file, typical settings, configuration, image

OpenVPN - it is like access to organization network where we can access normally via secure channel or tunnel via SSL/TLS certificates

the company-config.ovpn file typically contains:
ca ca.crt
cert bob.crt
key bob.key


image

What is bob.key, ca.crt and bob.crt

ca.crt -> this is certificate of CA simply saying cert of certificate authority that issued our certificates (lets say Bob and Pollys certs)
bob.crt -> this is Bobs client certificate that is used to pass info to second side (Polly or openVPN). This info then Polly can use to communicate with Bob in secure channel. Polly can simply verifies (via Bobs public key) that data was really signed by Bob (via Bobs private key). And vice versa.
bob.key -> this is private key of Bob that is used to sign data over SSL TLS communication channel

First step - pass certificate with info and sign verification over CA authority
Second step - RSA/AES communication with sign authentication which involves signature check

How private key and x.509 certificate looks like

Encrypted via password
-----BEGIN ENCRYPTED PRIVATE KEY-----
random nbr
-----END ENCRYPTED PRIVATE KEY-----

This means that private key is encrypted by password and hence before SSL handshake we need to provide password to properly pass certificate data to second side.



Not encrypted - this is encoded form of certificate that has also text form that is not transmitted over network - just for our eyes
-----BEGIN CERTIFICATE-----
random nbr
-----END CERTIFICATE-----


The structure of an X.509 v3 [digital certificate](https://en.wikipedia.org/wiki/Digital_certificate) is as follows:

image

⚠️ **GitHub.com Fallback** ⚠️