Crates.io | cryptid-rs |
lib.rs | cryptid-rs |
version | 0.1.1 |
source | src |
created_at | 2024-06-11 21:06:47.570645 |
updated_at | 2024-07-11 14:32:40.53514 |
description | A library to encrypt and decrypt integer IDs to URL safe strings |
homepage | |
repository | https://github.com/laurikari/cryptid-rs |
max_upload_size | |
id | 1268910 |
size | 30,790 |
Cryptid-rs is a library for securely encoding and decoding integers, such as database primary keys, into strings and back. The encoded string format is inspired by Stripe's APIs.
For example, a user ID of 123
might be encoded into user_hHLBCl4rZ3u
.
Some of these benefits may also be disadvantages depending on your needs. Consider carefully if this library is the right choice for you compared to other solutions, such as using UUIDs as your database keys.
Use the generic Field
type to define a type for each kind of object you are
exposing in your public APIs. The Field
type supports automatic encoding and
decoding with Diesel and Serde.
use cryptid_rs_rs;
use serde::{Serialize, Deserialize};
use serde_json;
// Define the ExampleId cryptid field type. The type marker defines the string prefix.
#[derive(Debug)]
pub struct ExampleIdMarker;
impl cryptid_rs::TypeMarker for ExampleIdMarker {
fn name() -> &'static str { "example" }
}
type ExampleId = cryptid_rs::Field<ExampleIdMarker>;
// The field can then be used in structs, and works automatically with Serde and Diesel.
#[derive(serde::Serialize)]
struct Example {
pub id: ExampleId,
}
cryptid_rs::Config::set_global(cryptid_rs::Config::new(b"your-secure-key"));
let obj = Example {id: ExampleId::new(12345)};
let obj_str = serde_json::to_string(&obj).unwrap();
assert_eq!(obj_str, "{\"id\":\"example_VgwPy6rwatl\"}");
The encryption uses format-preserving encryption (FPE) with AES (FF1 with AES256) and HMAC (SHA256) for integrity checks.
The HMAC is truncated to 4 bytes by default, which is large enough to make guessing impractical through a rate-limited API but still keeps the strings relatively short. For high-security applications, consider using a longer HMAC.