### Install crypto11 Library Source: https://github.com/thalesgroup/crypto11/blob/master/README.md Use 'go get' to install the crypto11 library. Requires Go v1.11+. ```bash go get github.com/ThalesGroup/crypto11 ``` -------------------------------- ### SoftHSM2 Configuration File Example Source: https://github.com/thalesgroup/crypto11/blob/master/README.md An example configuration file for SoftHSM2, specifying the directory for token storage and the backend type. This is used for setting up a SoftHSM2 slot. ```bash directories.tokendir = /home/rjk/go/src/github.com/ThalesIgnite/crypto11/tokens objectstore.backend = file log.level = INFO ``` -------------------------------- ### Generate and Use RSA Key Pair for Signing Source: https://context7.com/thalesgroup/crypto11/llms.txt Generates an RSA key pair on the token and uses it for signing and verification. This example demonstrates generating a key, signing a message hash, and verifying the signature using the public key. Ensure the token has sufficient space and permissions. ```go package main import ( "crypto" "crypto/rand" "crypto/rsa" "crypto/sha256" "log" "github.com/ThalesGroup/crypto11" ) func main() { ctx, _ := crypto11.ConfigureFromFile("config.json") defer ctx.Close() // Generate 2048-bit RSA key pair keyID := []byte("my-rsa-key-001") signer, err := ctx.GenerateRSAKeyPair(keyID, 2048) if err != nil { log.Fatalf("Failed to generate RSA key: %v", err) } // Sign a message message := []byte("Hello, HSM!") hash := sha256.Sum256(message) signature, err := signer.Sign(rand.Reader, hash[:], crypto.SHA256) if err != nil { log.Fatalf("Failed to sign: %v", err) } // Verify signature using the public key pubKey := signer.Public().(*rsa.PublicKey) err = rsa.VerifyPKCS1v15(pubKey, crypto.SHA256, hash[:], signature) if err != nil { log.Fatalf("Signature verification failed: %v", err) } log.Println("RSA signature verified successfully") } ``` -------------------------------- ### Find All Paired Certificates for TLS Source: https://context7.com/thalesgroup/crypto11/llms.txt Retrieves all certificates from the HSM that have corresponding private keys also stored on the HSM. These are suitable for use in TLS configurations. The example demonstrates how to use these certificates with an http.Server. ```go package main import ( "crypto/tls" "log" "net/http" "github.com/ThalesGroup/crypto11" ) func main() { ctx, _ := crypto11.ConfigureFromFile("config.json") defer ctx.Close() // Get all certificates with their HSM-protected private keys tlsCerts, err := ctx.FindAllPairedCertificates() if err != nil { log.Fatalf("Failed to find certificates: %v", err) } log.Printf("Found %d TLS certificates", len(tlsCerts)) // Use for TLS server if len(tlsCerts) > 0 { tlsConfig := &tls.Config{ Certificates: tlsCerts, } server := &http.Server{ Addr: ":8443", TLSConfig: tlsConfig, } log.Println("Starting TLS server with HSM-protected keys...") // server.ListenAndServeTLS("", "") // Certs already in config _ = server } } ``` -------------------------------- ### Remote Debugging Unit Tests Source: https://github.com/thalesgroup/crypto11/blob/master/README.md Start a Delve debugger session for remote debugging of unit tests. This is useful for inspecting test execution flow. ```bash dlv test --headless --listen=:2345 --api-version=2 --accept-multiclient block_test.go $DEPENDENCIES ``` -------------------------------- ### Find Certificate on HSM Source: https://context7.com/thalesgroup/crypto11/llms.txt Retrieves a previously imported certificate from the HSM by its ID, label, or serial number. Provide at least one of these parameters for the search. The example shows finding by ID and then by serial number. ```go package main import ( "log" "math/big" "github.com/ThalesGroup/crypto11" ) func main() { ctx, _ := crypto11.ConfigureFromFile("config.json") defer ctx.Close() // Find by ID cert, err := ctx.FindCertificate([]byte("my-rsa-key-001"), nil, nil) if err != nil { log.Fatalf("Certificate not found: %v", err) } log.Printf("Found certificate: %s", cert.Subject.CommonName) log.Printf("Valid until: %s", cert.NotAfter) // Find by serial number serial := big.NewInt(123456789) certBySerial, _ := ctx.FindCertificate(nil, nil, serial) _ = certBySerial } ``` -------------------------------- ### Delete Certificate from HSM Source: https://context7.com/thalesgroup/crypto11/llms.txt Removes a certificate from the HSM token. The certificate can be identified by its ID or serial number. The example shows deletion by ID and then by serial number. ```go package main import ( "log" "math/big" "github.com/ThalesGroup/crypto11" ) func main() { ctx, _ := crypto11.ConfigureFromFile("config.json") defer ctx.Close() // Delete by ID err := ctx.DeleteCertificate([]byte("cert-001"), nil, nil) if err != nil { log.Fatalf("Failed to delete certificate: %v", err) } // Delete by serial number serial := big.NewInt(123456789) ctx.DeleteCertificate(nil, nil, serial) log.Println("Certificate deleted") } ``` -------------------------------- ### Configure PKCS#11 Context from File Source: https://context7.com/thalesgroup/crypto11/llms.txt Loads PKCS#11 configuration from a JSON file and creates a Context. This is useful for externalizing configuration details. The JSON file should contain fields like Path, TokenLabel, and Pin. ```go package main import ( "log" "github.com/ThalesGroup/crypto11" ) // config.json: // { // "Path": "/usr/lib/softhsm/libsofthsm2.so", // "TokenLabel": "my-token", // "Pin": "1234" // } func main() { ctx, err := crypto11.ConfigureFromFile("config.json") if err != nil { log.Fatalf("Failed to configure from file: %v", err) } defer ctx.Close() log.Println("Configured from file successfully") } ``` -------------------------------- ### Configure and ConfigureFromFile Source: https://context7.com/thalesgroup/crypto11/llms.txt Methods to initialize a PKCS#11 context for managing session pooling and cryptographic operations. ```APIDOC ## Configure ### Description Creates a new Context for connecting to a PKCS#11 token, managing session pooling and thread-safe access. ### Parameters #### Request Body - **config** (struct) - Required - Configuration containing Path, TokenLabel, Pin, and MaxSessions. ## ConfigureFromFile ### Description Loads PKCS#11 configuration from a JSON file and creates a Context. ### Parameters #### Path Parameters - **path** (string) - Required - Path to the JSON configuration file. ``` -------------------------------- ### Enable CGo and Build crypto11 Source: https://github.com/thalesgroup/crypto11/blob/master/README.md Enable CGo and build the crypto11 package. CGo is required for cryptographic operations. ```bash go env -w CGO_ENABLED=1 go build ``` -------------------------------- ### Run Vulnerability Check Source: https://github.com/thalesgroup/crypto11/blob/master/README.md Scan the project and its dependencies for known vulnerabilities using govulncheck. ```bash $ govulncheck ./... ─╯ Scanning your code and 112 packages across 5 dependent modules for known vulnerabilities... No vulnerabilities found. ``` -------------------------------- ### Configure PKCS#11 Context Source: https://context7.com/thalesgroup/crypto11/llms.txt Creates a new Context for connecting to a PKCS#11 token using a Config struct. The Context manages session pooling and provides thread-safe access to cryptographic operations. Ensure the PKCS#11 library path and token credentials are correct. ```go package main import ( "log" "github.com/ThalesGroup/crypto11" ) func main() { // Configure using a Config struct config := &crypto11.Config{ Path: "/usr/lib/softhsm/libsofthsm2.so", TokenLabel: "my-token", Pin: "1234", MaxSessions: 10, } ctx, err := crypto11.Configure(config) if err != nil { log.Fatalf("Failed to configure PKCS#11: %v", err) } defer ctx.Close() // Context is now ready for cryptographic operations log.Println("Successfully connected to PKCS#11 token") } ``` -------------------------------- ### Run Unit Tests with Specific Dependencies Source: https://github.com/thalesgroup/crypto11/blob/master/README.md Execute unit tests on a specific file by exporting the DEPENDENCIES environment variable. This allows targeted testing of individual components. ```bash export DEPENDENCIES="rand.go attributes.go hmac.go crypto11.go common.go keys.go rsa.go certificates.go ecdsa.go blockmode.go sessions.go aead.go dsa.go symmetric.go common_test.go" go test block_test.go $DEPENDENCIES ``` -------------------------------- ### Initialize SoftHSM2 Token Source: https://github.com/thalesgroup/crypto11/blob/master/README.md Initialize a SoftHSM2 token with SO and User PINs. Ensure the SOFTHSM2_CONF environment variable is set. ```bash $ export SOFTHSM2_CONF=`pwd`/softhsm2.conf $ softhsm2-util --init-token --slot 0 --label test === SO PIN (4-255 characters) === Please enter SO PIN: ******** Please reenter SO PIN: ******** === User PIN (4-255 characters) === Please enter user PIN: ******** Please reenter user PIN: ******** The token has been initialized. ``` -------------------------------- ### Enable nCipher nShield PKCS#11 Debug Logging Source: https://github.com/thalesgroup/crypto11/blob/master/README.md Enable debug logging for nCipher nShield PKCS#11 operations by setting the CKNFAST_DEBUG environment variable. ```bash export CKNFAST_DEBUG=2 ``` -------------------------------- ### Minimal crypto11 Configuration File Source: https://github.com/thalesgroup/crypto11/blob/master/README.md A basic JSON configuration for crypto11, specifying the PKCS#11 library path, token label, and user PIN. ```json { "Path": "/usr/lib/softhsm/libsofthsm2.so", "TokenLabel": "token1", "Pin": "password" } ``` -------------------------------- ### Configure Crypto11 with TPM and PKCS11 Source: https://github.com/thalesgroup/crypto11/blob/master/README.md Configuration for Crypto11 to use a TPM via the tpm2-pkcs11 library. Keys must be pre-created in the TPM. ```json { "Path": "/usr/lib/x86_64-linux-gnu/libtpm2_pkcs11.so.1", "TokenLabel": "mylabel", "Pin": "mypin" } ``` -------------------------------- ### Retrieve Key Attributes Source: https://context7.com/thalesgroup/crypto11/llms.txt Fetches specific PKCS#11 attributes from a stored key object using the context. ```go package main import ( "log" "github.com/ThalesGroup/crypto11" ) func main() { ctx, _ := crypto11.ConfigureFromFile("config.json") defer ctx.Close() key, _ := ctx.FindKeyPair([]byte("my-rsa-key-001"), nil) // Get multiple attributes attrs, err := ctx.GetAttributes(key, []crypto11.AttributeType{ crypto11.CkaId, crypto11.CkaLabel, crypto11.CkaKeyType, }) if err != nil { log.Fatalf("Failed to get attributes: %v", err) } if id, ok := attrs[crypto11.CkaId]; ok { log.Printf("Key ID: %x", id.Value) } if label, ok := attrs[crypto11.CkaLabel]; ok { log.Printf("Key Label: %s", label.Value) } } ``` -------------------------------- ### Configure Crypto11 with nCipher nShield (Token Label) Source: https://github.com/thalesgroup/crypto11/blob/master/README.md Configuration for Crypto11 to use an nCipher nShield token identified by its label. Requires a card from the cardset to be in the slot. ```json { "Path" : "/opt/nfast/toolkits/pkcs11/libcknfast.so", "TokenLabel": "rjk", "Pin" : "password" } ``` -------------------------------- ### Configure Crypto11 with nCipher nShield (Accelerator) Source: https://github.com/thalesgroup/crypto11/blob/master/README.md Configuration for Crypto11 to use the 'accelerator' token on an nCipher nShield module, protecting keys with the module only. ```json { "Path" : "/opt/nfast/toolkits/pkcs11/libcknfast.so", "TokenLabel": "accelerator", "Pin" : "password" } ``` -------------------------------- ### Find All Key Pairs Source: https://context7.com/thalesgroup/crypto11/llms.txt Lists all asymmetric key pairs currently stored on the HSM token. ```go package main import ( "log" "github.com/ThalesGroup/crypto11" ) func main() { ctx, _ := crypto11.ConfigureFromFile("config.json") defer ctx.Close() keys, err := ctx.FindAllKeyPairs() if err != nil { log.Fatalf("Failed to list keys: %v", err) } log.Printf("Found %d key pairs on token", len(keys)) for i, key := range keys { log.Printf("Key %d: public key type %T", i, key.Public()) } } ``` -------------------------------- ### Configure Crypto11 with nCipher nShield (Token Serial) Source: https://github.com/thalesgroup/crypto11/blob/master/README.md Configuration for Crypto11 to use an nCipher nShield token identified by its serial number. Requires a card from the cardset to be in the slot. ```json { "Path" : "/opt/nfast/toolkits/pkcs11/libcknfast.so", "TokenSerial": "1d42780caa22efd5", "Pin" : "password" } ``` -------------------------------- ### Import Certificate with Label to HSM Source: https://context7.com/thalesgroup/crypto11/llms.txt Imports a certificate onto the HSM token, specifying both an ID and a label. This allows for more flexible retrieval later. The certificate object must be loaded and parsed prior to this operation. ```go package main import ( "crypto/x509" "log" "github.com/ThalesGroup/crypto11" ) func main() { ctx, _ := crypto11.ConfigureFromFile("config.json") defer ctx.Close() var cert *x509.Certificate // Load certificate as shown above err := ctx.ImportCertificateWithLabel( []byte("cert-001"), []byte("tls-server-cert"), cert, ) if err != nil { log.Fatalf("Failed to import certificate: %v", err) } } ``` -------------------------------- ### Perform RSA Decryption Source: https://context7.com/thalesgroup/crypto11/llms.txt Demonstrates decrypting data using an HSM-protected RSA private key by type asserting the signer to crypto.Decrypter. ```go package main import ( "crypto" "crypto/rand" "crypto/rsa" "log" "github.com/ThalesGroup/crypto11" ) func main() { ctx, _ := crypto11.ConfigureFromFile("config.json") defer ctx.Close() // Generate or find an RSA key signer, _ := ctx.GenerateRSAKeyPair([]byte("decrypt-key"), 2048) // Type assert to get decryption capability decrypter := signer.(crypto.Decrypter) pubKey := decrypter.Public().(*rsa.PublicKey) // Encrypt with public key (done in software) plaintext := []byte("secret message") ciphertext, err := rsa.EncryptOAEP(crypto.SHA256.New(), rand.Reader, pubKey, plaintext, nil) if err != nil { log.Fatalf("Encryption failed: %v", err) } // Decrypt with HSM-protected private key decrypted, err := decrypter.Decrypt(rand.Reader, ciphertext, &rsa.OAEPOptions{ Hash: crypto.SHA256, }) if err != nil { log.Fatalf("Decryption failed: %v", err) } log.Printf("Decrypted: %s", decrypted) } ``` -------------------------------- ### Find Key Pair by ID or Label Source: https://context7.com/thalesgroup/crypto11/llms.txt Retrieves an existing asymmetric key pair from the token using either its unique ID or a descriptive label. ```go package main import ( "crypto" "crypto/rand" "crypto/sha256" "log" "github.com/ThalesGroup/crypto11" ) func main() { ctx, _ := crypto11.ConfigureFromFile("config.json") defer ctx.Close() // Find key by ID keyID := []byte("my-rsa-key-001") signer, err := ctx.FindKeyPair(keyID, nil) if err != nil { log.Fatalf("Key not found: %v", err) } // Or find by label keyLabel := []byte("production-signing-key") signerByLabel, err := ctx.FindKeyPair(nil, keyLabel) if err != nil { log.Fatalf("Key not found by label: %v", err) } // Use the found key for signing hash := sha256.Sum256([]byte("data to sign")) signature, _ := signer.Sign(rand.Reader, hash[:], crypto.SHA256) log.Printf("Signed with found key, signature length: %d", len(signature)) _ = signerByLabel } ``` -------------------------------- ### Import X.509 Certificate to HSM Source: https://context7.com/thalesgroup/crypto11/llms.txt Imports an X.509 certificate onto the HSM token. The certificate is loaded from a PEM file and parsed before import. Ensure the corresponding private key is available on the HSM if you intend to pair them. ```go package main import ( "crypto/x509" "encoding/pem" "log" "os" "github.com/ThalesGroup/crypto11" ) func main() { ctx, _ := crypto11.ConfigureFromFile("config.json") defer ctx.Close() // Load certificate from PEM file pemData, _ := os.ReadFile("certificate.pem") block, _ := pem.Decode(pemData) cert, err := x509.ParseCertificate(block.Bytes) if err != nil { log.Fatalf("Failed to parse certificate: %v", err) } // Import certificate with ID matching its key pair err = ctx.ImportCertificate([]byte("my-rsa-key-001"), cert) if err != nil { log.Fatalf("Failed to import certificate: %v", err) } log.Printf("Imported certificate for: %s", cert.Subject.CommonName) } ``` -------------------------------- ### Generate Release Notes with github-changelog-generator Source: https://github.com/thalesgroup/crypto11/wiki/Labelling-Issues-and-Pull-Requests-and-Creating-Release-Notes Use this command to generate the CHANGELOG.md file. Replace `v1.2.3` with the actual release tag. This command excludes PRs labelled 'has issue' and only includes unreleased changes. ```bash github_changelog_generator -u ThalesIgnite -p crypto11 --exclude-labels "has issue" \ --unreleased-only --future-release v1.2.3 ``` -------------------------------- ### GenerateRSAKeyPair and GenerateRSAKeyPairWithLabel Source: https://context7.com/thalesgroup/crypto11/llms.txt Methods for generating RSA key pairs on the HSM token. ```APIDOC ## GenerateRSAKeyPair ### Description Generates an RSA key pair on the token with the specified bit size. ### Parameters - **keyID** ([]byte) - Required - Unique identifier for the key. - **bits** (int) - Required - Bit size of the RSA key. ### Response - **signer** (SignerDecrypter) - Returns a signer/decrypter interface for operations. ## GenerateRSAKeyPairWithLabel ### Description Generates an RSA key pair with both CKA_ID and CKA_LABEL attributes set. ### Parameters - **keyID** ([]byte) - Required - Unique identifier for the key. - **keyLabel** ([]byte) - Required - Label attribute for the key. - **bits** (int) - Required - Bit size of the RSA key. ``` -------------------------------- ### Configure Crypto11 with SoftHSM2 Source: https://github.com/thalesgroup/crypto11/blob/master/README.md Configuration for Crypto11 to use a SoftHSM2 token. Specify the PKCS#11 library path, token label, and PIN. ```json { "Path" : "/usr/lib/softhsm/libsofthsm2.so", "TokenLabel": "test", "Pin" : "password" } ``` -------------------------------- ### Generate RSA Key Pair with Label Source: https://context7.com/thalesgroup/crypto11/llms.txt Generates an RSA key pair on the token, setting both CKA_ID and CKA_LABEL attributes. This allows for easier identification and management of keys stored on the HSM. The keyLabel parameter is used to assign a human-readable label. ```go package main import ( "log" "github.com/ThalesGroup/crypto11" ) func main() { ctx, _ := crypto11.ConfigureFromFile("config.json") defer ctx.Close() keyID := []byte("key-001") keyLabel := []byte("production-signing-key") signer, err := ctx.GenerateRSAKeyPairWithLabel(keyID, keyLabel, 4096) if err != nil { log.Fatalf("Failed to generate labeled RSA key: %v", err) } log.Printf("Generated RSA key with label: %s", keyLabel) _ = signer } ``` -------------------------------- ### CloudHSM Configuration for Testing Source: https://github.com/thalesgroup/crypto11/blob/master/README.md A minimal JSON configuration for testing with AWS CloudHSM, including the library path, token label, and a username:password format for the PIN. It also enables GCM IV generation from the HSM. ```json { "Path": "/opt/cloudhsm/lib/libcloudhsm_pkcs11_standard.so", "TokenLabel": "cavium", "Pin": "username:password", "UseGCMIVFromHSM": true } ``` -------------------------------- ### Generate Symmetric Keys (AES, DES3) Source: https://context7.com/thalesgroup/crypto11/llms.txt Generates symmetric keys (AES or DES3) on the HSM. Specify the key size and cipher type. The generated keys are suitable for encryption and decryption operations. ```go package main import ( "log" "github.com/ThalesGroup/crypto11" ) func main() { ctx, _ := crypto11.ConfigureFromFile("config.json") defer ctx.Close() // Generate 256-bit AES key keyID := []byte("aes-key-001") aesKey, err := ctx.GenerateSecretKey(keyID, 256, crypto11.CipherAES) if err != nil { log.Fatalf("Failed to generate AES key: %v", err) } log.Printf("Generated AES-256 key, block size: %d", aesKey.Cipher.BlockSize) // Generate DES3 key (168-bit effective) des3Key, err := ctx.GenerateSecretKey([]byte("des3-key-001"), 168, crypto11.CipherDES3) if err != nil { log.Fatalf("Failed to generate DES3 key: %v", err) } log.Printf("Generated DES3 key, block size: %d", des3Key.Cipher.BlockSize) } ``` -------------------------------- ### Generate Labeled Symmetric Key Source: https://context7.com/thalesgroup/crypto11/llms.txt Generates a symmetric key on the HSM and assigns both an ID and a human-readable label. This is useful for key management and identification. ```go package main import ( "log" "github.com/ThalesGroup/crypto11" ) func main() { ctx, _ := crypto11.ConfigureFromFile("config.json") defer ctx.Close() key, err := ctx.GenerateSecretKeyWithLabel( []byte("key-001"), []byte("data-encryption-key"), 256, crypto11.CipherAES, ) if err != nil { log.Fatalf("Failed to generate key: %v", err) } log.Println("Generated labeled AES key") _ = key } ``` -------------------------------- ### Run Test Suite with Unsupported Tests Skipped Source: https://github.com/thalesgroup/crypto11/blob/master/README.md Execute the crypto11 test suite while skipping specific tests (CERTS, OAEP_LABEL, DSA) that may not be supported by AWS CloudHSM. This ensures compatibility with the CloudHSM environment. ```bash CRYPTO11_SKIP=CERTS,OAEP_LABEL,DSA go test -v ``` -------------------------------- ### Generate DSA Key Pair on HSM Source: https://context7.com/thalesgroup/crypto11/llms.txt Generates a DSA key pair on the HSM. Requires DSA parameters to be generated first. The generated key can then be used for signing operations. ```go package main import ( "crypto" "crypto/dsa" "crypto/rand" "crypto/sha256" "log" "github.com/ThalesGroup/crypto11" ) func main() { ctx, _ := crypto11.ConfigureFromFile("config.json") defer ctx.Close() // Generate DSA parameters params := &dsa.Parameters{} err := dsa.GenerateParameters(params, rand.Reader, dsa.L2048N256) if err != nil { log.Fatalf("Failed to generate DSA parameters: %v", err) } // Generate DSA key pair on HSM keyID := []byte("dsa-key-001") signer, err := ctx.GenerateDSAKeyPair(keyID, params) if err != nil { log.Fatalf("Failed to generate DSA key: %v", err) } // Sign a message hash := sha256.Sum256([]byte("DSA test message")) signature, err := signer.Sign(rand.Reader, hash[:], crypto.SHA256) if err != nil { log.Fatalf("Failed to sign: %v", err) } log.Printf("DSA signature length: %d bytes", len(signature)) } ``` -------------------------------- ### Generate ECDSA Key Pair Source: https://context7.com/thalesgroup/crypto11/llms.txt Creates a new ECDSA key pair on the token using a specified elliptic curve and demonstrates signing and verification. ```go package main import ( "crypto" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/sha256" "log" "github.com/ThalesGroup/crypto11" ) func main() { ctx, _ := crypto11.ConfigureFromFile("config.json") defer ctx.Close() // Generate ECDSA key with P-256 curve keyID := []byte("ecdsa-key-001") signer, err := ctx.GenerateECDSAKeyPair(keyID, elliptic.P256()) if err != nil { log.Fatalf("Failed to generate ECDSA key: %v", err) } // Sign a message message := []byte("Hello, ECDSA!") hash := sha256.Sum256(message) signature, err := signer.Sign(rand.Reader, hash[:], crypto.SHA256) if err != nil { log.Fatalf("Failed to sign: %v", err) } // Verify signature pubKey := signer.Public().(*ecdsa.PublicKey) valid := ecdsa.VerifyASN1(pubKey, hash[:], signature) log.Printf("ECDSA signature valid: %v", valid) } ``` -------------------------------- ### Generate ECDSA Key Pair with Label Source: https://context7.com/thalesgroup/crypto11/llms.txt Generates an ECDSA key pair assigning both an ID and a label for easier identification. ```go package main import ( "crypto/elliptic" "log" "github.com/ThalesGroup/crypto11" ) func main() { ctx, _ := crypto11.ConfigureFromFile("config.json") defer ctx.Close() // Supported curves: P-224, P-256, P-384, P-521 signer, err := ctx.GenerateECDSAKeyPairWithLabel( []byte("ec-key-001"), []byte("jwt-signing-key"), elliptic.P384(), ) if err != nil { log.Fatalf("Failed to generate ECDSA key: %v", err) } log.Println("Generated P-384 ECDSA key pair") _ = signer } ``` -------------------------------- ### Generate HMAC-SHA256 with HSM Key Source: https://context7.com/thalesgroup/crypto11/llms.txt Creates an HMAC-SHA256 hash instance using an HSM-protected secret key. Ensure the secret key is generated or imported into the HSM prior to use. ```go package main import ( "log" "github.com/miekg/pkcs11" "github.com/ThalesGroup/crypto11" ) func main() { ctx, _ := crypto11.ConfigureFromFile("config.json") defer ctx.Close() // Generate HMAC key hmacKey, err := ctx.GenerateSecretKey( []byte("hmac-key-001"), 256, crypto11.CipherHMACSHA256, ) if err != nil { log.Fatalf("Failed to generate HMAC key: %v", err) } // Create HMAC-SHA256 hash mac, err := hmacKey.NewHMAC(pkcs11.CKM_SHA256_HMAC, 32) if err != nil { log.Fatalf("Failed to create HMAC: %v", err) } // Write data to HMAC mac.Write([]byte("message to authenticate")) // Get the MAC result := mac.Sum(nil) log.Printf("HMAC-SHA256: %x", result) log.Printf("HMAC size: %d bytes", mac.Size()) } ``` -------------------------------- ### CBC Encryption and Decryption with HSM Key Source: https://context7.com/thalesgroup/crypto11/llms.txt Performs CBC mode encryption and decryption using a symmetric key stored on the HSM. Ensure the plaintext is a multiple of the block size. Remember to close the encrypter/decrypter to release HSM resources. ```go package main import ( "bytes" "crypto/rand" "log" "github.com/ThalesGroup/crypto11" ) func main() { ctx, _ := crypto11.ConfigureFromFile("config.json") defer ctx.Close() // Generate or find AES key key, _ := ctx.GenerateSecretKey([]byte("cbc-key"), 256, crypto11.CipherAES) // Generate random IV iv := make([]byte, 16) // AES block size rand.Read(iv) // Plaintext must be multiple of block size plaintext := []byte("16 bytes block!!") // Encrypt using CBC mode encrypter, err := key.NewCBCEncrypterCloser(iv) if err != nil { log.Fatalf("Failed to create encrypter: %v", err) } ciphertext := make([]byte, len(plaintext)) encrypter.CryptBlocks(ciphertext, plaintext) encrypter.Close() // Important: release HSM resources // Decrypt using CBC mode decrypter, err := key.NewCBCDecrypterCloser(iv) if err != nil { log.Fatalf("Failed to create decrypter: %v", err) } decrypted := make([]byte, len(ciphertext)) decrypter.CryptBlocks(decrypted, ciphertext) decrypter.Close() if bytes.Equal(plaintext, decrypted) { log.Println("CBC encryption/decryption successful") } } ``` -------------------------------- ### Find Symmetric Key by ID or Label Source: https://context7.com/thalesgroup/crypto11/llms.txt Retrieves a previously generated symmetric key from the HSM using its ID or label. This function is essential for accessing existing keys for cryptographic operations. ```go package main import ( "log" "github.com/ThalesGroup/crypto11" ) func main() { ctx, _ := crypto11.ConfigureFromFile("config.json") defer ctx.Close() // Find by ID key, err := ctx.FindKey([]byte("aes-key-001"), nil) if err != nil { log.Fatalf("Key not found: %v", err) } log.Printf("Found key with block size: %d", key.Cipher.BlockSize) // Find all symmetric keys allKeys, _ := ctx.FindAllKeys() log.Printf("Total symmetric keys: %d", len(allKeys)) } ``` -------------------------------- ### Generate Random Bytes with HSM Source: https://context7.com/thalesgroup/crypto11/llms.txt Uses the HSM's hardware random number generator to produce cryptographically secure random bytes. ```go package main import ( "encoding/hex" "log" "github.com/ThalesGroup/crypto11" ) func main() { ctx, _ := crypto11.ConfigureFromFile("config.json") defer ctx.Close() // Get hardware RNG reader rng, err := ctx.NewRandomReader() if err != nil { log.Fatalf("Failed to create random reader: %v", err) } // Generate random bytes randomBytes := make([]byte, 32) n, err := rng.Read(randomBytes) if err != nil { log.Fatalf("Failed to read random bytes: %v", err) } log.Printf("Generated %d random bytes: %s", n, hex.EncodeToString(randomBytes)) } ``` -------------------------------- ### Delete Keys from Token Source: https://context7.com/thalesgroup/crypto11/llms.txt Removes existing key pairs or symmetric keys from the HSM token. ```go package main import ( "log" "github.com/ThalesGroup/crypto11" ) func main() { ctx, _ := crypto11.ConfigureFromFile("config.json") defer ctx.Close() // Find and delete a key pair key, err := ctx.FindKeyPair([]byte("key-to-delete"), nil) if err != nil { log.Fatalf("Key not found: %v", err) } err = key.Delete() if err != nil { log.Fatalf("Failed to delete key: %v", err) } log.Println("Key pair deleted from token") // Delete a symmetric key secretKey, _ := ctx.FindKey([]byte("secret-to-delete"), nil) secretKey.Delete() } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.