|
| 1 | +// Copyright 2026 PingCAP, Inc. |
| 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 | +// See the License for the specific language governing permissions and |
| 12 | +// limitations under the License. |
| 13 | + |
| 14 | +package encryption |
| 15 | + |
| 16 | +import ( |
| 17 | + "encoding/base64" |
| 18 | + "encoding/json" |
| 19 | + "fmt" |
| 20 | +) |
| 21 | + |
| 22 | +// ByteArray supports decoding either: |
| 23 | +// - a JSON string (base64-encoded bytes), or |
| 24 | +// - a JSON array of uint8 values (TiKV status API style). |
| 25 | +type ByteArray []byte |
| 26 | + |
| 27 | +func (b *ByteArray) UnmarshalJSON(data []byte) error { |
| 28 | + if len(data) == 0 || string(data) == "null" { |
| 29 | + *b = nil |
| 30 | + return nil |
| 31 | + } |
| 32 | + |
| 33 | + switch data[0] { |
| 34 | + case '"': |
| 35 | + var s string |
| 36 | + if err := json.Unmarshal(data, &s); err != nil { |
| 37 | + return err |
| 38 | + } |
| 39 | + decoded, err := base64.StdEncoding.DecodeString(s) |
| 40 | + if err != nil { |
| 41 | + return err |
| 42 | + } |
| 43 | + *b = decoded |
| 44 | + return nil |
| 45 | + case '[': |
| 46 | + var ints []int |
| 47 | + if err := json.Unmarshal(data, &ints); err != nil { |
| 48 | + return err |
| 49 | + } |
| 50 | + out := make([]byte, len(ints)) |
| 51 | + for i, v := range ints { |
| 52 | + if v < 0 || v > 255 { |
| 53 | + return fmt.Errorf("byte value out of range: %d", v) |
| 54 | + } |
| 55 | + out[i] = byte(v) |
| 56 | + } |
| 57 | + *b = out |
| 58 | + return nil |
| 59 | + default: |
| 60 | + return fmt.Errorf("unsupported JSON type for bytes: %s", string(data)) |
| 61 | + } |
| 62 | +} |
0 commit comments