github.com/Schaudge/grailbase@v0.0.0-20240223061707-44c758a471c0/crypto/encryption/iv.go (about) 1 // Copyright 2017 GRAIL, Inc. All rights reserved. 2 // Use of this source code is governed by the Apache-2.0 3 // license that can be found in the LICENSE file. 4 5 package encryption 6 7 import ( 8 "encoding/hex" 9 "fmt" 10 "io" 11 ) 12 13 // IV represents the initialization vector used to encrypt a block. 14 type IV []byte 15 16 // MarshalJSON marshals an IV as a hex encoded string. 17 func (iv IV) MarshalJSON() ([]byte, error) { 18 if len(iv) == 0 { 19 return []byte(`""`), nil 20 } 21 dst := make([]byte, hex.EncodedLen(len(iv))+2) 22 hex.Encode(dst[1:], iv) 23 // need to supply leading/trailing double quotes. 24 dst[0], dst[len(dst)-1] = '"', '"' 25 return dst, nil 26 } 27 28 // UnmarshalJSON unmarshals a hex encoded string into an IV. 29 func (iv *IV) UnmarshalJSON(data []byte) error { 30 // need to strip leading and trailing double quotes 31 if data[0] != '"' || data[len(data)-1] != '"' { 32 return fmt.Errorf("IV is not quoted") 33 } 34 data = data[1 : len(data)-1] 35 *iv = make([]byte, hex.DecodedLen(len(data))) 36 _, err := hex.Decode(*iv, data) 37 return err 38 } 39 40 // SetRandSource sets the source of random numbers be used and is intended for 41 // primarily for testing purposes. 42 func SetRandSource(rd io.Reader) { 43 randomSource = rd 44 }