2023-06-19 17:42:47 -04:00
|
|
|
// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
2017-11-20 00:10:04 -05:00
|
|
|
|
2018-08-25 00:51:50 -04:00
|
|
|
package crypto // import "miniflux.app/crypto"
|
2017-11-20 00:10:04 -05:00
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rand"
|
|
|
|
"crypto/sha256"
|
|
|
|
"encoding/base64"
|
2019-10-05 07:30:25 -04:00
|
|
|
"encoding/hex"
|
2017-11-20 00:10:04 -05:00
|
|
|
"fmt"
|
|
|
|
)
|
|
|
|
|
|
|
|
// HashFromBytes returns a SHA-256 checksum of the input.
|
|
|
|
func HashFromBytes(value []byte) string {
|
|
|
|
sum := sha256.Sum256(value)
|
|
|
|
return fmt.Sprintf("%x", sum)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Hash returns a SHA-256 checksum of a string.
|
|
|
|
func Hash(value string) string {
|
|
|
|
return HashFromBytes([]byte(value))
|
|
|
|
}
|
|
|
|
|
|
|
|
// GenerateRandomBytes returns random bytes.
|
|
|
|
func GenerateRandomBytes(size int) []byte {
|
|
|
|
b := make([]byte, size)
|
|
|
|
if _, err := rand.Read(b); err != nil {
|
2017-11-24 19:09:10 -05:00
|
|
|
panic(err)
|
2017-11-20 00:10:04 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
return b
|
|
|
|
}
|
|
|
|
|
|
|
|
// GenerateRandomString returns a random string.
|
|
|
|
func GenerateRandomString(size int) string {
|
|
|
|
return base64.URLEncoding.EncodeToString(GenerateRandomBytes(size))
|
|
|
|
}
|
2019-10-05 07:30:25 -04:00
|
|
|
|
|
|
|
// GenerateRandomStringHex returns a random hexadecimal string.
|
|
|
|
func GenerateRandomStringHex(size int) string {
|
|
|
|
return hex.EncodeToString(GenerateRandomBytes(size))
|
|
|
|
}
|