2023-06-19 23:42:47 +02:00
|
|
|
// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
2017-11-20 06:10:04 +01:00
|
|
|
|
2023-08-11 04:46:45 +02:00
|
|
|
package crypto // import "miniflux.app/v2/internal/crypto"
|
2017-11-20 06:10:04 +01:00
|
|
|
|
|
|
|
import (
|
2023-09-09 07:45:17 +02:00
|
|
|
"crypto/hmac"
|
2017-11-20 06:10:04 +01:00
|
|
|
"crypto/rand"
|
|
|
|
"crypto/sha256"
|
|
|
|
"encoding/base64"
|
2019-10-05 13:30:25 +02:00
|
|
|
"encoding/hex"
|
2017-11-20 06:10:04 +01:00
|
|
|
"fmt"
|
2023-07-11 05:59:49 +02:00
|
|
|
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
2017-11-20 06:10:04 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
// 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-25 01:09:10 +01:00
|
|
|
panic(err)
|
2017-11-20 06:10:04 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return b
|
|
|
|
}
|
|
|
|
|
|
|
|
// GenerateRandomString returns a random string.
|
|
|
|
func GenerateRandomString(size int) string {
|
|
|
|
return base64.URLEncoding.EncodeToString(GenerateRandomBytes(size))
|
|
|
|
}
|
2019-10-05 13:30:25 +02:00
|
|
|
|
|
|
|
// GenerateRandomStringHex returns a random hexadecimal string.
|
|
|
|
func GenerateRandomStringHex(size int) string {
|
|
|
|
return hex.EncodeToString(GenerateRandomBytes(size))
|
|
|
|
}
|
2023-07-11 05:59:49 +02:00
|
|
|
|
|
|
|
func HashPassword(password string) (string, error) {
|
|
|
|
bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
|
|
|
return string(bytes), err
|
|
|
|
}
|
2023-09-09 07:45:17 +02:00
|
|
|
|
|
|
|
func GenerateSHA256Hmac(secret string, data []byte) string {
|
|
|
|
h := hmac.New(sha256.New, []byte(secret))
|
|
|
|
h.Write(data)
|
|
|
|
return hex.EncodeToString(h.Sum(nil))
|
|
|
|
}
|