Crypto

cryptography- or encoding-related functions


Functions


Crypto

The Crypto module provides basic cryptographic functions and encoding utilities. It includes support for hashing, CRC calculation, and various encoding/decoding operations.

Key Concepts

  • Hash calculation (MD5, SHA1)
  • CRC32 polynomial calculation
  • Base64 encoding/decoding
  • URL encoding/decoding
  • Character encoding conversion

Basic Usage

Hashing

; calculate MD5 digest (default)
print digest "hello world"          ; 5eb63bbbe01eeed093cb22bb8f5acdc3

; using SHA1
print digest.sha "hello world"      ; 2aae6c35c94fcfb415dbe95f408b9ce91ee846ed

; CRC32 calculation
print crc "hello world"             ; 0d4a1185

Important
The Crypto module provides basic cryptographic functions. For serious cryptographic needs, consider using specialized libraries.

Base64 Encoding/Decoding

; encoding
encoded: encode "Hello World!"      ; SGVsbG8gV29ybGQh
print encoded

; decoding
decoded: decode encoded             ; Hello World!
print decoded

URL Encoding/Decoding

; encode URL
url: "https://example.com/path with spaces?q=test+1"
encoded: encode.url url
print encoded       
; https%3A%2F%2Fexample.com%2Fpath%20with%20spaces%3Fq%3Dtest%2B1

; decode URL
decoded: decode.url encoded
print decoded       
; https://example.com/path with spaces?q=test+1

; encode only spaces
spaceEncoded: encode.url.spaces "hello world"  
; hello%20world

; encode everything including slashes
fullEncoded: encode.url.slashes "/path/to/resource"
; %2Fpath%2Fto%2Fresource

Character Encoding Conversion

; convert between character encodings
text: "Hello världen"           ; text with non-ASCII characters
converted: encode .from:"UTF-8" .to: "ISO-8859-1" text

Common Patterns

Password Hashing

hashPassword: function [password][
    ; combine password with... salt and hash
    salt: "somesalt"
    combined: join @[password salt]
    digest.sha combined
]

; usage
password: "mypassword123"
hashed: hashPassword password

print ["Hashed password:" hashed]
; Hashed password: 81ea5410f1cb78c81cbb6dbd678782f80f9150f5 

Safe URL Building

buildUrl: function [baseUrl parameters][
    query: map parameters [key value][
        key ++ "=" ++ encode.url value
    ]
    
    join.with:"?" @[
        baseUrl
        join.with:"&" query
    ]
]

; usage
url: buildUrl "https://api.example.com/search" #[
    "q": "search term"
    "lang": "en-US"
    "page": "1"
]

print url
; https://api.example.com/search?q=search%20term&lang=en-US&page=1

Tip
When working with URLs, always encode user inputs to prevent injection attacks and ensure proper URL formatting.