encode.ts 857 B

12345678910111213141516171819202122232425
  1. export function base64Encode(value: string) {
  2. return btoa(value).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "")
  3. }
  4. export function base64Decode(value: string) {
  5. return atob(value.replace(/-/g, "+").replace(/_/g, "/"))
  6. }
  7. export async function hash(content: string, algorithm = "SHA-256"): Promise<string> {
  8. const encoder = new TextEncoder()
  9. const data = encoder.encode(content)
  10. const hashBuffer = await crypto.subtle.digest(algorithm, data)
  11. const hashArray = Array.from(new Uint8Array(hashBuffer))
  12. const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("")
  13. return hashHex
  14. }
  15. export function checksum(content: string): string {
  16. let hash = 0x811c9dc5
  17. for (let i = 0; i < content.length; i++) {
  18. hash ^= content.charCodeAt(i)
  19. hash = Math.imul(hash, 0x01000193)
  20. }
  21. return (hash >>> 0).toString(36)
  22. }