tink_core/keyset/
insecure.rs

1// Copyright 2020 The Tink-Rust Authors
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
17//! Module for test code methods to read or write cleartext keyset material.
18
19use crate::TinkError;
20
21/// Create a [`Handle`](super::Handle) from cleartext key material.
22fn keyset_handle(ks: tink_proto::Keyset) -> Result<super::Handle, TinkError> {
23    super::Handle::from_keyset(ks)
24}
25
26/// Return the key material contained in a [`Handle`](super::Handle).
27pub fn keyset_material(h: &super::Handle) -> tink_proto::Keyset {
28    h.clone_keyset()
29}
30
31/// Create a new instance of [`Handle`](super::Handle) using the given
32/// [`Keyset`](tink_proto::Keyset).
33pub fn new_handle(ks: tink_proto::Keyset) -> Result<super::Handle, TinkError> {
34    if ks.key.is_empty() {
35        Err("insecure: invalid keyset".into())
36    } else {
37        keyset_handle(ks)
38    }
39}
40
41/// Create a [`Handle`](super::Handle) from a cleartext keyset obtained via `r`.
42pub fn read<T>(r: &mut T) -> Result<super::Handle, TinkError>
43where
44    T: super::Reader,
45{
46    let ks = r.read()?;
47    if ks.key.is_empty() {
48        Err("insecure: invalid keyset".into())
49    } else {
50        keyset_handle(ks)
51    }
52}
53
54/// Exports the keyset from `h` to the given writer `w` without encrypting it.
55///
56/// Storing secret key material in an unencrypted fashion is dangerous. If feasible, you should use
57/// [`super::Handle::write()`] instead.
58pub fn write<T>(h: &super::Handle, w: &mut T) -> Result<(), TinkError>
59where
60    T: super::Writer,
61{
62    w.write(&keyset_material(h))
63}