blob: 2dd8af0707b304d465cdea809d343222830775a1 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
/*
* This file is part of LibEuFin.
* Copyright (C) 2024 Taler Systems S.A.
* LibEuFin is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3, or
* (at your option) any later version.
* LibEuFin is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General
* Public License for more details.
* You should have received a copy of the GNU Affero General Public
* License along with LibEuFin; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>
*/
package tech.libeufin.common.crypto
import org.bouncycastle.jce.provider.BouncyCastleProvider
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.math.BigInteger
import java.security.*
import java.security.interfaces.RSAPrivateCrtKey
import java.security.interfaces.RSAPublicKey
import java.security.spec.*
import javax.crypto.*
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.PBEKeySpec
import javax.crypto.spec.PBEParameterSpec
import javax.crypto.spec.SecretKeySpec
import java.util.Base64
import tech.libeufin.common.*
/** Cryptographic operations for secure password storage and verification */
object PwCrypto {
// TODO Use a real password hashing method to store passwords
private val SECURE_RNG = SecureRandom()
/** Hash [pw] using the strongest supported hashing method */
fun hashpw(pw: String): String {
val saltBytes = ByteArray(8)
SECURE_RNG.nextBytes(saltBytes)
val salt = saltBytes.encodeBase64()
val pwh = CryptoUtil.hashStringSHA256("$salt|$pw").encodeBase64()
return "sha256-salted\$$salt\$$pwh"
}
/** Check whether [pw] match hashed [storedPwHash] */
fun checkpw(pw: String, storedPwHash: String): Boolean {
val components = storedPwHash.split('$')
when (val algo = components[0]) {
"sha256" -> { // Support legacy unsalted passwords
if (components.size != 2) throw Exception("bad password hash")
val hash = components[1]
val pwh = CryptoUtil.hashStringSHA256(pw).encodeBase64()
return pwh == hash
}
"sha256-salted" -> {
if (components.size != 3) throw Exception("bad password hash")
val salt = components[1]
val hash = components[2]
val pwh = CryptoUtil.hashStringSHA256("$salt|$pw").encodeBase64()
return pwh == hash
}
else -> throw Exception("unsupported hash algo: '$algo'")
}
}
}
|