|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +package privacy |
| 19 | + |
| 20 | +import ( |
| 21 | + "github.com/apache/servicecomb-service-center/pkg/log" |
| 22 | + "github.com/elithrar/simple-scrypt" |
| 23 | + "github.com/go-chassis/foundation/stringutil" |
| 24 | + "golang.org/x/crypto/bcrypt" |
| 25 | + "strings" |
| 26 | +) |
| 27 | + |
| 28 | +const ( |
| 29 | + algBcrypt = "$2a$" |
| 30 | +) |
| 31 | + |
| 32 | +//HashPassword |
| 33 | +//Deprecated: use ScryptPassword, this is only for unit test to test compatible with old version |
| 34 | +func HashPassword(pwd string) (string, error) { |
| 35 | + hash, err := bcrypt.GenerateFromPassword([]byte(pwd), 14) |
| 36 | + if err != nil { |
| 37 | + return "", err |
| 38 | + } |
| 39 | + return stringutil.Bytes2str(hash), nil |
| 40 | +} |
| 41 | +func ScryptPassword(pwd string) (string, error) { |
| 42 | + hash, err := scrypt.GenerateFromPassword([]byte(pwd), scrypt.DefaultParams) |
| 43 | + if err != nil { |
| 44 | + return "", err |
| 45 | + } |
| 46 | + return string(hash), nil |
| 47 | +} |
| 48 | +func SamePassword(hashedPwd, pwd string) bool { |
| 49 | + if strings.HasPrefix(hashedPwd, algBcrypt) { |
| 50 | + err := bcrypt.CompareHashAndPassword([]byte(hashedPwd), []byte(pwd)) |
| 51 | + if err == bcrypt.ErrMismatchedHashAndPassword { |
| 52 | + log.Warn("incorrect password attempts") |
| 53 | + } |
| 54 | + return err == nil |
| 55 | + } |
| 56 | + err := scrypt.CompareHashAndPassword([]byte(hashedPwd), []byte(pwd)) |
| 57 | + if err == scrypt.ErrMismatchedHashAndPassword { |
| 58 | + log.Warn("incorrect password attempts") |
| 59 | + } |
| 60 | + return err == nil |
| 61 | + |
| 62 | +} |
0 commit comments