File tree 1 file changed +32
-0
lines changed 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Copyright (c) 2025 Tulir Asokan
2
+ //
3
+ // This Source Code Form is subject to the terms of the Mozilla Public
4
+ // License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ // file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
+
7
+ package exstrings
8
+
9
+ import (
10
+ "crypto/sha256"
11
+ "crypto/subtle"
12
+ "unsafe"
13
+ )
14
+
15
+ // UnsafeBytes returns a byte slice that points to the same memory as the input string.
16
+ //
17
+ // The returned byte slice must not be modified.
18
+ func UnsafeBytes (str string ) []byte {
19
+ return unsafe .Slice (unsafe .StringData (str ), len (str ))
20
+ }
21
+
22
+ // SHA256 returns the SHA-256 hash of the input string without copying the string.
23
+ func SHA256 (str string ) [32 ]byte {
24
+ return sha256 .Sum256 (UnsafeBytes (str ))
25
+ }
26
+
27
+ // ConstantTimeEqual compares two strings using [subtle.ConstantTimeCompare] without copying the strings.
28
+ //
29
+ // Note that ConstantTimeCompare is not constant time if the strings are of different length.
30
+ func ConstantTimeEqual (a , b string ) bool {
31
+ return subtle .ConstantTimeCompare (UnsafeBytes (a ), UnsafeBytes (b )) == 1
32
+ }
You can’t perform that action at this time.
0 commit comments