대부분의 사용 사례에서는 메시지 인증 코드 (MAC) 기본 요소와 함께 HMAC_SHA256 키 유형을 사용하는 것이 좋습니다.
아무도 데이터를 조작할 수 없도록 하려면 메시지 인증 코드 (MAC) 기본 요소를 사용하는 것이 좋습니다. 이 요소는 단일 키를 사용하여 메시지 인증 코드를 생성하고 확인합니다. MAC은 데이터를 암호화하지 않습니다. 대부분의 경우 암호화 및 MAC을 포함하는 AEAD로 데이터를 보호하는 것이 MAC만 사용하는 것보다 좋습니다.
다음 예시를 참고하여 MAC 기본 요소를 사용해 보세요.
C++
// A command-line utility for showcasing using the Tink MAC primitive. #include <cstdlib> #include <fstream> #include <iostream> #include <memory> #include <ostream> #include <sstream> #include <string> #include <utility> #include "absl/flags/flag.h" #include "absl/flags/parse.h" #include "absl/log/absl_check.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "tink/config/global_registry.h" #include "util/util.h" #include "tink/keyset_handle.h" #include "tink/mac.h" #include "tink/mac/mac_config.h" ABSL_FLAG(std::string, keyset_filename, "", "Keyset file in JSON format"); ABSL_FLAG(std::string, mode, "", "Mode of operation {compute|verify}"); ABSL_FLAG(std::string, data_filename, "", "Data file name"); ABSL_FLAG(std::string, tag_filename, "", "Authentication tag file name"); namespace { using ::crypto::tink::KeysetHandle; using ::crypto::tink::Mac; using ::crypto::tink::MacConfig; constexpr absl::string_view kCompute = "compute"; constexpr absl::string_view kVerify = "verify"; void ValidateParams() { // ... } } // namespace namespace tink_cc_examples { // MAC example CLI implementation. absl::Status MacCli(absl::string_view mode, const std::string keyset_filename, const std::string& data_filename, const std::string& tag_filename) { absl::Status result = MacConfig::Register(); if (!result.ok()) return result; // Read the keyset from file. absl::StatusOr<std::unique_ptr<KeysetHandle>> keyset_handle = ReadJsonCleartextKeyset(keyset_filename); if (!keyset_handle.ok()) return keyset_handle.status(); // Get the primitive. absl::StatusOr<std::unique_ptr<Mac>> mac_primitive = (*keyset_handle) ->GetPrimitive<crypto::tink::Mac>( crypto::tink::ConfigGlobalRegistry()); if (!mac_primitive.ok()) return mac_primitive.status(); // Read the input. absl::StatusOr<std::string> data_file_content = ReadFile(data_filename); if (!data_file_content.ok()) return data_file_content.status(); std::string output; if (mode == kCompute) { // Compute authentication tag. absl::StatusOr<std::string> compute_result = (*mac_primitive)->ComputeMac(*data_file_content); if (!compute_result.ok()) return compute_result.status(); // Write out the authentication tag to tag file. return WriteToFile(*compute_result, tag_filename); } else { // operation == kVerify. // Read the authentication tag from tag file. absl::StatusOr<std::string> tag_result = ReadFile(tag_filename); if (!tag_result.ok()) { std::cerr << tag_result.status().message() << '\n'; exit(1); } // Verify authentication tag. absl::Status verify_result = (*mac_primitive)->VerifyMac(*tag_result, *data_file_content); if (verify_result.ok()) std::clog << "Verification succeeded!" << '\n'; return verify_result; } } } // namespace tink_cc_examples int main(int argc, char** argv) { absl::ParseCommandLine(argc, argv); ValidateParams(); std::string mode = absl::GetFlag(FLAGS_mode); std::string keyset_filename = absl::GetFlag(FLAGS_keyset_filename); std::string data_filename = absl::GetFlag(FLAGS_data_filename); std::string tag_filename = absl::GetFlag(FLAGS_tag_filename); std::clog << "Using keyset from file '" << keyset_filename << "' to " << mode << " authentication tag from file '" << tag_filename << "' for data file '" << data_filename << "'." << '\n'; std::clog << "The tag will be " << ((mode == kCompute) ? "written to" : "read from") << " file '" << tag_filename << "'." << '\n'; ABSL_CHECK_OK(tink_cc_examples::MacCli(mode, keyset_filename, data_filename, tag_filename)); return 0; }
Go
import ( "bytes" "fmt" "log" "github.com/tink-crypto/tink-go/v2/insecurecleartextkeyset" "github.com/tink-crypto/tink-go/v2/keyset" "github.com/tink-crypto/tink-go/v2/mac" ) func Example() { // A keyset created with "tinkey create-keyset --key-template=HMAC_SHA256_128BITTAG". // Note that this keyset has the secret key information in cleartext. jsonKeyset := `{ "key": [{ "keyData": { "keyMaterialType": "SYMMETRIC", "typeUrl": "type.googleapis.com/google.crypto.tink.HmacKey", "value": "EgQIAxAQGiA0LQjovcydWhVQV3k8W9ZSRkd7Ei4Y/TRWApE8guwV4Q==" }, "keyId": 1892702217, "outputPrefixType": "TINK", "status": "ENABLED" }], "primaryKeyId": 1892702217 }` // Create a keyset handle from the cleartext keyset in the previous // step. The keyset handle provides abstract access to the underlying keyset to // limit the exposure of accessing the raw key material. WARNING: In practice, // it is unlikely you will want to use a insecurecleartextkeyset, as it implies // that your key material is passed in cleartext, which is a security risk. // Consider encrypting it with a remote key in Cloud KMS, AWS KMS or HashiCorp Vault. // See https://github.com/google/tink/blob/master/docs/GOLANG-HOWTO.md#storing-and-loading-existing-keysets. keysetHandle, err := insecurecleartextkeyset.Read( keyset.NewJSONReader(bytes.NewBufferString(jsonKeyset))) if err != nil { log.Fatal(err) } // Retrieve the MAC primitive we want to use from the keyset handle. primitive, err := mac.New(keysetHandle) if err != nil { log.Fatal(err) } // Use the primitive to create a MAC tag for some data. In this case the primary // key of the keyset will be used (which is also the only key in this example). data := []byte("data") tag, err := primitive.ComputeMAC(data) if err != nil { log.Fatal(err) } // Use the primitive to verify the tag. VerifyMAC finds the correct key in // the keyset. If no key is found or verification fails, it returns an error. err = primitive.VerifyMAC(tag, data) if err != nil { log.Fatal(err) } fmt.Printf("tag is valid") // Output: tag is valid }
자바
package mac; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.crypto.tink.InsecureSecretKeyAccess; import com.google.crypto.tink.KeysetHandle; import com.google.crypto.tink.Mac; import com.google.crypto.tink.RegistryConfiguration; import com.google.crypto.tink.TinkJsonProtoKeysetFormat; import com.google.crypto.tink.mac.MacConfig; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; /** * A command-line utility for checking file integrity with a Message Authentication Code (MAC). * * <p>It loads cleartext keys from disk - this is not recommended! * * <p>It requires the following arguments: * * <ul> * <li>mode: either 'compute' or 'verify'. * <li>key-file: Read the key material from this file. * <li>input-file: Read the input from this file. * <li>mac-file: name of the file containing a hexadecimal MAC of the input data. */ public final class MacExample { public static void main(String[] args) throws Exception { if (args.length != 4) { System.err.printf("Expected 4 parameters, got %d\n", args.length); System.err.println("Usage: java MacExample compute/verify key-file input-file mac-file"); System.exit(1); } String mode = args[0]; if (!mode.equals("compute") && !mode.equals("verify")) { System.err.println("Incorrect mode. Please select compute or verify."); System.exit(1); } Path keyFile = Paths.get(args[1]); byte[] msg = Files.readAllBytes(Paths.get(args[2])); Path macFile = Paths.get(args[3]); // Register all MAC key types with the Tink runtime. MacConfig.register(); // Read the keyset into a KeysetHandle. KeysetHandle handle = TinkJsonProtoKeysetFormat.parseKeyset( new String(Files.readAllBytes(keyFile), UTF_8), InsecureSecretKeyAccess.get()); // Get the primitive. Mac macPrimitive = handle.getPrimitive(RegistryConfiguration.get(), Mac.class); if (mode.equals("compute")) { byte[] macTag = macPrimitive.computeMac(msg); Files.write(macFile, macTag); } else { byte[] macTag = Files.readAllBytes(macFile); // This will throw a GeneralSecurityException if verification fails. macPrimitive.verifyMac(macTag, msg); } } private MacExample() {} }
Python
import tink from tink import mac from tink import secret_key_access def example(): """Compute and verify MAC tags.""" # Register the MAC key managers. This is needed to create a Mac primitive # later. mac.register() # Created with "tinkey create-keyset --key-template=HMAC_SHA256_128BITTAG". # Note that this keyset has the secret key information in cleartext. keyset = r"""{ "key": [{ "keyData": { "keyMaterialType": "SYMMETRIC", "typeUrl": "type.googleapis.com/google.crypto.tink.HmacKey", "value": "EgQIAxAQGiA0LQjovcydWhVQV3k8W9ZSRkd7Ei4Y/TRWApE8guwV4Q==" }, "keyId": 1892702217, "outputPrefixType": "TINK", "status": "ENABLED" }], "primaryKeyId": 1892702217 }""" # Create a keyset handle from the cleartext keyset in the previous # step. The keyset handle provides abstract access to the underlying keyset to # limit access of the raw key material. WARNING: In practice, it is unlikely # you will want to use tink.json_proto_keyset_format.parse, as it implies that # your key material is passed in cleartext, which is a security risk. keyset_handle = tink.json_proto_keyset_format.parse( keyset, secret_key_access.TOKEN ) # Retrieve the Mac primitive we want to use from the keyset handle. primitive = keyset_handle.primitive(mac.Mac) # Use the primitive to compute the MAC for a message. In this case the primary # key of the keyset will be used (which is also the only key in this example). data = b'data' tag = primitive.compute_mac(data) # Use the primitive to verify the MAC for the message. Verify finds the # correct key in the keyset and verifies the MAC. If no key is found or # verification fails, it raises an error. primitive.verify_mac(tag, data)
메시지 인증 코드 (MAC)
MAC 기본 요소를 사용하면 아무도 데이터를 조작하지 않았음을 확인할 수 있습니다. 수신자와 대칭 키 를 공유하는 발신자는 특정 메시지의 인증 태그 를 계산할 수 있습니다. 이를 통해 수신자는 메시지가 예상된 발신자로부터 왔으며 수정되지 않았음을 확인할 수 있습니다.
MAC에는 다음과 같은 속성이 있습니다.
- 진위성: 키를 아는 것이 확인 가능한 MAC 태그를 만드는 유일한 방법입니다.
- 대칭: 태그를 계산하고 확인하려면 동일한 키가 필요합니다.
MAC은 알고리즘에 따라 결정적 또는 무작위로 지정될 수 있습니다. Tink는 현재 비결정적 MAC 알고리즘을 구현하지 않습니다. MAC 은 메시지 인증에만 사용해야 하며, 의사 난수 바이트 생성과 같은 다른 용도로는 사용하지 않아야 합니다 (자세한 내용은 PRF 참고).
비대칭 기본 요소가 필요한 경우 Digital Signature를 참고하세요.
키 유형 선택
대부분의 용도로는 HMAC_SHA256 을 사용하는 것이 좋지만 다른 옵션도 있습니다.
일반적으로 다음이 적용됩니다.
- HMAC_SHA512는 메시지 크기와 사용하는 하드웨어의 사양에 따라 더 빠를 수도 있고 더 느릴 수도 있습니다.
- HMAC_SHA512는 사실상 무제한의 메시지에 사용할 수 있는 가장 보수적인 모드입니다.
AES256_CMAC은 AES-NI 하드웨어 가속을 지원하는 시스템에서 가장 빠릅니다.
최소 보안 보장
- 최소 80비트 인증 강도
- 선택한 평문 공격에서 실존적 위조에 대한 보안
- 키 복구 공격 및 멀티 사용자 시나리오 (공격자가 특정 키가 아닌 최대 232개의 키 집합에서 키를 타겟팅하는 경우)에서 최소 128비트 보안