GREP11 API로 암호화 오퍼레이션 수행

IBM Cloud® Hyper Protect Crypto Services는 gRPC(GREP11 API라고도 함)를 통해 Enterprise PKCS #11(EP11) API를 제공하여 데이터 암호화 및 관리를 위해 Hyper Protect Crypto Services 서비스 인스턴스에 원격으로 액세스합니다.

IBM Cloud 인증 정보 검색

API 관련 작업을 수행하려면 서비스 및 인증용 인증 정보를 생성해야 합니다. 신임 정보를 수집하려면 다음 작업을 수행하십시오.

  1. IBM Cloud IAM 액세스 토큰을 생성하십시오.
  2. Hyper Protect Crypto Services 서비스 인스턴스를 고유하게 식별하는 인스턴스 ID를 검색하십시오.

GREP11 API 요성 생성

클라우드 HSM에 원격으로 액세스하려면Hyper Protect Crypto Services 암호화 작업을 수행하려면GREP11 API 요청을 전달하고GREP11 API 호출을 통한 API 엔드포인트 URL, 서비스 ID API 키 및 IAM 엔드포인트입니다.

을 위한Hyper Protect Crypto Services 표준 계획에서는 상호 TLS를 활성화할 수도 있습니다.GREP11 또 다른 인증 계층을 추가하는 API입니다. 자세한 정보는 EP11 연결에 대한 두 번째 인증 계층 사용을 참조하십시오.

예: GenerateRandomRequest() 함수를 사용하여 랜덤 데이터 생성

GREP11 API는 프로그래밍 언어를 지원합니다.gRPC 도서관. GREP11 API를 테스트하기 위해 두 개의 샘플 GitHub 저장소가 제공됩니다.

다음 Golang 코드 예제를 사용하면 GenerateRandom 함수를 호출하여 랜덤 데이터를 생성할 수 있습니다.

이 예에서는 다음과 같은 import 문을 통해 추가로 필요한 Golang 패키지가 포함되어 있다고 가정합니다.gRPC 그리고 http 패키지. import pb "github.com/IBM-Cloud/hpcs-grep11-go/grpc"문은 API 함수 호출을 수행하기 위해 GREP11에서 사용됩니다.

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을 찾으려면 프로비저닝된 서비스 인스턴스 UI에서개요 >연결하다 >엔터프라이즈 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 키 관리.

샘플 요청이 정상적으로 처리되는 경우 ep11.AES_BLOCKSIZE에 지정된 것과 같이 길이가 16바이트인 랜덤 데이터가 리턴됩니다.

이전 인증 예제 및 추가 Golang 코드 예제는 다음 위치에서 찾을 수 있습니다.

다음에 수행할 작업

암호화 키 및 데이터 관리를 시작할 준비가 되었습니다. Hyper Protect Crypto Services의 클라우드 HSM 기능을 사용한 데이터 관리에 대해 자세히 알아보려면 GREP11 API 참조 문서를 확인하십시오.