Tcl
Tcl
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 Tcl Downloads
load ./chilkat.dll
set success 0
# 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.
set jceks [new_CkJavaKeyStore]
# We'll need a pseudo-random number generator (PRNG) to generate symmetric keys.
set prng [new_CkPrng]
# Generate some keys..
# 128-bit AES key (16 bytes)
set aesKey [CkPrng_genRandom $prng 16 "base64"]
# 256-bit Blowfish key (32 bytes)
set blowfishKey [CkPrng_genRandom $prng 32 "base64"]
# HMAC SHA256 key
# (An HMAC key can be anything, and any length. We'll use the following string:
set hmacKey "This is my HMAC key"
# ChaCha20 256-bit
set chachaKey [CkPrng_genRandom $prng 32 "base64"]
# Add each secret key to the JCEKS
set encoding "base64"
set password "secret"
CkJavaKeyStore_AddSecretKey $jceks $aesKey $encoding "AES" "my aes key" $password
CkJavaKeyStore_AddSecretKey $jceks $blowfishKey $encoding "BLOWFISH" "my blowfish key" $password
# For HMAC, we're using the us-ascii bytes for the key..
CkJavaKeyStore_AddSecretKey $jceks $hmacKey "ascii" "HMAC_SHA256" "my hmac key" $password
CkJavaKeyStore_AddSecretKey $jceks $chachaKey $encoding "CHACHA" "my chacha20 key" $password
set filePassword "password"
# Write the JCEKs to a file.
set success [CkJavaKeyStore_ToFile $jceks $filePassword "qa_output/secretKeys.jceks"]
if {$success != 1} then {
puts [CkJavaKeyStore_lastErrorText $jceks]
delete_CkJavaKeyStore $jceks
delete_CkPrng $prng
exit
}
# We can also emit as a JWK Set..
set sbJson [new_CkStringBuilder]
set success [CkJavaKeyStore_ToJwkSet $jceks "secret" $sbJson]
if {$success != 1} then {
puts [CkJavaKeyStore_lastErrorText $jceks]
delete_CkJavaKeyStore $jceks
delete_CkPrng $prng
delete_CkStringBuilder $sbJson
exit
}
# Emit the JSON in pretty-printed (indented) form:
set json [new_CkJsonObject]
CkJsonObject_LoadSb $json $sbJson
CkJsonObject_put_EmitCompact $json 0
puts [CkJsonObject_emit $json]
# 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"
# }
# ]
# }
#
delete_CkJavaKeyStore $jceks
delete_CkPrng $prng
delete_CkStringBuilder $sbJson
delete_CkJsonObject $json