decrypt101
SocialOpen ProjectsSupport me My Resumes
  • Preface
    • Motivation
    • Roadmap’s
  • Introduction to Blockchain
    • A Brief History
    • Growth of Blockchain
    • Structure of Blockchain
    • Types of Blockchain
    • Key Technologies of Blockchain
    • Features of Blockchain
    • How Blockchain Works ?
    • Implementation of Blockchain
    • Summary
  • Components of Blockchain Architecture
    • Distributed Ledger
    • Blocks
    • Transaction
    • Chain
    • Peer-to-Peer Network
    • Blockchain Layers
    • Off-Chain & On-Chain
    • Wallet
    • Mining
    • Tokens
    • Assets
    • State Channels
    • Sidechains
    • Oracles on Blockchain
    • Atomic Swaps
    • Decentralized Identity (DID)
    • Blockchain Data Storage
    • Interoperability
    • Data structures for Scaling Blockchain
    • Maximal Extractable Value (MEV)
  • Consensus Mechanisms
    • Proof of Work (PoW)
      • Implemation Using Rust
    • Proof of Stake (PoS)
    • Proof of Burn (PoB)
    • Proof of Capacity (PoC)
    • Proof of Activity (PoAc)
    • Proof of Weight (PoWe)
    • Proof of Luck (PoL)
    • Proof of Ownership (PoO)
    • Proof of Existence (PoE)
    • Proof of Believability (PoBe)
    • Proof of History (PoH)
    • Proof of Authority (PoA)
    • Proof of Elapsed Time (PoET)
  • Cryptographics
    • Encryption & Decryption
      • Symmetric Encryption
      • Asymmetric Encryption
      • Key Management and Exchange
      • Implementation
    • Cryptographic Hashing
      • Secure Hash Algorithms (SHA)
      • Message Digest Algorithms
      • Ethash
      • Blake2
      • SCrypt
      • RIPEMD-160
    • Digital Signature
      • Digital Signature Algorithms
      • Digital Signature in Blockchain
    • Zero-Knowledge Proofs (ZKPs)
      • Types of Zero-Knowledge Proof and Protocols
      • A Case Study of Polygon Platform
    • Multi-Party Computation (MPC)
    • Cryptanalysis
    • Practical Implementation
  • Decentralized Application (DApp)
    • Design and UX in Web3
  • Smart Contract
    • Development Tools
    • Solidity
    • Testing Smart Contract
    • Developing Smart Contract
    • Interacting & Deploying with Smart Contract
    • Verifying Smart Contracts
    • Upgrading Smart Contracts
    • Securing Smart Contract
    • Smart Contract Composability
    • Testnet and Mainnet
    • Blockchain Platform Using Smart Contract
    • Application of Smart Contract
    • Practical Implementation
  • Blockchain Platforms
    • Ethereum
      • Ethereum Virtual Machine (EVM)
      • ETHER and GAS
      • Ethereum transaction
      • Ethereum Accounts
      • Ethereum Stacking
      • Ethereum Network
      • Ethereum Scaling Solutions
      • Ethereum Use-Cases
      • Getting Started with Ethereum
      • Ethereum Ecosystem and Support
    • Solana
      • Solana Architecture
        • Solana Account Model
        • Solana Wallet
        • Transactions and Instructions
        • Solana Programs
        • Program Derived Address (PDA)
        • Cross Program Invocation (CPI)
        • Tokens on Solana
        • Clusters and Public RPC Endpoints
        • Transaction Confirmation & Expiration
        • Retrying Transactions
        • Versioned Transactions
        • Address Lookup Tables
        • State Compression
        • Actions and Blinks
      • Solana Developments
      • Solana Client
      • Advanced Solana
      • Solana Scaling and Performance Architecture
      • Solana Solutions and cases
      • Practical Implemenation
    • Binance Smart Chain (BSC)
      • Create a BEP20 Token
    • Hyperledger Fabric
    • Cosmos
    • Polkadot
    • Quorum
    • Polygon
    • Algorand
    • Corda
    • Avalanche
    • TRON
    • Summary
  • Decentralized Finance (DeFi)
    • DeFi Components
    • DeFi Protocols
    • DeFi Platforms
    • DeFi Risk Classification
      • Infrastructure-layer Attacks
      • Smart Contract Layer-attacks
      • Application Layer-attacks
      • DeFi Risks
    • DeFi and Blockchain
    • DeFi Impact
  • Decentralized Ecosystem and Digital Innovation
    • Layer 2 Scaling Fundamental
    • Tokenomics
    • Cryptocurrency
    • Quantative Trading
    • NFTs
    • GameFi
    • Metaverse
  • Blockchain as a Service (BaaS)
    • Building Fullstack Blockchain Platform
    • Decentralized Digital Identity
    • Build a Cryptocurrencies Exchange
    • Play-to-Earn Gaming
    • Solana Token Airdrop Manager
    • Smart Contract Development on Solana with Rust
    • Quantitative Trading Platform
    • Insurances protocols
    • Flash Loans
    • Asset Management
    • Tokenized Derivatives
    • Automated Market Makers (AMMs)
    • Staking
    • Lending and Borrowing Platforms
    • Yield Farming
    • Stablecoin System
    • Security Token Offerings (STOs)
    • Initial Coin Offerings (ICOs)
    • On-Chain Voting Systems
    • Decentralized Autonomous Organizations (DAOs)
    • NFT Marketplaces
    • Provenance Verification
    • Supply Chain Tracking
    • Commodities Tokenization
    • Real Estate Tokenization
    • Digital Certificates
    • KYC (Know Your Customer)
  • Blockchain Development Across Languages
    • Blockchain using Go(Golang)
    • Blockchain using Rust
    • Blockchain using Python
    • Blockchain using Cairo
  • Distributed Systems & Infrastructure Technology
    • Classification of Distributed Systems
    • Networked systems versus Distributed systems
    • Parallel systems vs Distributed systems
    • Distributed versus Decentralized systems
    • Processes of Distributed Systems
    • Architecture of Distributed systems
    • Infrastructure Technologies
  • Distributed System Patterns
    • Distributed Agreements Algorithms
      • HoneyBadgerBFT
    • Data Replications
    • Data Partition
    • Consistency
    • Distributed Time
    • Cluster Management
    • Communication between Nodes
    • Fault Tolerance and Resilience
      • How to design better fault tolerance systems
      • Resilience Patterns
    • Coordination systems
      • Clock synchronization
    • Security
      • Trust in distributed systems
      • Design of Principal Security
      • Security threats, policies, and mechanisms
      • Authentication and Authorizations
      • Cryptography
      • Monitoring in Security
  • Distributed System Design
    • Page 1
    • Distributed Shared Memory
    • Distributed Data Management
    • Distributed Knowledge Management
    • Distributed Ledger
  • FAQs
  • Support and Community
Powered by GitBook
On this page
  1. Cryptographics
  2. Encryption & Decryption

Implementation

PreviousKey Management and ExchangeNextCryptographic Hashing

Last updated 8 months ago

Encryption & Decryption Using Golang

Prerequisites

Ensure you have Go installed on your system. You can download it from the official

package main

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"io"
)

// Function to encrypt plaintext using AES-GCM
func encrypt(plaintext, key string) (string, error) {
	// Convert the key to bytes
	keyBytes, err := hex.DecodeString(key)
	if err != nil {
		return "", fmt.Errorf("failed to decode key: %v", err)
	}

	// Create a new AES cipher using the key
	block, err := aes.NewCipher(keyBytes)
	if err != nil {
		return "", fmt.Errorf("failed to create cipher: %v", err)
	}

	// Create a new GCM (Galois/Counter Mode)
	gcm, err := cipher.NewGCM(block)
	if err != nil {
		return "", fmt.Errorf("failed to create GCM: %v", err)
	}

	// Create a random nonce of the appropriate length
	nonce := make([]byte, gcm.NonceSize())
	if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
		return "", fmt.Errorf("failed to generate nonce: %v", err)
	}

	// Encrypt the plaintext using the nonce and GCM
	ciphertext := gcm.Seal(nonce, nonce, []byte(plaintext), nil)
	return hex.EncodeToString(ciphertext), nil
}

// Function to decrypt ciphertext using AES-GCM
func decrypt(ciphertext, key string) (string, error) {
	// Convert the key and ciphertext to bytes
	keyBytes, err := hex.DecodeString(key)
	if err != nil {
		return "", fmt.Errorf("failed to decode key: %v", err)
	}

	ciphertextBytes, err := hex.DecodeString(ciphertext)
	if err != nil {
		return "", fmt.Errorf("failed to decode ciphertext: %v", err)
	}

	// Create a new AES cipher using the key
	block, err := aes.NewCipher(keyBytes)
	if err != nil {
		return "", fmt.Errorf("failed to create cipher: %v", err)
	}

	// Create a new GCM (Galois/Counter Mode)
	gcm, err := cipher.NewGCM(block)
	if err != nil {
		return "", fmt.Errorf("failed to create GCM: %v", err)
	}

	// Split the nonce and actual ciphertext
	nonceSize := gcm.NonceSize()
	nonce, ciphertextBytes := ciphertextBytes[:nonceSize], ciphertextBytes[nonceSize:]

	// Decrypt the ciphertext using the nonce and GCM
	plaintext, err := gcm.Open(nil, nonce, ciphertextBytes, nil)
	if err != nil {
		return "", fmt.Errorf("failed to decrypt: %v", err)
	}

	return string(plaintext), nil
}

func main() {
	// Example key (32 bytes for AES-256, 16 bytes for AES-128)
	key := "6368616e676520746869732070617373" // Example: "change this pass"

	// Plaintext to encrypt
	plaintext := "Hello, Golang Encryption!"

	// Encrypt the plaintext
	encrypted, err := encrypt(plaintext, key)
	if err != nil {
		fmt.Printf("Encryption failed: %v\n", err)
		return
	}
	fmt.Printf("Encrypted Text: %s\n", encrypted)

	// Decrypt the ciphertext
	decrypted, err := decrypt(encrypted, key)
	if err != nil {
		fmt.Printf("Decryption failed: %v\n", err)
		return
	}
	fmt.Printf("Decrypted Text: %s\n", decrypted)
}

OUTPUT :

Encrypted Text: 11ff3af66539bd5dea8decfbfe7dc0202eb5a82dbaf9f615e86e829ef3a4e293648a5dd72313e5f25f4c43837094c8be6ca99e3a21
Decrypted Text: Hello, Golang Encryption!
Go website.