code projected over woman
Photo by ThisIsEngineering on Pexels.com

In-Depth Guide to Public Key/Private Key (Asymmetric Cryptography)

Target Audience:

  • Engineers and students looking to learn the basics of cryptographic technologies
  • System architects considering enhanced security measures
  • Anyone interested in implementation examples using Python or Vue.js
  • Developers wanting to understand key management in database design

Summary (Introductory Overview)

  • Overview of Asymmetric Encryption: Leveraging public and private keys to achieve both confidentiality and authentication
  • Flow Diagrams: Complete flow from key generation through encryption/decryption and signing/verification
  • Advantages & Disadvantages: Security advantages with attention to processing costs
  • Implementation Samples: Python (cryptography library) and Vue.js (WebCrypto API)
  • Database Design Example: Table definitions for key pairs and signature metadata

1. Core Concepts of Asymmetric Encryption

Asymmetric encryption, which uses a pair of public and private keys, enables secure communication and authentication.
Unlike symmetric key encryption (using the same key for both encryption and decryption), which suffers from key distribution problems, asymmetric encryption addresses these issues as follows:

  1. Key Pair Generation
  2. Encryption & Decryption
  3. Digital Signing

With these three steps, you can simultaneously guarantee both confidentiality and authentication, which is the greatest strength of asymmetric cryptography.


2. Conceptual Overview: Entire Flow and Processes

When adopting asymmetric encryption, it’s crucial to first understand the overall processing flow. Below, we explain the three primary use cases—key generation, encryption/decryption, and signing/verification—in sequence.

2.1 Key Pair Generation Flow

flowchart TD
  A[Start] --> B[Generate Random Numbers]
  B --> C[Compute Public & Private Keys]
  C --> D[Distribute Public Key Externally]
  C --> E[Securely Store Private Key]
  D --> F[Done]
  E --> F
  • Random Number Generation: Ensure a source with sufficient entropy
  • Key Computation: Use a one-way mathematical function to derive the public and private keys
  • Public Key Distribution: Publish via certificates or server configuration
  • Private Key Storage: Store in an HSM, KMS, or encrypted storage

2.2 Data Encryption & Decryption Flow

flowchart TD
  A[Sender Prepares Plaintext] --> B[Encrypt with Recipient’s Public Key]
  B --> C[Transmit Ciphertext]
  C --> D[Decrypt with Private Key]
  D --> E[Recipient Obtains Plaintext]
  • Encryption: Use a padded algorithm like RSA-OAEP
  • Transmission: Exchange ciphertext over TLS or application-layer communication
  • Decryption: Only the private key can decrypt, ensuring confidentiality

2.3 Digital Signing & Verification Flow

flowchart TD
  A[Signer Prepares Plaintext] --> B[Generate Signature with Private Key]
  B --> C[Send Signature and Plaintext]
  C --> D[Verifier Checks with Public Key]
  D --> |Match| E[Authenticity & Integrity Confirmed]
  D --> |Mismatch| F[Verification Failed]
  • Signature Generation: Encrypt the hash with padding like PSS
  • Verification: Decrypt the signature with the public key and compare hashes
  • Tamper Detection: If hashes match, origin is confirmed; otherwise, verification fails

3. Advantages & Disadvantages of Asymmetric Encryption

Advantages

  • Solves Key Distribution: Public keys can be freely shared
  • Prevents Impersonation: Digital signatures guarantee sender identity
  • Scalability: Simplified key management for many-to-many communications

Disadvantages

  • High Processing Cost: Requires larger numerical operations compared to symmetric ciphers
  • Longer Key Lengths: Recommended key sizes (e.g., 2048 bits) increase data size
  • Operational Complexity: Requires key management, rotation, and revocation lists

4. Python Implementation Sample (cryptography Library)

Below is a sample using Python’s cryptography library for key generation, encryption, decryption, signing, and verification.

from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization, hashes

# 1. Key Pair Generation
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
public_key = private_key.public_key()

# Export private key in PEM format
pem_priv = private_key.private_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PrivateFormat.TraditionalOpenSSL,
    encryption_algorithm=serialization.NoEncryption()
)

# Export public key in PEM format
pem_pub = public_key.public_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PublicFormat.SubjectPublicKeyInfo
)

# 2. Encryption
message = b"Hello, world!"
ciphertext = public_key.encrypt(
    message,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None
    )
)

# 3. Decryption
plaintext = private_key.decrypt(
    ciphertext,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None
    )
)
print(plaintext.decode())

# 4. Digital Signature
signature = private_key.sign(
    message,
    padding.PSS(
        mgf=padding.MGF1(hashes.SHA256()),
        salt_length=padding.PSS.MAX_LENGTH
    ),
    hashes.SHA256()
)

# 5. Signature Verification
try:
    public_key.verify(
        signature,
        message,
        padding.PSS(
            mgf=padding.MGF1(hashes.SHA256()),
            salt_length=padding.PSS.MAX_LENGTH
        ),
        hashes.SHA256()
    )
    print("Signature verification succeeded")
except Exception as e:
    print("Signature verification failed:", e)

5. Vue.js Implementation Sample (WebCrypto API)

In the browser, you can use the standard WebCrypto API. Below is an example integrated into a Vue.js component.

<template>
  <div>
    <button @click="generateKeys">Generate Key Pair</button>
    <button @click="encryptData">Encrypt</button>
    <button @click="decryptData">Decrypt</button>
    <p>Decrypted Text: {{ decrypted }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      publicKey: null,
      privateKey: null,
      ciphertext: null,
      decrypted: ''
    }
  },
  methods: {
    async generateKeys() {
      const keyPair = await window.crypto.subtle.generateKey(
        {
          name: "RSA-OAEP",
          modulusLength: 2048,
          publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
          hash: "SHA-256"
        },
        true,
        ["encrypt", "decrypt"]
      );
      this.publicKey = keyPair.publicKey;
      this.privateKey = keyPair.privateKey;
      alert("Key pair generated");
    },
    async encryptData() {
      const encoder = new TextEncoder();
      const data = encoder.encode("Hello, Vue.js!");
      this.ciphertext = await window.crypto.subtle.encrypt(
        { name: "RSA-OAEP" }, this.publicKey, data
      );
      alert("Encryption complete");
    },
    async decryptData() {
      const decryptedBuffer = await window.crypto.subtle.decrypt(
        { name: "RSA-OAEP" }, this.privateKey, this.ciphertext
      );
      const decoder = new TextDecoder();
      this.decrypted = decoder.decode(decryptedBuffer);
    }
  }
}
</script>

6. Database Design Example (Table Definition)

Column Name Data Type Constraints Description
id SERIAL PRIMARY KEY NOT NULL Record identifier
user_id INTEGER NOT NULL, FOREIGN KEY ID of the key owner
public_key_pem TEXT NOT NULL PEM-formatted public key
private_key_enc BYTEA NOT NULL Encrypted private key (e.g., AES256)
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP Record creation timestamp
revoked BOOLEAN DEFAULT FALSE Key revocation flag
revoked_at TIMESTAMP WITH TIME ZONE Timestamp when key was revoked

Key Points:

  • Always store private keys encrypted.
  • Use a revoked flag and timestamp instead of a full CRL.
  • Index user_id for query performance.

7. Operational Considerations and Best Practices

  • Enforce Key Management Policies: Protect private keys in HSMs or KMS; never store them on application servers.
  • Key Rotation: Regularly rotate keys and promptly revoke old ones.
  • CRL & OCSP: Implement PKI to provide real-time revocation information.
  • Performance Monitoring: As encryption is CPU-intensive, consider load balancing and caching.

8. Conclusion

Asymmetric encryption using public and private keys is a powerful technique for ensuring both confidentiality and authentication. In this guide, we covered:

  1. Fundamental concepts of asymmetric encryption
  2. End-to-end flow and process diagrams
  3. Advantages and disadvantages
  4. Python (cryptography) implementation sample
  5. Vue.js (WebCrypto API) implementation sample
  6. Database design example
  7. Operational considerations

Leverage these insights to integrate secure communications and digital signature features into your systems and build more trusted services.


Author’s Note:
Visualizing the entire system flow brings clarity and confidence to the design phase. Try running the provided diagrams and code samples hands-on to deepen your understanding—happy learning!

By greeden

Leave a Reply

Your email address will not be published. Required fields are marked *

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)