or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

asymmetric-cryptography.mdcrypto-interface.mdhash-functions.mdindex.mdkey-derivation.mdmodern-cryptography.mdsymmetric-encryption.md

hash-functions.mddocs/

0

# Hash Functions

1

2

Cryptographic hash functions for data integrity, digital signatures, and key derivation. Supports SHA family, SHA-3, and SHAKE extendable-output functions.

3

4

## Capabilities

5

6

### SHA Family Hash Functions

7

8

Standard SHA (Secure Hash Algorithm) functions widely used in cryptographic applications.

9

10

```typescript { .api }

11

/**

12

* SHA hash algorithms

13

*/

14

type ShaAlgorithm = "SHA-1" | "SHA-256" | "SHA-384" | "SHA-512";

15

```

16

17

**Usage Example:**

18

19

```typescript

20

// Compute SHA-256 hash

21

const data = new TextEncoder().encode("Data to hash");

22

const hashBuffer = await crypto.subtle.digest("SHA-256", data);

23

const hashArray = Array.from(new Uint8Array(hashBuffer));

24

const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');

25

26

console.log("SHA-256:", hashHex);

27

```

28

29

### SHA-1

30

31

```typescript { .api }

32

/**

33

* SHA-1 hash function (deprecated for security-critical applications)

34

*/

35

interface Sha1Algorithm extends Algorithm {

36

name: "SHA-1";

37

}

38

```

39

40

### SHA-256

41

42

```typescript { .api }

43

/**

44

* SHA-256 hash function (256-bit output)

45

*/

46

interface Sha256Algorithm extends Algorithm {

47

name: "SHA-256";

48

}

49

```

50

51

### SHA-384

52

53

```typescript { .api }

54

/**

55

* SHA-384 hash function (384-bit output)

56

*/

57

interface Sha384Algorithm extends Algorithm {

58

name: "SHA-384";

59

}

60

```

61

62

### SHA-512

63

64

```typescript { .api }

65

/**

66

* SHA-512 hash function (512-bit output)

67

*/

68

interface Sha512Algorithm extends Algorithm {

69

name: "SHA-512";

70

}

71

```

72

73

### SHA-3 Family (Conditional Support)

74

75

SHA-3 hash functions based on Keccak algorithm (availability depends on Node.js crypto support).

76

77

```typescript { .api }

78

/**

79

* SHA-3 hash algorithms (platform-dependent)

80

*/

81

type Sha3Algorithm = "SHA3-256" | "SHA3-384" | "SHA3-512";

82

83

interface Sha3Params extends Algorithm {

84

name: "SHA3-256" | "SHA3-384" | "SHA3-512";

85

}

86

```

87

88

**Usage Example:**

89

90

```typescript

91

// SHA-3 availability check and usage

92

try {

93

const data = new TextEncoder().encode("SHA-3 test data");

94

const hash = await crypto.subtle.digest("SHA3-256", data);

95

console.log("SHA3-256 supported");

96

} catch (error) {

97

console.log("SHA3-256 not available on this platform");

98

}

99

```

100

101

### SHAKE Extendable-Output Functions (Node.js ≥12)

102

103

SHAKE functions provide variable-length output for specialized applications.

104

105

```typescript { .api }

106

/**

107

* SHAKE extendable-output function parameters

108

*/

109

interface ShakeParams extends Algorithm {

110

name: "shake128" | "shake256";

111

length: number; // Output length in bytes

112

}

113

```

114

115

**Usage Example:**

116

117

```typescript

118

// SHAKE128 with custom output length

119

const data = new TextEncoder().encode("Data for SHAKE");

120

const shakeOutput = await crypto.subtle.digest(

121

{ name: "shake128", length: 32 }, // 32 bytes output

122

data

123

);

124

125

// SHAKE256 with different output length

126

const shake256Output = await crypto.subtle.digest(

127

{ name: "shake256", length: 64 }, // 64 bytes output

128

data

129

);

130

```

131

132

## Hash Function Comparison

133

134

| Algorithm | Output Size | Security Level | Performance | Use Cases |

135

|-----------|-------------|----------------|-------------|-----------|

136

| SHA-1 | 160 bits | Deprecated | Fast | Legacy compatibility only |

137

| SHA-256 | 256 bits | High | Good | General purpose, Bitcoin |

138

| SHA-384 | 384 bits | High | Moderate | High security requirements |

139

| SHA-512 | 512 bits | High | Good | High security, 64-bit platforms |

140

| SHA3-256 | 256 bits | High | Moderate | Alternative to SHA-256 |

141

| SHA3-384 | 384 bits | High | Moderate | Alternative to SHA-384 |

142

| SHA3-512 | 512 bits | High | Moderate | Alternative to SHA-512 |

143

| SHAKE128 | Variable | High | Moderate | Custom output length |

144

| SHAKE256 | Variable | High | Moderate | Custom output length |

145

146

## Advanced Usage Examples

147

148

### Multiple Hash Computations

149

150

```typescript

151

async function computeMultipleHashes(data: ArrayBuffer) {

152

const algorithms: Algorithm[] = [

153

"SHA-1",

154

"SHA-256",

155

"SHA-384",

156

"SHA-512"

157

];

158

159

const hashes = await Promise.all(

160

algorithms.map(async (algorithm) => {

161

try {

162

const hash = await crypto.subtle.digest(algorithm, data);

163

return { algorithm, hash, success: true };

164

} catch (error) {

165

return { algorithm, error, success: false };

166

}

167

})

168

);

169

170

return hashes;

171

}

172

173

// Usage

174

const data = new TextEncoder().encode("Test data");

175

const results = await computeMultipleHashes(data);

176

```

177

178

### File Hashing Example

179

180

```typescript

181

async function hashFile(fileData: ArrayBuffer, algorithm = "SHA-256") {

182

const hashBuffer = await crypto.subtle.digest(algorithm, fileData);

183

const hashArray = Array.from(new Uint8Array(hashBuffer));

184

return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');

185

}

186

187

// Usage for file verification

188

const fileHash = await hashFile(fileData);

189

const expectedHash = "a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3";

190

const isValid = fileHash === expectedHash;

191

```

192

193

### Streaming Hash (Conceptual)

194

195

```typescript

196

// For large data, consider chunked processing

197

async function hashLargeData(dataChunks: ArrayBuffer[]) {

198

// Note: WebCrypto doesn't directly support streaming

199

// This concatenates chunks for demonstration

200

const totalLength = dataChunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);

201

const combined = new Uint8Array(totalLength);

202

203

let offset = 0;

204

for (const chunk of dataChunks) {

205

combined.set(new Uint8Array(chunk), offset);

206

offset += chunk.byteLength;

207

}

208

209

return await crypto.subtle.digest("SHA-256", combined);

210

}

211

```

212

213

## Provider Classes

214

215

### Hash Algorithm Providers

216

217

```typescript { .api }

218

class Sha1Provider extends core.ProviderCrypto {

219

public name: "SHA-1";

220

public usages: never[]; // Digest only

221

}

222

223

class Sha256Provider extends core.ProviderCrypto {

224

public name: "SHA-256";

225

public usages: never[]; // Digest only

226

}

227

228

class Sha384Provider extends core.ProviderCrypto {

229

public name: "SHA-384";

230

public usages: never[]; // Digest only

231

}

232

233

class Sha512Provider extends core.ProviderCrypto {

234

public name: "SHA-512";

235

public usages: never[]; // Digest only

236

}

237

238

class Shake128Provider extends core.ProviderCrypto {

239

public name: "shake128";

240

public usages: never[]; // Digest only

241

}

242

243

class Shake256Provider extends core.ProviderCrypto {

244

public name: "shake256";

245

public usages: never[]; // Digest only

246

}

247

```

248

249

## Platform Availability

250

251

- **SHA-1, SHA-256, SHA-384, SHA-512**: Available on all supported Node.js versions

252

- **SHA3-256, SHA3-384, SHA3-512**: Conditional availability based on Node.js crypto support

253

- **SHAKE128, SHAKE256**: Requires Node.js ≥12

254

- **Platform Detection**: Use try-catch blocks to detect algorithm availability

255

256

## Security Considerations

257

258

- **SHA-1**: Deprecated due to collision vulnerabilities, avoid for new applications

259

- **SHA-256**: Recommended for most applications, widely supported

260

- **SHA-384/SHA-512**: Use for high-security requirements

261

- **SHA-3**: Alternative to SHA-2, useful for diversification

262

- **SHAKE**: Use when variable output length is needed

263

264

## Error Handling

265

266

```typescript

267

async function safeDigest(algorithm: string, data: BufferSource) {

268

try {

269

return await crypto.subtle.digest(algorithm, data);

270

} catch (error) {

271

if (error.name === "NotSupportedError") {

272

throw new Error(`Hash algorithm ${algorithm} not supported`);

273

}

274

if (error.name === "TypeError") {

275

throw new Error("Invalid data format for hashing");

276

}

277

throw error;

278

}

279

}

280

```