1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
| // Package main demonstrates generating a self-signed X.509 certificate using
// the ML-DSA (Module-Lattice Digital Signature Algorithm) post-quantum
// signature scheme specified in FIPS 204.
//
// Requirements: Go 1.27+ (crypto/mldsa standard library package).
package main
import (
"crypto/mldsa"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/hex"
"encoding/pem"
"fmt"
"log"
"math/big"
"net"
"os"
"time"
)
// GenerateQuantumSafeCertificate generates a self-signed X.509 certificate
// using ML-DSA-65 (FIPS 204).
//
// ML-DSA-65 provides NIST Security Level 3 (192-bit classical security)
// and is resistant to attacks by both classical and quantum computers.
//
// Returns the parsed certificate and the ML-DSA private key, or an error.
func GenerateQuantumSafeCertificate() (*x509.Certificate, *mldsa.PrivateKey, error) {
fmt.Println("=== Generating ML-DSA-65 Quantum-Safe Certificate ===")
fmt.Println()
// Step 1: Generate ML-DSA-65 key pair
fmt.Println("[1] Generating ML-DSA-65 key pair (FIPS 204, NIST Level 3)...")
privateKey, err := mldsa.GenerateKey(mldsa.MLDSA65())
if err != nil {
return nil, nil, fmt.Errorf("failed to generate ML-DSA-65 key: %w", err)
}
fmt.Println("Key pair generated successfully.")
fmt.Println()
// Step 2: Build certificate template
fmt.Println("[2] Building X.509 certificate template...")
domain := "Example"
template := &x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
CommonName: "Example-PQC",
OrganizationalUnit: []string{"Engineering"},
Organization: []string{"TestOrg"},
Country: []string{"KN"},
Province: []string{"Kandor"},
Locality: []string{"Krypton"},
},
DNSNames: []string{domain, "localhost"},
IPAddresses: []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")},
NotBefore: time.Now(),
NotAfter: time.Now().Add(3 * 365 * 24 * time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
BasicConstraintsValid: true,
IsCA: false,
}
fmt.Printf("Subject: %s\n", template.Subject.CommonName)
fmt.Printf("NotBefore: %s\n", template.NotBefore.Format(time.RFC3339))
fmt.Printf("NotAfter: %s\n", template.NotAfter.Format(time.RFC3339))
fmt.Println()
// Step 3: Create self-signed certificate using ML-DSA-65
fmt.Println("[3] Creating self-signed certificate with ML-DSA-65...")
certDER, err := x509.CreateCertificate(rand.Reader, template, template, privateKey.PublicKey(), privateKey)
if err != nil {
return nil, nil, fmt.Errorf("failed to create certificate: %w", err)
}
fmt.Println("Certificate created successfully (DER encoded).")
fmt.Println()
// Step 4: Parse the certificate back to verify it
fmt.Println("[4] Parsing certificate back from DER...")
cert, err := x509.ParseCertificate(certDER)
if err != nil {
return nil, nil, fmt.Errorf("failed to parse certificate: %w", err)
}
fmt.Println("Certificate parsed successfully.")
fmt.Println()
return cert, privateKey, nil
}
func main() {
cert, privateKey, err := GenerateQuantumSafeCertificate()
if err != nil {
log.Fatalf("FATAL: %v", err)
}
// Print certificate details
fmt.Println("============================================================")
fmt.Println(" QUANTUM-SAFE CERTIFICATE DETAILS ")
fmt.Println("============================================================")
fmt.Println()
fmt.Printf("Version: %d (X.509 v%d)\n", cert.Version, cert.Version)
fmt.Printf("Serial Number: %s\n", cert.SerialNumber.String())
fmt.Printf("Signature Algo: %s\n", cert.SignatureAlgorithm)
fmt.Printf("Public Key Algo: %s\n", cert.PublicKeyAlgorithm)
fmt.Printf("Issuer: %s\n", cert.Issuer.String())
fmt.Printf("Subject: %s\n", cert.Subject.String())
fmt.Printf("Not Before: %s\n", cert.NotBefore.Format(time.RFC3339))
fmt.Printf("Not After: %s\n", cert.NotAfter.Format(time.RFC3339))
fmt.Printf("Is CA: %t\n", cert.IsCA)
fmt.Printf("DNS Names: %v\n", cert.DNSNames)
fmt.Printf("IP Addresses: %v\n", cert.IPAddresses)
fmt.Println()
// Print public key info
fmt.Println("============================================================")
fmt.Println(" ML-DSA-65 PUBLIC KEY ")
fmt.Println("============================================================")
fmt.Println()
pubKey := privateKey.PublicKey()
pubKeyBytes := pubKey.Bytes()
fmt.Printf("Algorithm: ML-DSA-65 (FIPS 204)\n")
fmt.Printf("Security Level: NIST Level 3 (192-bit)\n")
fmt.Printf("Public Key Size: %d bytes\n", len(pubKeyBytes))
fmt.Printf("Public Key (hex, first 64 bytes):\n")
fmt.Printf(" %s...\n", hex.EncodeToString(pubKeyBytes[:64]))
fmt.Println()
// Print private key seed info
fmt.Println("============================================================")
fmt.Println(" ML-DSA-65 PRIVATE KEY SEED ")
fmt.Println("============================================================")
fmt.Println()
privKeyBytes := privateKey.Bytes()
fmt.Printf("Seed Size: %d bytes\n", len(privKeyBytes))
fmt.Printf("Seed (hex): %s\n", hex.EncodeToString(privKeyBytes))
fmt.Println()
// Print signature info from the certificate
fmt.Println("============================================================")
fmt.Println(" CERTIFICATE SIGNATURE ")
fmt.Println("============================================================")
fmt.Println()
fmt.Printf("Signature Algo: %s\n", cert.SignatureAlgorithm)
fmt.Printf("Signature Size: %d bytes\n", len(cert.Signature))
fmt.Printf("Signature (hex, first 64 bytes):\n")
if len(cert.Signature) >= 64 {
fmt.Printf(" %s...\n", hex.EncodeToString(cert.Signature[:64]))
}
fmt.Println()
// Marshal and print the private key in PKCS#8 PEM format
fmt.Println("============================================================")
fmt.Println(" PRIVATE KEY (PKCS#8 PEM FORMAT) ")
fmt.Println("============================================================")
fmt.Println()
pkcs8DER, err := x509.MarshalPKCS8PrivateKey(privateKey)
if err != nil {
log.Fatalf("Failed to marshal private key to PKCS#8: %v", err)
}
privPEM := pem.EncodeToMemory(&pem.Block{
Type: "PRIVATE KEY",
Bytes: pkcs8DER,
})
fmt.Printf("%s\n", privPEM)
// Marshal and print the public key in PKIX PEM format
fmt.Println("============================================================")
fmt.Println(" PUBLIC KEY (PKIX PEM FORMAT) ")
fmt.Println("============================================================")
fmt.Println()
pkixDER, err := x509.MarshalPKIXPublicKey(pubKey)
if err != nil {
log.Fatalf("Failed to marshal public key to PKIX: %v", err)
}
pubPEM := pem.EncodeToMemory(&pem.Block{
Type: "PUBLIC KEY",
Bytes: pkixDER,
})
fmt.Printf("%s\n", pubPEM)
// Print the certificate in PEM format
fmt.Println("============================================================")
fmt.Println(" QUANTUM-SAFE CERTIFICATE (PEM FORMAT) ")
fmt.Println("============================================================")
fmt.Println()
certPEM := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: cert.Raw,
})
fmt.Printf("%s\n", certPEM)
// Verify the certificate signature against itself (self-signed)
fmt.Println("============================================================")
fmt.Println(" SELF-SIGNATURE VERIFICATION ")
fmt.Println("============================================================")
fmt.Println()
err = cert.CheckSignatureFrom(cert)
if err != nil {
fmt.Printf(" Verification FAILED: %v\n", err)
} else {
fmt.Println(" Verification PASSED: Self-signed certificate signature is valid.")
}
fmt.Println()
// Write certificate and keys to files for inspection
fmt.Println("============================================================")
fmt.Println(" WRITING FILES TO DISK ")
fmt.Println("============================================================")
fmt.Println()
if err := os.WriteFile("certificate.pem", certPEM, 0644); err != nil {
log.Fatalf("Failed to write certificate: %v", err)
}
fmt.Println(" Written: certificate.pem")
if err := os.WriteFile("private_key.pem", privPEM, 0600); err != nil {
log.Fatalf("Failed to write private key: %v", err)
}
fmt.Println(" Written: private_key.pem")
if err := os.WriteFile("public_key.pem", pubPEM, 0644); err != nil {
log.Fatalf("Failed to write public key: %v", err)
}
fmt.Println(" Written: public_key.pem")
}
|