使用 GREP11 API 執行加密作業
IBM Cloud® Hyper Protect Crypto Services 提供透過 gRPC 的企業 PKCS #11 (EP11) API(也稱為 GREP11),以遠端存取 Hyper Protect Crypto Services 服務實例來進行資料加密和管理。
擷取 IBM Cloud 認證
若要使用 API,您需要產生服務及鑑別認證。 若要收集您的認證,請執行下列動作:
產生 GREP11 API 要求
為了遠端存取雲端HSMHyper Protect Crypto Services要執行加密操作,您需要產生一個GREP11 API請求,並傳遞GREP11透過 API 呼叫取得 API 端點 URL、服務 ID API 金鑰和 IAM 端點。
對於 Hyper Protect Crypto Services 標準方案,您也可以啟用 GREP11 API 的相互 TLS,以新增另一個鑑別層。 如需相關資訊,請參閱 啟用 EP11 連線的第二層鑑別。
範例:使用 GenerateRandomRequest() 函數產生隨機資料
GREP11 API 支援程式語言 gRPC圖書館。 提供兩個範例 GitHub 儲存庫,供您測試 GREP11 API:
您可以使用下列 Golang 程式碼範例,透過呼叫 GenerateRandom 函數來產生隨機資料。
此範例假設透過 import 陳述式 (例如 gRPC 及 http 套件) 包含額外的必要 Golang 套件。 這 import pb "github.com/IBM-Cloud/hpcs-grep11-go/grpc" 語句被使用GREP11執行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")
在此範例中,更新下列變數:
-
代替
<grep11_server_address>與你的價值GREP11 API端點。 若要尋找服務端點 URL,請從已佈建的服務實例使用者介面中,按一下 概觀 > 連接 > 企業 PKCS #11 端點 URL。 或者,您可以動態地 檢索 API 端點 URL。 回覆值包含下列各項。 視您使用公用或 專用網路 而定,請使用ep11區段中傳回的公用或專用服務端點值。{ "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" } }如果您在 2024 年 4 月 12 日之後在某些區域建立實例,您可能需要使用新格式的新 API 終端節點:
<instance_ID>.ep11.<REGION>.hs-crypto.appdomain.cloud。 可用日期因地區而異。 有關支援的區域、可用日期和新端點 URL 的更多信息,請參閱 新端點。 -
代替
<ibm_cloud_apikey>使用您建立的服務 ID API 金鑰。 可以按照以下說明建立服務 ID API 金鑰 管理服務 ID API 金鑰。
如果樣本請求處理成功,將傳回長度為16位元組的隨機數據,具體見 ep11.AES_BLOCKSIZE。
您可以在下列位置找到先前的鑑別範例以及其他 Golang 程式碼範例:
下一步
您已準備好開始管理加密金鑰和資料。 若要進一步瞭解如何使用 Hyper Protect Crypto Services 的雲端 HSM 函數來管理資料,請參閱 GREP11 API 參考資料文件。