1// Copyright 2019 Google LLC 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14// 15//////////////////////////////////////////////////////////////////////////////// 16 17package mac_test 18 19// [START mac-example] 20 21import ( 22 "bytes" 23 "fmt" 24 "log" 25 26 "github.com/google/tink/go/insecurecleartextkeyset" 27 "github.com/google/tink/go/keyset" 28 "github.com/google/tink/go/mac" 29) 30 31func Example() { 32 // A keyset created with "tinkey create-keyset --key-template=HMAC_SHA256_128BITTAG". 33 // Note that this keyset has the secret key information in cleartext. 34 jsonKeyset := `{ 35 "key": [{ 36 "keyData": { 37 "keyMaterialType": 38 "SYMMETRIC", 39 "typeUrl": 40 "type.googleapis.com/google.crypto.tink.HmacKey", 41 "value": 42 "EgQIAxAQGiA0LQjovcydWhVQV3k8W9ZSRkd7Ei4Y/TRWApE8guwV4Q==" 43 }, 44 "keyId": 1892702217, 45 "outputPrefixType": "TINK", 46 "status": "ENABLED" 47 }], 48 "primaryKeyId": 1892702217 49 }` 50 51 // Create a keyset handle from the cleartext keyset in the previous 52 // step. The keyset handle provides abstract access to the underlying keyset to 53 // limit the exposure of accessing the raw key material. WARNING: In practice, 54 // it is unlikely you will want to use a insecurecleartextkeyset, as it implies 55 // that your key material is passed in cleartext, which is a security risk. 56 // Consider encrypting it with a remote key in Cloud KMS, AWS KMS or HashiCorp Vault. 57 // See https://github.com/google/tink/blob/master/docs/GOLANG-HOWTO.md#storing-and-loading-existing-keysets. 58 keysetHandle, err := insecurecleartextkeyset.Read( 59 keyset.NewJSONReader(bytes.NewBufferString(jsonKeyset))) 60 if err != nil { 61 log.Fatal(err) 62 } 63 64 // Retrieve the MAC primitive we want to use from the keyset handle. 65 primitive, err := mac.New(keysetHandle) 66 if err != nil { 67 log.Fatal(err) 68 } 69 70 // Use the primitive to create a MAC tag for some data. In this case the primary 71 // key of the keyset will be used (which is also the only key in this example). 72 data := []byte("data") 73 tag, err := primitive.ComputeMAC(data) 74 if err != nil { 75 log.Fatal(err) 76 } 77 78 // Use the primitive to verify the tag. VerifyMAC finds the correct key in 79 // the keyset. If no key is found or verification fails, it returns an error. 80 err = primitive.VerifyMAC(tag, data) 81 if err != nil { 82 log.Fatal(err) 83 } 84 fmt.Printf("tag is valid") 85 // Output: tag is valid 86} 87 88// [END mac-example] 89