diff options
| author | Jacky Zhao <[email protected]> | 2020-05-15 18:53:37 -0700 |
|---|---|---|
| committer | GitHub <[email protected]> | 2020-05-15 18:53:37 -0700 |
| commit | 2e4a87393d6fdf0320696faedecdc7699289fffb (patch) | |
| tree | 7afe72a155fd9f6afd1bdded4a214b6fbba77fa0 /backend/security/hash.go | |
| parent | Merge pull request #24 from jackyzha0/update-readme (diff) | |
| parent | Add comments and clean up encryption (diff) | |
| download | ctrl-v-2e4a87393d6fdf0320696faedecdc7699289fffb.tar.xz ctrl-v-2e4a87393d6fdf0320696faedecdc7699289fffb.zip | |
Merge pull request #25 from jackyzha0/security
Add encryption to content when password is specified
Diffstat (limited to 'backend/security/hash.go')
| -rw-r--r-- | backend/security/hash.go | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/backend/security/hash.go b/backend/security/hash.go new file mode 100644 index 0000000..b6ce167 --- /dev/null +++ b/backend/security/hash.go @@ -0,0 +1,41 @@ +package security + +import ( + "crypto/md5" + "encoding/hex" + "golang.org/x/crypto/bcrypt" + "math/big" + "time" +) + +const UrlLength = 7 + +// GenerateURI creates a unique identifier for a paste based on ip and timestamp +func GenerateURI(ip string) string { + timeStamp := time.Now().String() + return hashString(ip + timeStamp)[:UrlLength] +} + +// hashes using MD5 and then converts to base 62 +func hashString(text string) string { + hash := md5.Sum([]byte(text)) + hexStr := hex.EncodeToString(hash[:]) + + bi := big.NewInt(0) + bi.SetString(hexStr, 16) + return bi.Text(62) +} + +func HashPassword(password string) (string, error) { + hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + return string(hashedPassword), err +} + +func PasswordsEqual(dbPassword, parsedPassword string) bool { + dbPassBytes := []byte(dbPassword) + parsedPassBytes := []byte(parsedPassword) + compErr := bcrypt.CompareHashAndPassword(dbPassBytes, parsedPassBytes) + + // if comparison error, the given password is not valid + return compErr == nil +}
\ No newline at end of file |