Skip to content

k.security ​

Security utilities - hashing, HMAC, RSA signing and encryption, symmetric ciphers, Base64, GUID / Snowflake ID, and JWT

Execution ContextPrerequisitesTypical Use
KScript APIs, Page / Layout / View server scriptsJWT requires admin JwtSetting; hashGuid FileIO mode requires existing site fileHashing, 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 ​

js
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 / PropertyDescriptionReturns
md5 / sha1 / sha256 / sha512 / sha256BinaryOne-way hashes (md5 uppercase hex; SHA hex lowercase)string / number[]
hmacMd5 / hmacSha1 / hmacSha256Base64-encoded HMAC message signaturesstring
sha256Sign(privateKey, value)PEM RSA private key SHA256 PKCS#1 v1.5 signaturestring
encrypt / decrypt / aesEncrypt / aesDecryptSymmetric string and AES encryption/decryptionstring
toBase64 / fromBase64 / decodeBase64Base64 conversion for text strings and byte arraysstring / number[]
newGuid / shortGuid / hashGuid / newSnowIdGUID, deterministic hash GUID, and 64-bit Snowflake IDstring / number
hashPassword / verifyPasswordSalted password hashing and verificationstring / boolean
jwt (encode / decode / parsePayload / payload)JWT creation, signature verification, and payload decodingstring / any
rsa (generateKeys / encrypt / decrypt)XML RSA key generation and encryption/decryptionRsaKeys / 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).

ParameterTypeRequiredDescription
inputstringYesInput string to hash

Returns: string, 32-character uppercase hex MD5 hash.

js
k.api.get(() => {
  return { hash: k.security.md5("hello") }
})
// Returns: { "hash": "5D41402ABC4B2A76B9719D911017C592" }

sha1() ​

Compute the SHA1 digest of a string (40-character lowercase hexadecimal).

ParameterTypeRequiredDescription
inputstringYesInput string to hash

Returns: string, 40-character lowercase hex SHA1 hash.

js
k.api.get(() => {
  return { hash: k.security.sha1("hello") }
})
// Returns: { "hash": "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d" }

sha256() ​

Compute the SHA256 digest of a string (64-character lowercase hexadecimal).

ParameterTypeRequiredDescription
inputstringYesInput string to hash

Returns: string, 64-character lowercase hex SHA256 hash.

js
k.api.get(() => {
  return { hash: k.security.sha256("hello") }
})
// Returns: { "hash": "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824" }

sha512() ​

Compute the SHA512 digest of a string (128-character lowercase hexadecimal).

ParameterTypeRequiredDescription
inputstringYesInput string to hash

Returns: string, 128-character lowercase hex SHA512 hash.

js
k.api.get(() => {
  return { hash: k.security.sha512("hello") }
})

sha256Binary() ​

Compute the SHA256 digest of a string and return the raw bytes.

ParameterTypeRequiredDescription
inputstringYesInput string to hash

Returns: number[], 32-byte SHA256 digest (usable directly with k.file.writeBinary or k.response.binary).

js
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.

ParameterTypeRequiredDescription
inputstring | number[]YesString or byte array to encode

Returns: string, Base64-encoded string.

js
k.api.get(() => {
  return { encoded: k.security.toBase64("hello") }
})
// Returns: { "encoded": "aGVsbG8=" }

fromBase64() ​

Decode a Base64 string into a plain text string.

ParameterTypeRequiredDescription
base64stringstringYesBase64 string

Returns: string, decoded text.

js
k.api.get(() => {
  return { decoded: k.security.fromBase64("aGVsbG8=") }
})
// Returns: { "decoded": "hello" }

decodeBase64() ​

Decode a Base64 string into a byte array.

ParameterTypeRequiredDescription
inputstringYesBase64 string

Returns: number[], decoded byte array.

js
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.

js
k.api.get(() => {
  return { guid: k.security.newGuid() }
})

shortGuid() ​

Generate a URL-safe short GUID string.

Parameters: None.

Returns: string, short GUID string.

js
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.

ParameterTypeRequiredDescription
inputstringYesSource string, or relative site file path when using { source: "FileIo" }
optionsHashGuidOptionsNo{ 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).

js
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.

js
k.api.get(() => {
  const id = k.security.newSnowId()
  return { id }
})

Password Hashing ​

hashPassword() ​

Hash a password using Kooboo's salted hashing algorithm.

ParameterTypeRequiredDescription
passwordstringYesPlaintext password

Returns: string, salted password hash.

js
k.api.get(() => {
  return { hashed: k.security.hashPassword("mypassword") }
})

verifyPassword() ​

Verify a plaintext password against a stored salted hash.

ParameterTypeRequiredDescription
passwordstringYesPlaintext password to check
saltdpasswordstringYesSalted hash generated by hashPassword()

Returns: boolean.

js
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.

ParameterTypeRequiredDescription
claimsRecord<string, any>YesClaims payload object

Returns: string, signed JWT string.

js
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.

ParameterTypeRequiredDescription
tokenstringNoJWT 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 400 in API routes); wrap calls in try / catch
js
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.

ParameterTypeRequiredDescription
tokenstringYesJWT token string

Returns: string, parse with JSON.parse().

js
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.

MethodParametersReturnsDescription
encrypt(input, key)input: string, key: stringstringEncrypt text
decrypt(input, key)input: string, key: stringstringDecrypt text
js
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.

MethodParametersReturnsDescription
aesEncrypt(input, key)input: string, key: stringstringAES-encrypt text
aesDecrypt(input, key)input: string, key: stringstringAES-decrypt text
js
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.

ParameterTypeRequiredDescription
inputstringYesContent to sign
keystringYesSecret key

Returns: string, Base64 HMAC-MD5 signature.

js
k.api.get(() => {
  return { hmac: k.security.hmacMd5("hello", "key") }
})

hmacSha1() ​

Compute a Base64-encoded HMAC-SHA1 signature.

ParameterTypeRequiredDescription
inputstringYesContent to sign
keystringYesSecret key

Returns: string, Base64 HMAC-SHA1 signature.

js
k.api.get(() => {
  return { hmac: k.security.hmacSha1("hello", "key") }
})

hmacSha256() ​

Compute a Base64-encoded HMAC-SHA256 signature.

ParameterTypeRequiredDescription
inputstringYesContent to sign
keystringYesSecret key

Returns: string, Base64 HMAC-SHA256 signature.

js
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.

ParameterTypeRequiredDescription
privateKeystringYesPEM private key string (-----BEGIN PRIVATE KEY-----)
valuestringYesPayload string to sign

Returns: string, Base64 signature string.

js
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.

ParameterTypeRequiredDescription
sizenumberYesRSA key bit length, such as 2048 (defaults to 512 when <= 0)

Returns: RsaKeys.

js
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.

MethodParametersReturnsDescription
rsa.encrypt(publickey, content)publickey: string, content: stringstringEncrypt using public key
rsa.decrypt(privatekey, content)privatekey: string, content: stringstringDecrypt using private key
js
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
ts
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;
}