The Programmer's Guide
  • About
  • Algorithm
    • Big O Notation
      • Tree
      • Problems
    • Basic Notes
    • Data Structure Implementation
      • Custom LinkedList
      • Custom Stack
      • Custom Queue
      • Custom Tree
        • Binary Tree Implementation
        • Binary Search Tree Implementation
        • Min Heap Implementation
        • Max Heap Implementation
        • Trie Implementation
      • Custom Graph
        • Adjacency List
        • Adjacency Matrix
        • Edge List
        • Bidirectional Search
    • Mathematical Algorithms
      • Problems - Set 1
      • Problems - Set 2
    • Bit Manipulation
      • Representation
      • Truth Tables
      • Number System
        • Java Program
      • Problems - Set 1
    • Searching
    • Sorting
    • Array Algorithms
    • String Algorithms
    • Tree
      • Tree Traversal Techniques
      • Tree Implementation
      • Applications of Trees
      • Problems - Set 1
    • Graph
      • Graph Traversal Techniques
      • Shortest Path Algorithms
      • Minimum Spanning Tree (MST) Algorithms
    • Dynamic Programming
      • Problems - Set 1
    • Recursion
    • Parallel Programming
    • Miscellaneous
      • Problems - Set 1
  • API
    • API Basics
      • What is an API?
      • Types of API
        • Comparison - TBU
      • Synchronous vs Asynchronous API
    • API Architecture
      • Synchronous & Asynchronous Communication
    • API Specification
  • Cloud Computing
    • Cloud Fundamentals
      • Cloud Terminology
      • Core Terminology
      • Cloud Models
      • Cloud Service Models
      • Benefits, Challenges and Risk of Cloud Computing
      • Cloud Ecosystem
  • Database
    • DBMS
      • Types of DBMS
        • Relational DBMS (RDBMS)
        • NoSQL DBMS
        • Object-Oriented DBMS (OODBMS)
        • Columnar DBMS
        • In-Memory DBMS
        • Distributed DBMS
        • Cloud-Based DBMS
        • Hierarchical DBMS
      • DBMS Architecture
      • DBMS Structure
    • SQL Databases
      • Terminology
      • RDBMS Concepts
        • Entity Relationship Diagram (ERD)
          • ERD Examples
        • Normalization
        • Denormalization
        • ACID & BASE Properties
          • ACID Properties
          • BASE Properties
        • Locking and Unlocking
      • SQL Fundamentals
        • SQL Commands
          • DDL (Data Definition Language)
          • DML (Data Manipulation Language)
          • DCL (Data Control Language)
          • TCL (Transaction Control Language)
          • DQL (Data Query Language)
        • SQL Operators
          • INTERSECT
          • EXCEPT
          • MINUS
          • IN and NOT IN
          • EXISTS and NOT EXISTS
        • SQL Clauses
          • Joins
          • OVER
          • WITH
          • CONNECT BY
          • MODEL
          • FETCH FIRST
          • KEEP
          • OFFSET with FETCH
        • SQL Functions
          • Oracle Specific
        • SQL Data Types
          • Numeric Types
          • Character Types
          • Date & Time Types
          • Large Object Types
        • Others
          • Indexing
      • Vendor Specific Concepts
        • Oracle Specific
          • Data Types
          • Character Set
          • Rownum, Rowid, Urowid
          • Order of Execution of the query
          • Keys
          • Tablespace
          • Partition
      • Best Practice
      • Resources & References
        • O’Reilly SQL Cookbook (2nd Edition)
          • 1. Retrieving Records
          • 2. Sorting Query Results
          • 3. Working with Multiple Tables
          • 4. Inserting, Updating, and Deleting
          • 5. Metadata Queries
          • 6. Working with Strings
          • 7. Working with Numbers
          • 8. Date Arithmetic
          • 9. Date Manipulation
          • 10. Working with Ranges
          • 11. Advanced Searching
          • 12. Reporting and Reshaping
          • 13. Hierarchical Queries
          • 14. Odds 'n' Ends
    • SQL vs NoSQL
    • Best Practices
  • Git
    • Commands
      • Setup and Configuration Commands
      • Getting and Creating Projects
      • Tracking Changes
      • Branching and Merging
      • Sharing and Updating Projects
      • Inspection and Comparison
      • Debugging
      • Patching
      • Stashing and Cleaning
      • Advanced Manipulations
    • Workflows
      • Branching Strategies
        • Git Flow
        • Trunk-Based Development
        • GitHub Flow
        • Comparison
      • Merge Strategies
        • Merge
        • Rebase
        • Squash
        • Fast-forward vs No-fast-forward
        • MR vs PR
      • Conflict Resolution
        • Handling Merge Conflicts
        • Merge Conflicts
        • Rebase Conflicts
        • Divergent Branches After git pull
        • Force Push
      • Patch & Recovery
        • Cherry-pick strategies
        • Revert vs Reset
        • Recover from a bad rebase
      • Rebasing Practices
        • Merge vs Rebase
        • Rebase develop branch on main branch
      • Repository Management
        • Working Directory
        • Mirror a repository
        • Convert a local folder to a Git repo
        • Backup and restore a Git repository
  • Java
    • Java Installation
    • Java Distributions
    • Java Platform Editions
      • Java SE
      • Java EE
      • Jakarta EE
      • Java ME
      • JavaFX
    • Java Overview
      • OOP Principles
        • Encapsulation
        • Inheritance
        • Polymorphism
        • Abstraction
          • Abstract Class & Method
          • Interface
            • Functional Interfaces
            • Marker Interfaces
          • Abstract Class vs Interface
      • OOP Basics
        • What is a Class?
          • Types of Classes
        • What is an Object?
          • Equals and HashCode
            • FAQ
          • Shallow Copy and Deep Copy
          • Ways to Create Object
          • Serialization & Deserialization
        • Methods & Fields
          • Method Overriding & Overloading
          • Method Signature & Header
          • Variables
        • Constructors
        • Access Modifiers
      • Parallelism & Concurrency
        • Ways to Identify Thread Concurrency or Parallelism
        • Thread Basics
          • Thread vs Process
          • Creating Threads
          • Thread Context Switching
          • Thread Lifecycle & States
          • Runnable & Callable
          • Types of Threads
          • Thread Priority
        • Thread Management & Synchronisation
          • Thread Resource Sharing
          • Thread Synchronization
            • Why is Synchronization Needed?
            • Synchronized Blocks & Methods
          • Thread Lock
            • Types of Locks
            • Intrinsic Lock (Monitor Lock)
            • Reentrant Lock
          • Semaphore
          • Thread Starvation
          • Thread Contention
          • Thread Deadlock
          • Best Practices for Avoiding Thread Issues
      • Keywords
        • this
        • super
        • Access Modifiers
      • Data Types
        • Default Values
        • Primitive Types
          • byte
          • short
          • int
          • long
          • float
          • double
          • char
          • boolean
        • Non-Primitive (Reference) Types
          • String
            • StringBuilder
            • StringBuffer
              • Problems
            • Multiline String
            • Comparison - String, StringBuilder & StringBuffer
          • Array
          • Collections
            • List
              • Array vs List
              • ArrayList
              • Vector
                • Stack
                  • Problems
              • LinkedList
            • Queue
              • PriorityQueue
              • Deque (Double-Ended Queue)
                • ArrayDeque
                • ConcurrentLinkedDeque - TBU
                • LinkedBlockingDeque - TBU
            • Map
              • HashMap
              • Hashtable
              • LinkedHashMap
              • ConcurrentHashMap
              • TreeMap
              • EnumMap
              • WeakHashMap
            • Set
              • HashSet
              • LinkedHashSet
              • TreeSet
              • EnumSet
              • ConcurrentSkipListSet
              • CopyOnWriteArraySet
        • Specialized Classes
          • BigInteger
          • BigDecimal
            • Examples
          • BitSet
          • Date and Time
            • Examples
          • Optional
          • Math
          • UUID
          • Scanner
          • Formatter
            • Examples
          • Properties
          • Regex (Pattern and Matcher)
            • Examples
          • Atomic Classes
          • Random
          • Format
            • NumberFormat
            • DateFormat
            • DecimalFormat
        • Others
          • Object
          • Enum
            • Pre-Defined Enum
            • Custom Enum
            • EnumSet and EnumMap
          • Record
          • Optional
          • System
          • Runtime
          • ProcessBuilder
          • Class
          • Void
          • Throwable
            • Error
            • Exception
              • Custom Exception Handling
              • Best Practice
            • Error vs Exception
            • StackTraceElement
    • Java Features by Version
      • How New Java Features are Released ?
      • Java Versions
        • Java 8
        • Java 9
        • Scoped Values
        • Unnamed Variables & Patterns
      • FAQ
    • Concepts
      • Set 1
        • Streams
          • flatmap
          • Collectors Utility Class
          • Problems
        • Functional Interfaces
          • Standard Built-In Interfaces
          • Custom Interfaces
        • Annotation
          • Custom Annotation
          • Meta Annotation
        • Generics
          • Covariance and Invariance
        • Asynchronous Computation
          • Future
          • CompletableFuture
          • Future v/s CompletableFuture
          • ExecutorService
            • Thread Pool
            • Types of Work Queues
            • Rejection Policies
            • ExecutorService Implementations
            • ExecutorService Usage
          • Locks, Atomic Variables, CountDownLatch, CyclicBarrier - TBU
          • Parallel Streams, Fork/Join Framework,Stream API with Parallelism - TBU
      • Set 2
        • Standards
          • ISO Standards
          • JSR
            • JSR 303, 349, 380 (Bean Validation)
        • Operator Precedence
      • Set 3
        • Date Time Formatter
        • Validation
      • Set 4
        • Input from User
        • Comparison & Ordering
          • Object Equality Check
          • Comparable and Comparator
            • Comparator Interface
          • Sorting of Objects
          • Insertion Ordering
    • Packages
      • Core Packages
        • java.lang
          • java.lang.System
          • java.lang.Thread
      • Jakarta Packages
        • jakarta.validation
        • javax.validation
      • Third-party Packages
    • Code Troubleshoot
      • Thread Dump
      • Heap Dump
    • Code Quality & Analysis
      • ArchUnit
      • Terminologies
        • Cyclic dependencies
    • Code Style
      • Naming Convention
      • Package Structure
      • Formatting
      • Comments and Documentation
      • Imports
      • Exception Handling
      • Class Structure
      • Method Guidelines
      • Page 1
      • Code Smells to Avoid
      • Lambdas and Streams Style
      • Tools
    • Tools
      • IntelliJ IDEA
        • Shortcuts for MAC
      • Apache JMeter
        • Examples
      • Thread Dump Capture
        • jstack
        • VisualVM - TBU
        • jcmd - TBU
        • JConsole - TBU
        • YourKit Java Profiler - TBU
        • Eclipse MAT - TBU
        • IntelliJ IDEA Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Thread Dump Analyzers - TBU
      • Heap Dump Capture
        • jmap
        • VisualVM - TBU
        • jcmd - TBU
        • Eclipse MAT (Memory Analyzer Tool) - TBU
        • IntelliJ IDEA Profiler - TBU
        • YourKit Java Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Kill -3 Command - TBU
        • jhat (Java Heap Analysis Tool) - TBU
        • JVM Options - TBU
      • Wireshark
        • Search Filters
    • Best Practices
      • Artifact and BOM Versioning
  • Maven
    • Installation
    • Local Repository & Configuration
    • Command-line Options
    • Build & Lifecycle
    • Dependency Management
      • Dependency
        • Transitive Dependency
        • Optional Dependency
      • Dependency Scope
        • Maven Lifecycle and Dependency Scope
      • Dependency Exclusions & Overrides
      • Bill of Materials (BOM)
      • Dependency Conflict Resolution
      • Dependency Tree & Analysis
      • Dependency Versioning Strategies
    • Plugins
      • Build Lifecycle Management
      • Dependency Management
      • Code Quality and Analysis
      • Documentation Generation
      • Code Generation
      • Packaging and Deployment
      • Reporting
      • Integration and Testing
      • Customization and Enhancement
        • build-helper-maven-plugin
        • properties-maven-plugin
        • ant-run plugin
        • exec-maven-plugin
        • gmavenplus-plugin
      • Performance Optimization
    • FAQs
      • Fixing Maven SSL Issues: Unable to Find Valid Certification Path
  • Spring
    • Spring Basics
      • What is Spring?
      • Why Use Spring
      • Spring Ecosystem
      • Versioning
      • Setting Up a Spring Project
    • Core Concepts
      • Spring Core
        • Dependency Injection (DI)
        • Stereotype Annotation
      • Spring Beans
        • Bean Lifecycle
        • Bean Scope
          • Singleton Bean
        • Lazy & Eager Initialization
          • Use Case of Lazy Initialization
        • BeanFactory
        • ApplicationContext
      • Spring Annotations
        • Spring Boot Specific
        • Controller Layer (Web & REST Controllers)
    • Spring Features
      • Auto Configuration
        • Spring Boot 2: spring.factories
        • Spring Boot 3: spring.factories
      • Spring Caching
        • In-Memory Caching
      • Spring AOP
        • Before Advice
        • After Returning Advice
        • After Throwing Advice
        • After (finally) Advice
        • Around Advice
      • Spring File Handling
      • Reactive Programming
        • Reactive System
        • Reactive Stream Specification
        • Project Reactor
          • Mono & Flux
      • Asynchronous Computation
        • @Async annotation
      • Spring Security
        • Authentication
          • Core Components
            • Security Filter Chain
              • HttpSecurity
              • Example
            • AuthenticationManager
            • AuthenticationProvider
            • UserDetailsService
              • UserDetails
              • PasswordEncoder
            • SecurityContext
            • SecurityContextHolder
            • GrantedAuthority
            • Security Configuration (Spring Security DSL)
          • Authentication Models
            • One-Way Authentication
            • Mutual Authentication
          • Authentication Mechanism
            • Basic Authentication
            • Form-Based Authentication
            • Token-Based Authentication (JWT)
            • OAuth2 Authentication
            • Multi-Factor Authentication (MFA)
            • SAML Authentication
            • X.509 Certificate Authentication
            • API Key Authentication
            • Remember-Me Authentication
            • Custom Authentication
          • Logout Handling
        • Authorization
        • Security Filters and Interceptors
        • CSRF
          • Real-World CSRF Attacks & Prevention
        • CORS
        • Session Management and Security
        • Best Practices
      • Spring Persistence
        • JDBC
          • JDBC Components
          • JDBC Template
          • Transaction Management
          • Best Practices in JDBC Usage
          • Datasource
            • Connection Pooling
              • HikariCP
            • Caching
        • JPA (Java Persistence API)
          • JPA Fundamentals
          • ORM Mapping Annotations
            • 1. Entity and Table Mappings
            • 2. Field/Column Mappings
            • 3. Relationship Mappings
            • 4. Inheritance Mappings
            • 5. Additional Configuration Annotations
          • Querying Data
            • JPQL
            • Criteria API
            • JPA Specification
              • Example - Employee Portal
            • Native SQL Queries
            • Named Queries
            • Query Return Types
            • Pagination & Sorting
              • Example - Employee Portal
            • Projection
          • Fetch Strategies in JPA
        • JPA Implementation
          • Hibernate
            • Properties
            • Example
        • Spring Data JPA
          • Repository Abstractions
          • Entity-to-Table Mapping
          • Derived Query Methods
        • Cross-Cutting Concerns
          • Transactions
          • Caching
          • Concurrency
        • Examples
          • Employee Portal
            • API
    • Distributed Systems & Communication
      • Distributed Scheduling
      • Inter-Service Communication
        • 1. RestTemplate
        • 2. WebClient
        • 3. OpenFeign
        • Retry Mechanism
          • @Retryable annotation
            • Example
    • Security & Data Protection
      • Encoding | Decoding
        • Types
          • Base Encoding
            • Base16 - TBD
              • Encoding and Decoding in Java - TBD
            • Base32
              • Encoding and Decoding in Java
            • Base64 -TBD
              • Encoding and Decoding in Java - TBD
          • Text Encoding - TBD
            • Extended ASCII
              • Encoding and Decoding in Java - TBD
                • ISO-8859-1
                • Windows-1252 - TBD
                • IBM Code Pages - TBD
            • ASCII
              • Encoding and Decoding in Java
        • Java Guidelines
          • Text Encoding Decoding Examples
          • Base Encoding Decoding Examples
          • Best Practices and Concepts
          • Libraries
      • Cryptography
        • Terminology
        • Java Cryptography Architecture (JCA)
        • Key Management
          • Key Generation
            • Tools and Libraries
              • OpenSSL
              • Java Keytool
                • Concept
                • Use Cases
            • Key & Certificate File Formats
          • Key Distribution
          • Key Storage
          • Key Rotation
          • Key Revocation
        • Encryption & Decryption
          • Symmetric Encryption
            • Algorithm
            • Modes of Operation
            • Examples
          • Asymmetric Encryption
            • Algorithm
            • Mode of Operation
            • Examples
    • Utilities & Libraries
      • Apache Libraries
        • Apache Camel
          • Camel Architecture
            • Camel Context
            • Camel Endpoints
            • Camel Components
            • Camel Exchange & MEP
          • Spring Dependency
          • Different Components
            • Camel SFTP
        • Apache Commons Lang
      • MapStruct Mapper
      • Utilities by Spring framework
        • FileCopyUtils
    • General Concepts
      • Spring Boot Artifact Packaging
      • Classpath and Resource Loading
      • Configuration - Mapping Properties to Java Class
      • Validations in Spring Framework
        • Jakarta Validation
          • Jakarta Bean Validation Annotations
    • Practical Guidelines
      • Spring Configuration
      • Spring Code Design
  • Software Testing
    • Software Testing Methodologies
      • Functional Testing
      • Non Functional Testing
    • Software Testing Life Cycle (STLC)
    • Integration Test
      • Dynamic Property Registration
    • Java Test Framework
      • JUnit
        • JUnit 4
          • Examples
        • JUnit 5
          • Examples
        • JUnit 4 vs JUnit 5
  • System Design
    • Foundations
      • Programming Paradigms
      • Object-Oriented Design
        • SOLID Principles
        • GRASP Principles
        • Composition
        • Aggregation
        • Association
      • Design Pattern
        • Creational Pattern
        • Structural Pattern
        • Behavioral Pattern
        • Examples
          • Data Collector
          • Payment Processor
        • Design Enhancements
          • Fluent API Design
            • Examples
    • Architectural Building Blocks
      • CAP Theorem
      • Load Balancer
        • Load Balancer Architecture
        • Load Balancing in Java Microservices
          • Client-Side Load Balancing Example
          • Server-Side Load Balancing Example
        • Load Balancer Monitoring Tool
      • Scaling
        • Vertical Scaling (Scaling Up)
        • Horizontal Scaling (Scaling Out)
        • Auto-Scaling
        • Database Scaling via Sharding
      • Caching
        • Pod-Level vs Distributed Caching
      • Networking Metrics
        • Types of Delay
        • Scenario
      • System Characteristics
      • Workload Types
      • Resilience & Failure Handling
    • Performance
      • Why Is My API Sometimes Slow ?
    • Security
      • Security by Design
      • Zero Trust Security Model
      • Zero Trust Architecture
      • Principles
        • CIA
        • Least Privilege Principle
        • Defense in Depth
      • Security Threats & Mitigations
        • OWASP
          • Top 10 Security Threats
          • Application Security Verification Standard
          • Software Assurance Maturity Model
          • Dependency Check
          • CSRFGuard
          • Cheat Sheets
          • Security Testing Guide
          • Threat Dragon
        • Threat Modeling
      • Compliance & Regulation
        • PCI DSS
    • Deployment Patterns
    • Diagrams
      • UML Diagrams
        • PlantUML
          • Class Diagram
          • Object Diagram
          • Sequence Diagram
          • Use Case Diagram
          • Activity Diagram
          • State Diagram
          • Architecture Diagram
          • Component Diagram
          • Timing Diagram
          • ER Diagram (Entity-Relationship)
          • Network Diagram
    • Common Terminologies
    • Problems
      • Reference Materials
      • Cache Design
  • Interview Guide
    • Non-Technical
      • Behavioural or Introductory Guide
      • Project Specific
    • Technical
      • Java Interview Companion
        • Java Key Concepts
          • Set 1
          • Set 2
        • Java Code Snippets
        • Java Practice Programs
          • Set 3 - Strings
          • Set 4 - Search
          • Set 5 - Streams and Collection
      • SQL Interview Companion
        • SQL Practice Problems
          • Set 1
      • Spring Interview Companion
        • Spring Key Concepts
          • Set 1 - General
          • Set 2 - Core Spring
        • Spring Code Snippets
          • JPA
      • Application Server
      • Maven
      • Containerized Application
      • Microservices
    • General
      • Applicant Tracking System (ATS)
      • Flowchart - How to Solve Coding Problem?
Powered by GitBook
On this page
  • About
  • Version
  • Help Section
  • Openssl options available
  • Openssl Message Digest options available
  • Openssl Cipher options available
  • Openssl genpkey options available
  • Openssl ecparam options available
  • Openssl pkey options available
  • Openssl pkeyutl options available
  • Openssl req options
  • Symmetric Key
  • Generating a Symmetric Key
  • Encrypting Data
  • Decrypting Data
  • Asymmetric Key
  • Generating a Private Key
  • Generating a Public Key
  • Encrypting Data
  • Decrypting Data
  • Creating a Certificate Signing Request (CSR)
  • Self-Signing a Certificate
  • Signing Data
  • Verifying a Signature

Was this helpful?

  1. Spring
  2. Security & Data Protection
  3. Cryptography
  4. Key Management
  5. Key Generation
  6. Tools and Libraries

OpenSSL

PreviousTools and LibrariesNextJava Keytool

Last updated 8 months ago

Was this helpful?

About

OpenSSL is a widely-used toolkit for implementing SSL/TLS and other cryptographic protocols. It includes various commands to generate symmetric keys, encrypt and decrypt data, and manage cryptographic keys.

Version

Help Section

Openssl options available

Openssl Message Digest options available

Openssl Cipher options available

Openssl genpkey options available

Openssl ecparam options available

Openssl pkey options available

Openssl pkeyutl options available

Openssl req options

Symmetric Key

Symmetric key generation involves creating a secret key that will be used for both encryption and decryption processes in symmetric cryptography. The strength and security of the encryption depend on the quality of the generated key.

Generating a Symmetric Key

To generate a symmetric key using OpenSSL:

openssl rand <key_length> > <output_file>
  • <key_length>: Specify the desired key length in bytes (e.g., 16 for 128-bit key).

  • <output_file>: Name of the file to store the generated key (written in raw binary format).

openssl rand -base64 <key_length> > <output_file>
  • -base64 : encodes the key in Base64 format for readability

openssl rand -hex <key_length> > <output_file>
  • -hex : outputs the key in hexadecimal format, which might be required by some tools.

// Examples

// Generate a 256-bit (32 bytes) random key and saves it to symmetric.key
openssl rand -out symmetric.key 32

Encrypting Data

To encrypt data using a symmetric key

openssl enc <encryption algorithm> -salt -in <input_file> -out <output_file> -k <symmetric_key>
  • <encryption algorithm>: Specifies the encryption algorithm (AES-128 in CBC mode for example). We can use other algorithms and modes like des-cbc or aes-256-cfb. Choose based on the security requirements.

  • -salt: (Optional) Adds a salt to the encryption.

  • -in <input_file>: Path to the file containing the plain text data you want to encrypt.

  • -out <output_file>: Path to the file where the encrypted data (ciphertext) will be written.

  • -k <symmetric_key>: This is where we provide the symmetric key used for encryption. There are two ways to specify the key:

    • Raw Key: If key is a raw binary string (generated with openssl rand without -base64), use this option directly followed by the key in hexadecimal format. (e.g., -k F40F9211C8AF2009...).

    • Base64 Encoded Key: If key is Base64 encoded (more common for readability), use -k followed by the -base64 option and then the Base64 encoded key string. (e.g., -k -base64 your_base64_encoded_key).

  • Password-Based Encryption: We can use the -pass option to provide a password at runtime. OpenSSL will derive a key from the password using PBKDF2 for added security. (e.g., openssl enc -aes-128-cbc -in data.txt -out data.txt.enc -pass pass:your_password).

Key Management with Passwords:

  • There's no separate key file to manage in password-based encryption.

  • The password acts as the "key" to the derived key.

  • It's crucial to choose a strong password and keep it confidential for successful decryption.

Key Derivation with Password:

  1. When we provide a password during encryption with -pass pass:your_password, OpenSSL doesn't store the password itself.

  2. Instead, it uses a Key Derivation Function (KDF) to derive a secret key from your password. This KDF process involves one-way hashing and salting (adding random data) to make it computationally infeasible to recover the password from the derived key.

  3. This derived key is then used for encryption or decryption.

// Examples

// Encrypting a file with a Base64 encoded key
// Assuming we have a file named data.txt to encrypt and a Base64 encoded key stored in secret_key.txt.
openssl enc -aes-128-cbc -in data.txt -out data.txt.enc -k -base64 $(cat secret_key.txt)

// To encrypt a data using AES algorithm with a 256-bit key in CBC mode
openssl enc -aes-256-cbc -salt -in plaintext.txt -out encrypted.txt -pass pass:your_password

Decrypting Data

To decrypt data using a symmetric key

openssl enc -d <encryption algorithm> -in <encrypted_file> -out <decrypted_file> -k <symmetric_key>
  • -d: Decryption mode flag (essential for decryption).

  • <encryption algorithm>: Specifies the decryption algorithm and mode used during encryption (should match the encryption process).

  • -in <encrypted_file>: Path to the file containing the encrypted data (ciphertext).

  • -out <decrypted_file>: Path to the file where the decrypted plain text data will be written.

  • -k <symmetric_key>: This is where you provide the symmetric key used for decryption. Similar to encryption, there are two ways to specify the key:

    • Raw Key: If the key is a raw binary string, use -k followed by the key in hexadecimal format.

    • Base64 Encoded Key: If the key is Base64 encoded (more common), use -k followed by the -base64 option and then the Base64 encoded key string

Matching Parameters: Ensure the decryption command uses the same algorithm and mode (-aes-256-cbc for example) as used during encryption for successful decryption.

Correct Key: Use the exact key (raw, Base64 encoded, or password) that was used for encryption.

Decryption Failure: Incorrect password, key, or algorithm can lead to decryption failure.

// Examples

// Decrypting with Raw Key
// Assuming we have an encrypted file data.txt.enc and the raw binary key stored in secret_key.bin
// xxd -p secret_key.bin reads the raw binary key from secret_key.bin and outputs it in a format suitable for OpenSSL
openssl enc -d -aes-256-cbc -in data.txt.enc -out data.txt -k $(xxd -p secret_key.bin)

// Decrypting with Base64 Encoded Key
// Assuming we have the encrypted file data.txt.enc and the Base64 encoded key stored in secret_key.txt
openssl enc -d -aes-256-cbc -in data.txt.enc -out data.txt -k -base64 $(cat secret_key.txt)

// Password-Based Decryption
// Replace your_password with the exact password you used during encryption
openssl enc -d -aes-256-cbc -in data.txt.enc -out data.txt -pass pass:your_password

Asymmetric Key

Asymmetric key cryptography, also known as public-key cryptography, utilizes a pair of mathematically linked keys: a public key and a private key.

Key Pair:

  • Public Key: This key is freely distributed and can be shared with anyone. It's used for encryption. Anyone with the public key can encrypt data, but only the holder of the corresponding private key can decrypt it.

  • Private Key: This key is kept secret and never shared. It's used for decryption. Only the entity possessing the private key can decrypt data encrypted with the corresponding public key.

The public key cannot be reversed and used for decryption like a private key. This is a fundamental design principle that ensures the security of the system.

Generating a Private Key

openssl genpkey -algorithm <alogorithm type> -out private_key.pem [options]
  • algorithm: Type of algorithm to use. For example RSA, DSA, EC etc.

// Examples

// RSA algorithm is widely used for key generation
// -pkeyopt rsa_keygen_bits:2048: Specifies the key size (2048 bits)
openssl genpkey -algorithm RSA -out private_key.pem -pkeyopt rsa_keygen_bits:2048

// The Digital Signature Algorithm
// -pkeyopt dsa_paramgen_bits:2048: Specifies the key size (2048 bits)
openssl genpkey -algorithm DSA -out private_key.pem -pkeyopt dsa_paramgen_bits:2048

// Elliptic Curve (EC) cryptography
// -name prime256v1: Specifies the curve name
openssl ecparam -name prime256v1 -genkey -noout -out private_key.pem

Generating a Public Key

OpenSSL can create the corresponding public key from the private key

openssl pkey -in <private_key_file> -pubout -out <public_key_file>
  • <private_key_file>: Path to the existing private key file (generated in step 1).

  • <public_key_file>: Path to the file where the public key will be stored (in PEM format).

// Examples

// Generate a public key from a private key
openssl pkey -in private_key.pem -pubout -out public_key.pem

// Command is specifically designed for RSA key operations
openssl rsa -in my_private_key.pem -pubout -out my_public_key.pem

Encrypting Data

In asymmetric encryption, we use the public key of the recipient to encrypt data and the corresponding private key of the recipient to decrypt it.

openssl pkeyutl -encrypt -in <input_file> -out <output_file> -pubin -inkey recipient_public_key.pem
  • -encrypt: Encrypt the input data.

  • -pubin: Indicates the input key is a public key.

  • -inkey public_key.pem: Path to the recipient's public key used for encryption (PEM format).

  • -in plaintext.txt: Input file to encrypt.

  • -out encrypted.bin: Output the encrypted data to encrypted.bin

// Examples

// Encrypting data using recipient's public key (RSA)
openssl pkeyutl -encrypt -in message.txt -out message.enc -pubin -inkey recipient_public_key.pem

// Encrypting data using recipient's public key (DSA)
openssl pkeyutl -encrypt -in message.txt -out message.enc -pubin -inkey recipient_public_key.pem

// Encrypting data using recipient's public key (ECC)
openssl pkeyutl -encrypt -in message.txt -out message.enc -pubin -inkey recipient_public_key.pe

Decrypting Data

While asymmetric encryption uses public keys, decryption relies on the corresponding private key.

openssl pkeyutl -decrypt -in message.enc -out message.txt -inkey your_private_key.pem
  • -decrypt: Decrypt the input data.

  • -pubin: Indicates the input key is a public key.

  • -inkey your_private_key.pem: Path to the recipient's private key used for decryption (PEM format).

  • -in encryptedtext.enc: Input file with encrypted data.

  • -out plaintext.txt: Output the decrypted data to plaintext.txt

// Examples

// Decrypting data using your private key (RSA)
openssl pkeyutl -decrypt -in message.enc -out message.txt -inkey your_private_key.pem

// Decrypting data using your private key (DSA)
openssl pkeyutl -decrypt -in message.enc -out message.txt -inkey your_private_key.pem

// Decrypting data using your private key (ECC)
openssl pkeyutl -decrypt -in message.enc -out message.txt -inkey your_private_key.pem

Creating a Certificate Signing Request (CSR)

A Certificate Signing Request (CSR) is a data structure containing information used to obtain a digital certificate from a Certificate Authority (CA)

openssl req -new -key private_key.pem -out csr.pem [options]
  • -new: Indicates a new CSR creation.

  • -key my_private_key.pem: Specifies the path to your private key file.

  • -out my_csr.csr: Specifies the output file for the CSR.

  • [-subj "/C=US/ST=California/L=San Francisco/O=My Company/CN=www.example.com"]: This is an optional subject field. It defines information about the entity requesting the certificate. You can replace the values with your own details:

    • /C=US: Country (2-letter code)

    • /ST=California: State/Province

    • /L=San Francisco: Locality (City)

    • /O=My Company: Organization Name

    • /CN=www.example.com: Common Name (Domain name or server identifier)

Once we have the CSR file (e.g., my_csr.csr), we can submit it to a Certificate Authority (CA) of our choice to obtain the digital certificate. The CA will validate the information and issue a certificate signed by their trusted root certificate.

// Examples

// Generate a CSR with default settings
openssl req -new -key private_key.pem -out csr.pem

// Generating the CSR with Subject Information
openssl req -new -key my_private_key.pem -out my_csr.csr \
  -subj "/C=US/ST=California/L=San Francisco/O=My Company/CN=www.example.com"

Self-Signing a Certificate

While obtaining a certificate from a trusted Certificate Authority (CA) is generally recommended, OpenSSL allows us to create a self-signed certificate for testing or internal purposes.

openssl req -x509 -sha256 -days 365 -newkey rsa:2048 -keyout my_server_key.pem \
  -out my_server_cert.crt [-subj "/C=US/ST=California/L=San Francisco/O=My Company/CN=www.example.com"]
  • -x509: This flag indicates creating a self-signed certificate.

  • -sha256: Specifies the signature hashing algorithm (SHA-256 is recommended).

  • -days 365: Sets the validity period of the certificate to 365 days .

  • -newkey rsa:2048: Generates a new RSA key (2048 bits) and stores it in my_server_key.pem.

  • -keyout my_server_key.pem: Specifies the output file for the private key (same as before).

  • -out my_server_cert.crt: Specifies the output file for the self-signed certificate.

  • [-subj "/C=US/ST=California/L=San Francisco/O=My Company/CN=www.example.com"]: This optional subject information is similar to CSR creation.

Trusting the Self-Signed Certificate:

Since it's self-signed, most browsers and applications will show a security warning when using this certificate.

Here are two approaches, depending on our needs:

For testing on a local machine: We can import the self-signed certificate into our browser's trust store. However, this is not recommended for production environments due to security risks.

For internal use on a closed network: We can configure our applications and servers to trust the self-signed certificate's fingerprint or subject information. However, exercise caution as this bypasses the validation provided by trusted CAs.

// Examples

// Create a self signed certificate
openssl req -x509 -key private_key.pem -in csr.pem -out certificate.pem -days 365

// Create a self signed certificate with subject
openssl req -x509 -sha256 -days 365 -key my_server_key.pem \
  -out my_server_cert.crt [-subj "/C=US/ST=California/L=San Francisco/O=My Company/CN=www.example.com"]
  
// Create a private key along with self signed certificate
openssl req -x509 -sha256 -days 365 -newkey rsa:2048 -keyout my_server_key.pem \
  -out my_server_cert.crt -subj "/C=US/ST=California/L=San Francisco/O=My Company/CN=www.example.com"
  

Signing Data

Digital signatures are a crucial aspect of secure communication, allowing verification of data integrity and origin. OpenSSL provides functionalities for signing data using your private key.

openssl dgst -sha256 -sign my_private_key.pem -out signature.txt data.txt
  • -sha256: Specifies the hashing algorithm used to create a digest of the data (SHA-256 is recommended).

  • -sign my_private_key.pem: Indicates signing with our private key stored in my_private_key.pem.

  • -out signature.txt: Specifies the output file for the signature .

  • data.txt: The path to the file containing the data we want to sign.

Anyone with access to our public key (derived from our private key) can verify the signature to confirm the data's authenticity and integrity.

// Examples

// Sign data using a private key with SHA-256 hash algorithm.
openssl dgst -sha256 -sign private_key.pem -out signature.bin plaintext.txt

Verifying a Signature

Verify a signature using a public key

openssl dgst -sha256 -verify signer_public_key.pem -signature signature.txt data.txt
  • -sha256: Specifies the hashing algorithm used during signing (ensure it matches the signing process).

  • -verify signer_public_key.pem: Indicates verification using the public key of the signer. This file (e.g., signer_public_key.pem) should be obtained from a trusted source.

  • -signature signature.txt: Specifies the path to the signature file created during signing.

  • data.txt: The path to the original data file (or the data itself if not in a file).

Output:

  • If the verification is successful, OpenSSL will print "Verified OK". This indicates the data has not been tampered with and the signature is valid.

  • If the verification fails, it will display an error message. This might suggest the data has been modified, the signature is invalid, or the wrong public key was used.

  1. Signing Process: During signing, a cryptographic hash function is used to create a "digest" of the data. This digest is a unique fingerprint of the data's content. The signer then uses their private key to encrypt this digest, creating a digital signature.

  2. Verification Process: During verification, the same hashing algorithm is used to create a new digest of the received data. Then, the verifier uses the signer's public key (which can be mathematically derived from their private key) to decrypt the attached signature.

  3. Verification Outcome: If the decrypted signature (digest) matches the newly created digest of the received data,verification is successful. This indicates that:

    • The data has not been altered since it was signed, as any changes would result in a different digest.

    • The signature is authentic, as only the private key corresponding to the public key used for verification could have created the valid signature.

https://github.com/openssl/openssl/blob/master/INSTALL.md