Skip to content

Instantly share code, notes, and snippets.

@jedisct1
Last active January 3, 2025 18:01
Show Gist options
  • Save jedisct1/8ddffc713739382146481d154c9322e5 to your computer and use it in GitHub Desktop.
Save jedisct1/8ddffc713739382146481d154c9322e5 to your computer and use it in GitHub Desktop.
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"log"
"os"
)
func main() {
// Read the entire file containing the PKCS#8-encoded private key
pemData, err := os.ReadFile("rsakey.pem")
if err != nil {
log.Fatalf("Failed to read file: %v", err)
}
// Decode the PEM block
block, _ := pem.Decode(pemData)
if block == nil {
log.Fatal("Failed to decode PEM block containing private key")
}
// Ensure the block type is "PRIVATE KEY" (PKCS#8)
if block.Type != "PRIVATE KEY" {
log.Fatalf("Expected a block of type 'PRIVATE KEY', but got '%s'", block.Type)
}
// Parse the PKCS#8-encoded private key
parsedKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
log.Fatalf("Unable to parse PKCS#8 private key: %v", err)
}
// Type-assert the private key to *rsa.PrivateKey
privateKey, ok := parsedKey.(*rsa.PrivateKey)
if !ok {
log.Fatal("Not an RSA private key")
}
// Call this if the key is going to be reused for multiple decryptions:
// privateKey.Precompute()
// Successfully loaded RSA private key
fmt.Println("Successfully loaded RSA private key:")
fmt.Printf("Modulus size: %d bits\n", privateKey.N.BitLen())
// 2. Read ciphertext from a file (in this example, raw binary data)
ciphertext, err := os.ReadFile("signed_message.bin")
if err != nil {
log.Fatalf("Failed to read ciphertext file: %v", err)
}
// 3. Decrypt using RSA-PKCS1v15
plaintext, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, ciphertext)
if err != nil {
log.Fatalf("Failed to decrypt: %v", err)
}
fmt.Println("Decrypted message:")
fmt.Println(string(plaintext))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment