Sample code for 30+ languages & platforms
Rust

Create JCEKS Containing Secret Keys

See more Java KeyStore (JKS) Examples

Demonstrates how to create a JCEKS keystore file containing symmetric secret keys (for AES, Blowfish, HMAC SHA25, ChaCha20, etc.)

This example requires Chilkat v9.5.0.66 or greater.

Chilkat Rust Downloads

Rust

// IMPORTANT: This example requires Chilkat v9.5.0.66 or greater.

// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

let jceks = chilkat::JavaKeyStore::new();

// We'll need a pseudo-random number generator (PRNG) to generate symmetric keys.
let prng = chilkat::Prng::new();

// Generate some keys..

// 128-bit AES key (16 bytes)
let aes_key = prng.gen_random(16, "base64").unwrap_or_default();

// 256-bit Blowfish key (32 bytes)
let blowfish_key = prng.gen_random(32, "base64").unwrap_or_default();

// HMAC SHA256 key
// (An HMAC key can be anything, and any length. We'll use the following string:
let hmac_key = "This is my HMAC key".to_string();

// ChaCha20 256-bit
let chacha_key = prng.gen_random(32, "base64").unwrap_or_default();

// Add each secret key to the JCEKS
let encoding = "base64".to_string();
let password = "secret".to_string();
let _ = jceks.add_secret_key(&aes_key, &encoding, "AES", "my aes key", &password);
let _ = jceks.add_secret_key(&blowfish_key, &encoding, "BLOWFISH", "my blowfish key", &password);
// For HMAC, we're using the us-ascii bytes for the key..
let _ = jceks.add_secret_key(&hmac_key, "ascii", "HMAC_SHA256", "my hmac key", &password);
let _ = jceks.add_secret_key(&chacha_key, &encoding, "CHACHA", "my chacha20 key", &password);

let file_password = "password".to_string();
// Write the JCEKs to a file.
if jceks.to_file(&file_password, "qa_output/secretKeys.jceks").is_err() {
    println!("{}", jceks.last_error_text());
    return;
}

// We can also emit as a JWK Set..
let sb_json = chilkat::StringBuilder::new();
if jceks.to_jwk_set("secret", &sb_json).is_err() {
    println!("{}", jceks.last_error_text());
    return;
}

// Emit the JSON in pretty-printed (indented) form:
let json = chilkat::JsonObject::new();
let _ = json.load_sb(&sb_json);
json.set_emit_compact(false);
println!("{}", json.emit().unwrap_or_default());

// Output is:

// { 
//   "keys": [
//     { 
//       "kty": "oct",
//       "alg": "AES",
//       "k": "vHekQQB0Gc1NvppapUTW2g",
//       "kid": "my aes key"
//     },
//     { 
//       "kty": "oct",
//       "alg": "BLOWFISH",
//       "k": "qHsdXaJsXicVCZbK8l8hJQpYOa0GkiO9gsRK9WLtht8",
//       "kid": "my blowfish key"
//     },
//     { 
//       "kty": "oct",
//       "alg": "HMAC_SHA256",
//       "k": "VGhpcyBpcyBteSBITUFDIGtleQ",
//       "kid": "my hmac key"
//     },
//     { 
//       "kty": "oct",
//       "alg": "CHACHA",
//       "k": "yNv832U43C9BcWvaQAH2_rG-GwfmpgT5JBRllWGQY1o",
//       "kid": "my chacha20 key"
//     }
//   ]
// }
//