k.security
Security utilities - hashing, HMAC, RSA signing and encryption, symmetric ciphers, Base64, GUID / Snowflake ID, and JWT
| Execution Context | Prerequisites | Typical Use |
|---|---|---|
| KScript APIs, Page / Layout / View server scripts | JWT requires admin JwtSetting; hashGuid FileIO mode requires existing site file | Hashing, HMAC/PEM signing, password verification, encryption, IDs, and JWT tokens |
k.security provides cryptographic and security helpers including one-way hashes, HMAC signatures, RSA-SHA256 PEM signing, symmetric encryption, Base64 conversion, GUID and Snowflake ID generation, password hashing, and JWT encoding/verification.
Quick Start
k.api.get(() => {
const hash = k.security.sha256("hello")
const id = k.security.newSnowId()
const hashedPwd = k.security.hashPassword("secret123")
return {
hash,
id,
passwordOk: k.security.verifyPassword("secret123", hashedPwd)
}
})Quick Reference
| Method / Property | Description | Returns |
|---|---|---|
md5 / sha1 / sha256 / sha512 / sha256Binary | One-way hashes (md5 uppercase hex; SHA hex lowercase) | string / number[] |
hmacMd5 / hmacSha1 / hmacSha256 | Base64-encoded HMAC message signatures | string |
sha256Sign(privateKey, value) | PEM RSA private key SHA256 PKCS#1 v1.5 signature | string |
encrypt / decrypt / aesEncrypt / aesDecrypt | Symmetric string and AES encryption/decryption | string |
toBase64 / fromBase64 / decodeBase64 | Base64 conversion for text strings and byte arrays | string / number[] |
newGuid / shortGuid / hashGuid / newSnowId | GUID, deterministic hash GUID, and 64-bit Snowflake ID | string / number |
hashPassword / verifyPassword | Salted password hashing and verification | string / boolean |
jwt (encode / decode / parsePayload / payload) | JWT creation, signature verification, and payload decoding | string / any |
rsa (generateKeys / encrypt / decrypt) | XML RSA key generation and encryption/decryption | RsaKeys / string |
Hash Algorithms
md5()
Compute the MD5 digest of a string (32-character uppercase hexadecimal). Note that md5() encodes the input as ASCII (Encoding.ASCII), so non-ASCII characters (such as Chinese text or emoji) are replaced with ? (0x3F) before hashing and produce a different digest than standard UTF-8 MD5 (unlike the UTF-8-based SHA methods).
| Parameter | Type | Required | Description |
|---|---|---|---|
input | string | Yes | Input string to hash |
Returns: string, 32-character uppercase hex MD5 hash.
k.api.get(() => {
return { hash: k.security.md5("hello") }
})
// Returns: { "hash": "5D41402ABC4B2A76B9719D911017C592" }sha1()
Compute the SHA1 digest of a string (40-character lowercase hexadecimal).
| Parameter | Type | Required | Description |
|---|---|---|---|
input | string | Yes | Input string to hash |
Returns: string, 40-character lowercase hex SHA1 hash.
k.api.get(() => {
return { hash: k.security.sha1("hello") }
})
// Returns: { "hash": "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d" }sha256()
Compute the SHA256 digest of a string (64-character lowercase hexadecimal).
| Parameter | Type | Required | Description |
|---|---|---|---|
input | string | Yes | Input string to hash |
Returns: string, 64-character lowercase hex SHA256 hash.
k.api.get(() => {
return { hash: k.security.sha256("hello") }
})
// Returns: { "hash": "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824" }sha512()
Compute the SHA512 digest of a string (128-character lowercase hexadecimal).
| Parameter | Type | Required | Description |
|---|---|---|---|
input | string | Yes | Input string to hash |
Returns: string, 128-character lowercase hex SHA512 hash.
k.api.get(() => {
return { hash: k.security.sha512("hello") }
})sha256Binary()
Compute the SHA256 digest of a string and return the raw bytes.
| Parameter | Type | Required | Description |
|---|---|---|---|
input | string | Yes | Input string to hash |
Returns: number[], 32-byte SHA256 digest (usable directly with k.file.writeBinary or k.response.binary).
k.api.get(() => {
const bytes = k.security.sha256Binary("hello")
return { length: bytes.length, base64: k.security.toBase64(bytes) }
})Base64 Encoding & Decoding
toBase64()
Encode a UTF-8 string or byte array into Base64.
| Parameter | Type | Required | Description |
|---|---|---|---|
input | string | number[] | Yes | String or byte array to encode |
Returns: string, Base64-encoded string.
k.api.get(() => {
return { encoded: k.security.toBase64("hello") }
})
// Returns: { "encoded": "aGVsbG8=" }fromBase64()
Decode a Base64 string into a plain text string.
| Parameter | Type | Required | Description |
|---|---|---|---|
base64string | string | Yes | Base64 string |
Returns: string, decoded text.
k.api.get(() => {
return { decoded: k.security.fromBase64("aGVsbG8=") }
})
// Returns: { "decoded": "hello" }decodeBase64()
Decode a Base64 string into a byte array.
| Parameter | Type | Required | Description |
|---|---|---|---|
input | string | Yes | Base64 string |
Returns: number[], decoded byte array.
k.api.get(() => {
return { bytes: k.security.decodeBase64("aGVsbG8=") }
})
// Returns: { "bytes": [104, 101, 108, 108, 111] }GUID & IDs
newGuid()
Generate a new GUID string.
Parameters: None.
Returns: string, 32-character lowercase hex GUID.
k.api.get(() => {
return { guid: k.security.newGuid() }
})shortGuid()
Generate a URL-safe short GUID string.
Parameters: None.
Returns: string, short GUID string.
k.api.get(() => {
return { guid: k.security.shortGuid() }
})hashGuid()
Compute a deterministic 32-character hex GUID string from input text or a site FileIO file. When { source: "FileIo" } is specified, the target file must exist in FileIO or a file-not-found error is thrown.
| Parameter | Type | Required | Description |
|---|---|---|---|
input | string | Yes | Source string, or relative site file path when using { source: "FileIo" } |
options | HashGuidOptions | No | { source?: string }; set { source: "FileIo" } to hash a FileIO file |
Returns: string, 32-character hex digest string (empty text input still hashes to a deterministic 32-character hex string; "" is only returned in { source: "FileIo" } mode when the file path cannot be resolved).
k.api.get(() => {
return { hash: k.security.hashGuid("hello") }
})newSnowId()
Generate a monotonically increasing 64-bit Snowflake ID.
Parameters: None.
Returns: number, numeric Snowflake ID.
k.api.get(() => {
const id = k.security.newSnowId()
return { id }
})Password Hashing
hashPassword()
Hash a password using Kooboo's salted hashing algorithm.
| Parameter | Type | Required | Description |
|---|---|---|---|
password | string | Yes | Plaintext password |
Returns: string, salted password hash.
k.api.get(() => {
return { hashed: k.security.hashPassword("mypassword") }
})verifyPassword()
Verify a plaintext password against a stored salted hash.
| Parameter | Type | Required | Description |
|---|---|---|---|
password | string | Yes | Plaintext password to check |
saltdpassword | string | Yes | Salted hash generated by hashPassword() |
Returns: boolean.
k.api.get(() => {
const hashed = k.security.hashPassword("mypassword")
return { valid: k.security.verifyPassword("mypassword", hashed) }
})JWT
Prerequisite
Configure JWT settings in the admin before using JWT APIs: Site Settings → Service Integration → Others → JwtSetting.
jwt.encode()
Generate a signed JWT token.
| Parameter | Type | Required | Description |
|---|---|---|---|
claims | Record<string, any> | Yes | Claims payload object |
Returns: string, signed JWT string.
k.api.get(() => {
return { token: k.security.jwt.encode({ name: "user" }) }
})jwt.decode()
Verify and decode a JWT token. When called with no argument, it reads Authorization: Bearer ... from the request headers first and falls back to the jwt_access_token cookie when the header is absent.
| Parameter | Type | Required | Description |
|---|---|---|---|
token | string | No | JWT token; reads from the Authorization header first and falls back to the jwt_access_token cookie when omitted |
Returns: string, a JSON string that must be parsed with JSON.parse():
- Success:
{"code":0,"value":{...}} - Invalid signature or expired token:
{"code":1,"value":"error message"} - Malformed token without three dot-delimited segments throws a parameter exception (HTTP
400in API routes); wrap calls intry / catch
k.api.get(() => {
const token = k.security.jwt.encode({ name: "user" })
try {
const result = JSON.parse(k.security.jwt.decode(token))
if (result.code === 0) {
return { success: true, data: result.value }
}
return { success: false, error: result.value }
} catch (e) {
return { success: false, error: String(e) }
}
})jwt.parsePayload()
Decode a JWT payload without verifying its signature, returning a JSON string in the same {"code":0,"value":{...}} envelope.
| Parameter | Type | Required | Description |
|---|---|---|---|
token | string | Yes | JWT token string |
Returns: string, parse with JSON.parse().
k.api.get(() => {
const token = k.security.jwt.encode({ name: "user" })
const parsed = JSON.parse(k.security.jwt.parsePayload(token))
return parsed
})jwt.payload
Read the decoded JWT payload populated on the request context by JWT verification middleware (null when no JWT verification pipeline injected it).
Type: any.
Symmetric Encryption
encrypt() / decrypt()
Encrypt and decrypt strings using symmetric encryption.
| Method | Parameters | Returns | Description |
|---|---|---|---|
encrypt(input, key) | input: string, key: string | string | Encrypt text |
decrypt(input, key) | input: string, key: string | string | Decrypt text |
k.api.get(() => {
const encrypted = k.security.encrypt("hello", "mykey")
const decrypted = k.security.decrypt(encrypted, "mykey")
return { encrypted, decrypted }
})aesEncrypt() / aesDecrypt()
Encrypt and decrypt strings using AES.
| Method | Parameters | Returns | Description |
|---|---|---|---|
aesEncrypt(input, key) | input: string, key: string | string | AES-encrypt text |
aesDecrypt(input, key) | input: string, key: string | string | AES-decrypt text |
k.api.get(() => {
const encrypted = k.security.aesEncrypt("hello", "hashkey")
const decrypted = k.security.aesDecrypt(encrypted, "hashkey")
return { encrypted, decrypted }
})HMAC & Signing
hmacMd5()
Compute a Base64-encoded HMAC-MD5 signature.
| Parameter | Type | Required | Description |
|---|---|---|---|
input | string | Yes | Content to sign |
key | string | Yes | Secret key |
Returns: string, Base64 HMAC-MD5 signature.
k.api.get(() => {
return { hmac: k.security.hmacMd5("hello", "key") }
})hmacSha1()
Compute a Base64-encoded HMAC-SHA1 signature.
| Parameter | Type | Required | Description |
|---|---|---|---|
input | string | Yes | Content to sign |
key | string | Yes | Secret key |
Returns: string, Base64 HMAC-SHA1 signature.
k.api.get(() => {
return { hmac: k.security.hmacSha1("hello", "key") }
})hmacSha256()
Compute a Base64-encoded HMAC-SHA256 signature.
| Parameter | Type | Required | Description |
|---|---|---|---|
input | string | Yes | Content to sign |
key | string | Yes | Secret key |
Returns: string, Base64 HMAC-SHA256 signature.
k.api.get(() => {
return { hmac: k.security.hmacSha256("hello", "key") }
})sha256Sign()
Sign an ASCII payload using a PEM-formatted RSA private key (SHA-256 + PKCS#1 v1.5) and return a Base64 signature.
| Parameter | Type | Required | Description |
|---|---|---|---|
privateKey | string | Yes | PEM private key string (-----BEGIN PRIVATE KEY-----) |
value | string | Yes | Payload string to sign |
Returns: string, Base64 signature string.
k.api.post(() => {
const { pem, payload } = JSON.parse(k.request.body || "{}")
const signature = k.security.sha256Sign(pem, payload)
return { signature }
})RSA
rsa.generateKeys()
Generate an XML-formatted RSA key pair (<RSAKeyValue>...</RSAKeyValue>). Read keys.publicKey and keys.privateKey in scripts; when returned directly as JSON, keys serialize as PublicKey and PrivateKey.
| Parameter | Type | Required | Description |
|---|---|---|---|
size | number | Yes | RSA key bit length, such as 2048 (defaults to 512 when <= 0) |
Returns: RsaKeys.
k.api.get(() => {
return k.security.rsa.generateKeys(2048)
})rsa.encrypt() / rsa.decrypt()
Encrypt with an XML RSA public key and decrypt with the matching XML RSA private key.
| Method | Parameters | Returns | Description |
|---|---|---|---|
rsa.encrypt(publickey, content) | publickey: string, content: string | string | Encrypt using public key |
rsa.decrypt(privatekey, content) | privatekey: string, content: string | string | Decrypt using private key |
k.api.get(() => {
const keys = k.security.rsa.generateKeys(2048)
const encrypted = k.security.rsa.encrypt(keys.publicKey, "message")
const decrypted = k.security.rsa.decrypt(keys.privateKey, encrypted)
return { encrypted, decrypted }
})TypeScript Definitions
Show full TypeScript definitions
interface Security {
// Hashing
md5(input: string): string;
sha1(input: string): string;
sha256(input: string): string;
sha512(input: string): string;
sha256Binary(input: string): number[];
// HMAC & asymmetric signing
hmacMd5(input: string, key: string): string;
hmacSha1(input: string, key: string): string;
hmacSha256(input: string, key: string): string;
sha256Sign(privateKey: string, value: string): string;
// Symmetric encryption
encrypt(input: string, key: string): string;
decrypt(input: string, key: string): string;
aesEncrypt(input: string, key: string): string;
aesDecrypt(input: string, key: string): string;
// Base64 encoding/decoding
toBase64(input: string): string;
toBase64(input: number[]): string;
fromBase64(base64string: string): string;
decodeBase64(input: string): number[];
// GUID & IDs
newGuid(): string;
shortGuid(): string;
hashGuid(input: string, options?: HashGuidOptions): string;
newSnowId(): number;
// Passwords
hashPassword(password: string): string;
verifyPassword(password: string, saltdpassword: string): boolean;
// JWT
jwt: kJwt;
// RSA
rsa: RSAEncryption;
}
interface HashGuidOptions {
source?: string;
}
interface kJwt {
payload: any;
encode(claims: Record<string, any>): string;
decode(): string;
decode(token: string): string;
parsePayload(token: string): string;
}
interface RSAEncryption {
generateKeys(size: number): RsaKeys;
encrypt(publickey: string, content: string): string;
decrypt(privatekey: string, content: string): string;
}
interface RsaKeys {
publicKey: string;
privateKey: string;
}Related Docs
- k.request — HTTP request information
- k.response — HTTP response handling
- k.cookie — Cookie management