|
2 | 2 | //! Agents are actors (such as users) that can edit content. |
3 | 3 | //! https://docs.atomicdata.dev/commits/concepts.html |
4 | 4 |
|
| 5 | +use base64::{engine::general_purpose, Engine}; |
| 6 | + |
5 | 7 | use crate::{errors::AtomicResult, urls, Resource, Storelike, Value}; |
6 | 8 |
|
7 | 9 | #[derive(Clone, Debug)] |
@@ -93,28 +95,39 @@ fn generate_keypair() -> AtomicResult<Pair> { |
93 | 95 | .map_err(|e| format!("Error generating keypair {}", e)) |
94 | 96 | .unwrap(); |
95 | 97 | Ok(Pair { |
96 | | - private: base64::encode(seed), |
97 | | - public: base64::encode(key_pair.public_key()), |
| 98 | + private: encode_base64(&seed), |
| 99 | + public: encode_base64(key_pair.public_key().as_ref()), |
98 | 100 | }) |
99 | 101 | } |
100 | 102 |
|
101 | 103 | /// Returns a Key Pair (including public key) from a private key, base64 encoded. |
102 | 104 | pub fn generate_public_key(private_key: &str) -> Pair { |
103 | 105 | use ring::signature::KeyPair; |
104 | | - let private_key_bytes = base64::decode(private_key).unwrap(); |
| 106 | + let private_key_bytes = decode_base64(private_key).unwrap(); |
105 | 107 | let key_pair = ring::signature::Ed25519KeyPair::from_seed_unchecked(private_key_bytes.as_ref()) |
106 | 108 | .map_err(|_| "Error generating keypair") |
107 | 109 | .unwrap(); |
108 | 110 | Pair { |
109 | | - private: base64::encode(private_key_bytes), |
110 | | - public: base64::encode(key_pair.public_key().as_ref()), |
| 111 | + private: encode_base64(&private_key_bytes), |
| 112 | + public: encode_base64(key_pair.public_key().as_ref()), |
111 | 113 | } |
112 | 114 | } |
113 | 115 |
|
| 116 | +pub fn decode_base64(string: &str) -> AtomicResult<Vec<u8>> { |
| 117 | + let vec = general_purpose::STANDARD |
| 118 | + .decode(string) |
| 119 | + .map_err(|e| format!("Invalid key. Not valid Base64. {}", e))?; |
| 120 | + Ok(vec) |
| 121 | +} |
| 122 | + |
| 123 | +pub fn encode_base64(bytes: &[u8]) -> String { |
| 124 | + general_purpose::STANDARD.encode(bytes) |
| 125 | +} |
| 126 | + |
114 | 127 | /// Checks if the public key is a valid ED25519 base64 key. |
115 | 128 | /// Not perfect - only checks byte length and parses base64. |
116 | 129 | pub fn verify_public_key(public_key: &str) -> AtomicResult<()> { |
117 | | - let pubkey_bin = base64::decode(public_key) |
| 130 | + let pubkey_bin = decode_base64(public_key) |
118 | 131 | .map_err(|e| format!("Invalid public key. Not valid Base64. {}", e))?; |
119 | 132 | if pubkey_bin.len() != 32 { |
120 | 133 | return Err(format!( |
|
0 commit comments