백엔드 개발 Golang 실제 암호화폐의 마법: Go&#s 암호화 패키지를 작동하게 하기, Go Crypto 13

실제 암호화폐의 마법: Go&#s 암호화 패키지를 작동하게 하기, Go Crypto 13

Dec 31, 2024 am 11:06 AM

Real-World Crypto Magic: Putting Go

안녕하세요, 암호화폐 마법사님! Go의 암호화폐 패키지로 실제 세계의 마법을 볼 준비가 되셨나요? 우리는 이 멋진 암호 주문을 모두 배웠습니다. 이제 이를 실용적인 마법에 사용해 보겠습니다! 안전한 파일 암호화 주문과 공개 키 인프라(PKI) 소환 의식이라는 두 가지 강력한 아티팩트를 만들겠습니다.

마법 #1: 안전한 파일 암호화 주문

강력한 AES-GCM(갈루아/카운터 모드) 마법을 사용해 파일을 안전하게 암호화하고 복호화할 수 있는 마법의 두루마리를 만들어 보겠습니다. 이 주문은 비밀 유지와 무결성 보호를 모두 제공합니다!

package main

import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/rand"
    "errors"
    "fmt"
    "io"
    "os"
)

// Our encryption spell
func encrypt(plaintext []byte, key []byte) ([]byte, error) {
    block, err := aes.NewCipher(key)
    if err != nil {
        return nil, err
    }

    gcm, err := cipher.NewGCM(block)
    if err != nil {
        return nil, err
    }

    nonce := make([]byte, gcm.NonceSize())
    if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
        return nil, err
    }

    return gcm.Seal(nonce, nonce, plaintext, nil), nil
}

// Our decryption counter-spell
func decrypt(ciphertext []byte, key []byte) ([]byte, error) {
    block, err := aes.NewCipher(key)
    if err != nil {
        return nil, err
    }

    gcm, err := cipher.NewGCM(block)
    if err != nil {
        return nil, err
    }

    if len(ciphertext) < gcm.NonceSize() {
        return nil, errors.New("ciphertext too short")
    }

    nonce, ciphertext := ciphertext[:gcm.NonceSize()], ciphertext[gcm.NonceSize():]
    return gcm.Open(nil, nonce, ciphertext, nil)
}

// Enchant a file with our encryption spell
func encryptFile(inputFile, outputFile string, key []byte) error {
    plaintext, err := os.ReadFile(inputFile)
    if err != nil {
        return err
    }

    ciphertext, err := encrypt(plaintext, key)
    if err != nil {
        return err
    }

    return os.WriteFile(outputFile, ciphertext, 0644)
}

// Remove the encryption enchantment from a file
func decryptFile(inputFile, outputFile string, key []byte) error {
    ciphertext, err := os.ReadFile(inputFile)
    if err != nil {
        return err
    }

    plaintext, err := decrypt(ciphertext, key)
    if err != nil {
        return err
    }

    return os.WriteFile(outputFile, plaintext, 0644)
}

func main() {
    // Summon a magical key
    key := make([]byte, 32) // AES-256
    if _, err := rand.Read(key); err != nil {
        panic("Our magical key summoning failed!")
    }

    // Cast our encryption spell
    err := encryptFile("secret_scroll.txt", "encrypted_scroll.bin", key)
    if err != nil {
        panic("Our encryption spell fizzled!")
    }
    fmt.Println("Scroll successfully enchanted with secrecy!")

    // Remove the encryption enchantment
    err = decryptFile("encrypted_scroll.bin", "decrypted_scroll.txt", key)
    if err != nil {
        panic("Our decryption counter-spell backfired!")
    }
    fmt.Println("Scroll successfully disenchanted!")
}
로그인 후 복사

이 마법의 두루마리는 AES-GCM을 사용한 안전한 파일 암호화를 보여줍니다. 여기에는 마법 사고로부터의 보호(오류 처리), nonce에 대한 안전한 난수 소환, 적절한 마법 키 관리 방법이 포함됩니다.

마법 #2: PKI 소환 의식

이제 기본 공개 키 인프라(PKI) 시스템을 호출하는 더 복잡한 작업을 수행해 보겠습니다. 이 시스템은 마법의 인증서를 생성하고, CA(인증 기관)에 서명하고, 이러한 신비한 문서를 확인할 수 있습니다.

package main

import (
    "crypto/ecdsa"
    "crypto/elliptic"
    "crypto/rand"
    "crypto/x509"
    "crypto/x509/pkix"
    "encoding/pem"
    "fmt"
    "math/big"
    "os"
    "time"
)

// Summon a magical key pair
func generateKey() (*ecdsa.PrivateKey, error) {
    return ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
}

// Create a mystical certificate
func createCertificate(template, parent *x509.Certificate, pub interface{}, priv interface{}) (*x509.Certificate, []byte, error) {
    certDER, err := x509.CreateCertificate(rand.Reader, template, parent, pub, priv)
    if err != nil {
        return nil, nil, err
    }

    cert, err := x509.ParseCertificate(certDER)
    if err != nil {
        return nil, nil, err
    }

    return cert, certDER, nil
}

// Summon a Certificate Authority
func generateCA() (*x509.Certificate, *ecdsa.PrivateKey, error) {
    caPrivKey, err := generateKey()
    if err != nil {
        return nil, nil, err
    }

    template := x509.Certificate{
        SerialNumber: big.NewInt(1),
        Subject: pkix.Name{
            Organization: []string{"Wizards' Council"},
        },
        NotBefore:             time.Now(),
        NotAfter:              time.Now().AddDate(10, 0, 0),
        KeyUsage:              x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
        ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
        BasicConstraintsValid: true,
        IsCA:                  true,
    }

    caCert, _, err := createCertificate(&template, &template, &caPrivKey.PublicKey, caPrivKey)
    if err != nil {
        return nil, nil, err
    }

    return caCert, caPrivKey, nil
}

// Generate a certificate for a magical domain
func generateCertificate(caCert *x509.Certificate, caPrivKey *ecdsa.PrivateKey, domain string) (*x509.Certificate, *ecdsa.PrivateKey, error) {
    certPrivKey, err := generateKey()
    if err != nil {
        return nil, nil, err
    }

    template := x509.Certificate{
        SerialNumber: big.NewInt(2),
        Subject: pkix.Name{
            Organization: []string{"Wizards' Guild"},
            CommonName:   domain,
        },
        NotBefore:   time.Now(),
        NotAfter:    time.Now().AddDate(1, 0, 0),
        KeyUsage:    x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
        ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
        DNSNames:    []string{domain},
    }

    cert, _, err := createCertificate(&template, caCert, &certPrivKey.PublicKey, caPrivKey)
    if err != nil {
        return nil, nil, err
    }

    return cert, certPrivKey, nil
}

// Inscribe a certificate onto a magical parchment (PEM)
func saveCertificateToPEM(cert *x509.Certificate, filename string) error {
    certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})
    return os.WriteFile(filename, certPEM, 0644)
}

// Inscribe a private key onto a magical parchment (PEM)
func savePrivateKeyToPEM(privKey *ecdsa.PrivateKey, filename string) error {
    privKeyBytes, err := x509.MarshalECPrivateKey(privKey)
    if err != nil {
        return err
    }
    privKeyPEM := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: privKeyBytes})
    return os.WriteFile(filename, privKeyPEM, 0600)
}

func main() {
    // Summon the Certificate Authority
    caCert, caPrivKey, err := generateCA()
    if err != nil {
        panic("The CA summoning ritual failed!")
    }

    // Inscribe the CA certificate and private key
    err = saveCertificateToPEM(caCert, "ca_cert.pem")
    if err != nil {
        panic("Failed to inscribe the CA certificate!")
    }
    err = savePrivateKeyToPEM(caPrivKey, "ca_key.pem")
    if err != nil {
        panic("Failed to inscribe the CA private key!")
    }

    // Generate a certificate for a magical domain
    domain := "hogwarts.edu"
    cert, privKey, err := generateCertificate(caCert, caPrivKey, domain)
    if err != nil {
        panic("The domain certificate summoning failed!")
    }

    // Inscribe the domain certificate and private key
    err = saveCertificateToPEM(cert, "domain_cert.pem")
    if err != nil {
        panic("Failed to inscribe the domain certificate!")
    }
    err = savePrivateKeyToPEM(privKey, "domain_key.pem")
    if err != nil {
        panic("Failed to inscribe the domain private key!")
    }

    fmt.Println("The PKI summoning ritual was successful! CA and domain certificates have been manifested.")
}
로그인 후 복사

이 신비한 의식은 다음을 포함하는 간단한 PKI 시스템의 생성을 보여줍니다.

  1. 인증 기관(CA) 소환
  2. CA를 사용하여 마법의 서명으로 도메인 인증서 축복
  3. 마법의 양피지에 인증서와 개인 키를 새깁니다(PEM 형식)

이 예에서는 Go 암호화 패키지의 실제 애플리케이션을 보여주며 보안 파일 암호화 및 기본 PKI 시스템을 보여줍니다. 여기에는 적절한 키 관리, 안전한 난수 생성, 최신 암호화 알고리즘 사용 등 우리가 논의한 많은 모범 사례와 개념이 통합되어 있습니다.

젊은 마법사여, 현실 세계에서 이러한 암호화 시스템을 구현할 때 항상 다른 마스터 마법사가 자신의 주문을 철저하게 검토하고 테스트하는지 확인하세요. 그리고 가장 중요한 마법 구성 요소의 경우 가능하면 기존 그리모어(라이브러리)를 사용하는 것이 좋습니다.

이제 책임감 있게 암호화폐 주문을 걸어보세요! 귀하의 비밀은 비밀로 유지되고 귀하의 신원은 계속 확인되기를 바랍니다!

위 내용은 실제 암호화폐의 마법: Go&#s 암호화 패키지를 작동하게 하기, Go Crypto 13의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Golang의 목적 : 효율적이고 확장 가능한 시스템 구축 Golang의 목적 : 효율적이고 확장 가능한 시스템 구축 Apr 09, 2025 pm 05:17 PM

Go Language는 효율적이고 확장 가능한 시스템을 구축하는 데 잘 작동합니다. 장점은 다음과 같습니다. 1. 고성능 : 기계 코드로 컴파일, 빠른 달리기 속도; 2. 동시 프로그래밍 : 고어 라틴 및 채널을 통한 멀티 태스킹 단순화; 3. 단순성 : 간결한 구문, 학습 및 유지 보수 비용 절감; 4. 크로스 플랫폼 : 크로스 플랫폼 컴파일, 쉬운 배포를 지원합니다.

Golang 및 C : 동시성 대 원시 속도 Golang 및 C : 동시성 대 원시 속도 Apr 21, 2025 am 12:16 AM

Golang은 동시성에서 C보다 낫고 C는 원시 속도에서 Golang보다 낫습니다. 1) Golang은 Goroutine 및 Channel을 통해 효율적인 동시성을 달성하며, 이는 많은 동시 작업을 처리하는 데 적합합니다. 2) C 컴파일러 최적화 및 표준 라이브러리를 통해 하드웨어에 가까운 고성능을 제공하며 극도의 최적화가 필요한 애플리케이션에 적합합니다.

공연 경주 : 골랑 대 c 공연 경주 : 골랑 대 c Apr 16, 2025 am 12:07 AM

Golang과 C는 각각 공연 경쟁에서 고유 한 장점을 가지고 있습니다. 1) Golang은 높은 동시성과 빠른 발전에 적합하며 2) C는 더 높은 성능과 세밀한 제어를 제공합니다. 선택은 프로젝트 요구 사항 및 팀 기술 스택을 기반으로해야합니다.

Golang vs. Python : 성능 및 확장 성 Golang vs. Python : 성능 및 확장 성 Apr 19, 2025 am 12:18 AM

Golang은 성능과 확장 성 측면에서 Python보다 낫습니다. 1) Golang의 컴파일 유형 특성과 효율적인 동시성 모델은 높은 동시성 시나리오에서 잘 수행합니다. 2) 해석 된 언어로서 파이썬은 천천히 실행되지만 Cython과 같은 도구를 통해 성능을 최적화 할 수 있습니다.

Golang vs. Python : 주요 차이점과 유사성 Golang vs. Python : 주요 차이점과 유사성 Apr 17, 2025 am 12:15 AM

Golang과 Python은 각각 고유 한 장점이 있습니다. Golang은 고성능 및 동시 프로그래밍에 적합하지만 Python은 데이터 과학 및 웹 개발에 적합합니다. Golang은 동시성 모델과 효율적인 성능으로 유명하며 Python은 간결한 구문 및 풍부한 라이브러리 생태계로 유명합니다.

C와 Golang : 성능이 중요 할 때 C와 Golang : 성능이 중요 할 때 Apr 13, 2025 am 12:11 AM

C는 하드웨어 리소스 및 고성능 최적화가 직접 제어되는 시나리오에 더 적합하지만 Golang은 빠른 개발 및 높은 동시성 처리가 필요한 시나리오에 더 적합합니다. 1.C의 장점은 게임 개발과 같은 고성능 요구에 적합한 하드웨어 특성 및 높은 최적화 기능에 가깝습니다. 2. Golang의 장점은 간결한 구문 및 자연 동시성 지원에 있으며, 이는 동시성 서비스 개발에 적합합니다.

Golang의 영향 : 속도, 효율성 및 단순성 Golang의 영향 : 속도, 효율성 및 단순성 Apr 14, 2025 am 12:11 AM

goimpactsdevelopmentpositively throughlyspeed, 효율성 및 단순성.

Golang 및 C : 성능 상충 Golang 및 C : 성능 상충 Apr 17, 2025 am 12:18 AM

Golang과 C의 성능 차이는 주로 메모리 관리, 컴파일 최적화 및 런타임 효율에 반영됩니다. 1) Golang의 쓰레기 수집 메커니즘은 편리하지만 성능에 영향을 줄 수 있습니다. 2) C의 수동 메모리 관리 및 컴파일러 최적화는 재귀 컴퓨팅에서 더 효율적입니다.

See all articles