Esecuzione di operazioni crittografiche con l'API GREP11
IBM Cloud® Hyper Protect Crypto Services fornisce una API Enterprise PKCS #11 (EP11) su gRPC (a cui si fa riferimento anche come API GREP11) per accedere in remoto all'istanza del servizio Hyper Protect Crypto Services per la crittografia e la gestione dei dati.
Richiamo delle tue credenziali IBM Cloud
Per utilizzare l'API, devi generare le tue credenziali del servizio e di autenticazione. Per raccogliere le tue credenziali:
Generazione di una richiesta API GREP11
Per accedere da remoto al cloud HSM suHyper Protect Crypto Services per eseguire operazioni crittografiche è necessario generare un fileGREP11 Richiesta API e passa il fileGREP11 URL dell'endpoint API, chiave API dell'ID servizio ed endpoint IAM tramite la chiamata API.
Per il piano standard Hyper Protect Crypto Services, puoi anche abilitare il TLS reciproco per l'API GREP11 per aggiungere un altro livello di autenticazione. Per ulteriori informazioni, consultare Abilitazione del secondo livello di autenticazione per le connessioni EP11.
Esempio: generazione di dati casuali utilizzando la funzione GenerateRandomRequest()
GREP11 L'API supporta i linguaggi di programmazione con gRPC biblioteche. Vengono forniti due repository GitHub di esempio per testare l'API GREP11:
Puoi utilizzare il seguente esempio di codice Golang per generare dei dati casuali richiamando la funzione GenerateRandom.
In questo esempio si presume che i pacchetti Golang aggiuntivi richiesti siano inclusi tramite le istruzioni di importazione, come i package gRPC e
http. IL import pb "github.com/IBM-Cloud/hpcs-grep11-go/grpc" l'istruzione è utilizzata daGREP11 per eseguire chiamate di funzioni API.
import pb "github.com/IBM-Cloud/hpcs-grep11-go/grpc"
// Data structure and supporting methods used for GREP11 authentication
// IAMPerRPCCredentials type defines the fields required for IBM Cloud IAM authentication
// This type implements the gRPC PerRPCCredentials interface
type IAMPerRPCCredentials struct {
expiration time.Time
updateLock sync.Mutex
AccessToken string // Required if APIKey nor Endpoint are specified - IBM Cloud IAM access token
APIKey string // Required if AccessToken is not specified - IBM Cloud API key
Endpoint string // Required if AccessToken is not specified - IBM Cloud IAM endpoint
}
// GetRequestMetadata is used by GRPC for authentication
func (cr *IAMPerRPCCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
// Set token if empty or Set token if expired
if len(cr.APIKey) != 0 && len(cr.Endpoint) != 0 && time.Now().After(cr.expiration) {
if err := cr.getToken(ctx); err != nil {
return nil, err
}
}
return map[string]string{
"authorization": cr.AccessToken,
}, nil
}
// RequireTransportSecurity is used by gRPC for authentication
func (cr *IAMPerRPCCredentials) RequireTransportSecurity() bool {
return true
}
// getToken obtains a bearer token and the expiration
func (cr *IAMPerRPCCredentials) getToken(ctx context.Context) (err error) {
cr.updateLock.Lock()
defer cr.updateLock.Unlock()
// Check if another thread has updated the token
if time.Now().Before(cr.expiration) {
return nil
}
var req *http.Request
client := http.Client{}
requestBody := []byte("grant_type=urn:ibm:params:oauth:grant-type:apikey&apikey=" + cr.APIKey)
req, err = http.NewRequest("POST", cr.Endpoint+"/identity/token", bytes.NewBuffer(requestBody))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req = req.WithContext(ctx)
resp, err := client.Do(req)
if err != nil {
return err
}
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %s", err)
}
defer resp.Body.Close()
iamToken := struct {
AccessToken string `json:"access_token"`
ExpiresIn int32 `json:"expires_in"`
}{}
err = json.Unmarshal(respBody, &iamToken)
if err != nil {
return fmt.Errorf("error unmarshaling response body: %s", err)
}
cr.AccessToken = fmt.Sprintf("Bearer %s", iamToken.AccessToken)
cr.expiration = time.Now().Add((time.Duration(iamToken.ExpiresIn - 60)) * time.Second)
return nil
}
// Generating a GREP11 API function call
// The following IBM Cloud items need to be changed prior to running the sample program
const address = "<grep11_server_address>"
var callOpts = []grpc.DialOption{
grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{})),
grpc.WithPerRPCCredentials(&util.IAMPerRPCCredentials{
APIKey: "<ibm_cloud_apikey>",
Endpoint: "https://iam.cloud.ibm.com",
}),
}
conn, err := grpc.Dial(address, callOpts...)
if err != nil {
panic(fmt.Errorf("Could not connect to server: %s", err))
}
defer conn.Close()
cryptoClient := pb.NewCryptoClient(conn)
rngTemplate := &pb.GenerateRandomRequest{
Len: (uint64)(ep11.AES_BLOCK_SIZE),
}
// Generate 16 bytes of random data for the initialization vector
rng, err := cryptoClient.GenerateRandom(context.Background(), rngTemplate)
if err != nil {
panic(fmt.Errorf("GenerateRandom Error: %s", err))
}
iv := rng.Rnd[:ep11.AES_BLOCK_SIZE]
fmt.Println("Generated IV")
Nell'esempio, aggiorna le seguenti variabili:
-
Sostituire
<grep11_server_address>con il valore del tuoGREP11 Endpoint API. Per trovare l'URL dell'endpoint del servizio, dalla tua IU della tua istanza del servizio di cui è stato eseguito il provisioning, fai clic su Overview > Connect > Enterprise PKCS #11 endpoint URL. In alternativa, puoi dinamicamente recuperare l'URL dell'endpoint API. Il valore restituito include quanto segue: A seconda che tu stia utilizzando la rete pubblica o privata, utilizza il valore dell'endpoint del servizio pubblico o privato restituito nella sezioneep11.{ "instance_id": "<instance_ID>", "kms": { "public": "<instance_ID>.api.<region>.hs-crypto.appdomain.cloud", "private":"<instance_ID>.api.private.<region>.hs-crypto.appdomain.cloud" }, "ep11": { "public": "<instance_ID>.ep11.<region>.hs-crypto.appdomain.cloud", "private":"<instance_ID>.ep11.private.<region>.hs-crypto.appdomain.cloud" } }Se crei le tue istanze dopo il 12 aprile 2024 in alcune regioni, potresti dover utilizzare i nuovi endpoint API con il nuovo formato come
<instance_ID>.ep11.<REGION>.hs-crypto.appdomain.cloud. La data di disponibilità varia in base alla regione. Per ulteriori informazioni sulle regioni supportate, sulle date di disponibilità e sui nuovi URL degli endpoint, vedere Nuovi endpoint. -
Sostituire
<ibm_cloud_apikey>con la chiave API dell'ID servizio che hai creato. La chiave API dell'ID servizio può essere creata seguendo le istruzioni in Gestione della chiave API dell'ID servizio.
Se la richiesta del campione viene elaborata con successo, verranno restituiti dati casuali con una lunghezza di 16 byte, come specificato in ep11.AES_BLOCKSIZE.
L'esempio di autenticazione precedente nonché più esempi di codice Golang possono essere trovati all'indirizzo:
Operazioni successive
È tutto pronto per iniziare a gestire le tue chiavi e i tuoi dati di crittografia. Per ulteriori informazioni sulla gestione dei tuoi dati utilizzando la funzione HSM cloud di Hyper Protect Crypto Services, consulta la documentazione di guida di riferimento dell'API GREP11.