generated from ali/HarmonyTemplate
提交 Haven Android 仓库源码 v5.87.79
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
plugins {
|
||||
alias(libs.plugins.android.library)
|
||||
alias(libs.plugins.hilt)
|
||||
alias(libs.plugins.ksp)
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "sh.haven.core.security"
|
||||
compileSdk = 37
|
||||
|
||||
defaultConfig {
|
||||
minSdk = 26
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
testOptions {
|
||||
unitTests.isReturnDefaultValues = true
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(libs.core.ktx)
|
||||
implementation(libs.tink.android)
|
||||
implementation(libs.biometric)
|
||||
implementation(libs.bouncycastle)
|
||||
implementation(libs.coroutines.core)
|
||||
implementation(libs.hilt.android)
|
||||
ksp(libs.hilt.compiler)
|
||||
|
||||
testImplementation(libs.junit)
|
||||
testImplementation(libs.mockk)
|
||||
// Android's android.jar stubs out org.json.JSONObject in unit tests
|
||||
// (returns defaults). Add the real impl so JwtPayloadTest can parse
|
||||
// base64-decoded JWT claims.
|
||||
testImplementation("org.json:json:20260814")
|
||||
}
|
||||
|
||||
kotlin {
|
||||
compilerOptions {
|
||||
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
package sh.haven.core.security
|
||||
|
||||
import org.bouncycastle.crypto.agreement.X25519Agreement
|
||||
import org.bouncycastle.crypto.digests.SHA256Digest
|
||||
import org.bouncycastle.crypto.generators.HKDFBytesGenerator
|
||||
import org.bouncycastle.crypto.macs.HMac
|
||||
import org.bouncycastle.crypto.modes.ChaCha20Poly1305
|
||||
import org.bouncycastle.crypto.params.AEADParameters
|
||||
import org.bouncycastle.crypto.params.HKDFParameters
|
||||
import org.bouncycastle.crypto.params.KeyParameter
|
||||
import org.bouncycastle.crypto.params.X25519PrivateKeyParameters
|
||||
import org.bouncycastle.crypto.params.X25519PublicKeyParameters
|
||||
import java.io.BufferedInputStream
|
||||
import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
import java.io.PushbackInputStream
|
||||
import java.security.MessageDigest
|
||||
import java.security.SecureRandom
|
||||
import java.util.Base64
|
||||
|
||||
/**
|
||||
* The age file-encryption format (v1), implemented on BouncyCastle primitives
|
||||
* so it works on API 26+ (Android's JCA lacks X25519 / ChaCha20-Poly1305 that
|
||||
* far back). Interoperable with the upstream `age` CLI.
|
||||
*
|
||||
* v1 scope: **X25519 recipients only** — passphrase (scrypt) recipients and
|
||||
* ASCII armor are not implemented (decryption of such files fails rather than
|
||||
* silently mis-handling them). The format is validated against the C2SP/CCTV
|
||||
* age test vectors plus round-trips with the reference `age` binary; see
|
||||
* `AgeFileTest`.
|
||||
*
|
||||
* Spec: https://age-encryption.org/v1
|
||||
*/
|
||||
object AgeFile {
|
||||
private const val VERSION_LINE = "age-encryption.org/v1"
|
||||
private const val FILE_KEY_SIZE = 16
|
||||
private const val CHUNK_SIZE = 64 * 1024
|
||||
private const val TAG_SIZE = 16
|
||||
private const val ENC_CHUNK_SIZE = CHUNK_SIZE + TAG_SIZE
|
||||
private const val X25519_INFO = "age-encryption.org/v1/X25519"
|
||||
private const val RECIPIENT_HRP = "age"
|
||||
private const val IDENTITY_HRP = "age-secret-key-"
|
||||
|
||||
/** An age X25519 keypair. [secret] is `AGE-SECRET-KEY-1…`, [recipient] is `age1…`. */
|
||||
data class AgeIdentity(val secret: String, val recipient: String)
|
||||
|
||||
/** Any failure parsing or decrypting an age file (bad format, bad MAC, no matching identity, corrupt payload). */
|
||||
class AgeException(message: String, cause: Throwable? = null) : Exception(message, cause)
|
||||
|
||||
private val b64Encoder: Base64.Encoder = Base64.getEncoder().withoutPadding()
|
||||
private val b64Decoder: Base64.Decoder = Base64.getDecoder()
|
||||
|
||||
// ── Identity generation ────────────────────────────────────────────────
|
||||
|
||||
fun generateIdentity(random: SecureRandom = SecureRandom()): AgeIdentity {
|
||||
val priv = X25519PrivateKeyParameters(random)
|
||||
val pub = priv.generatePublicKey()
|
||||
val recipient = Bech32.encode(RECIPIENT_HRP, pub.encoded)
|
||||
val secret = Bech32.encode(IDENTITY_HRP, priv.encoded).uppercase()
|
||||
return AgeIdentity(secret, recipient)
|
||||
}
|
||||
|
||||
/** Derive the `age1…` recipient for an `AGE-SECRET-KEY-1…` identity (matches `age-keygen -y`). */
|
||||
fun recipientFor(identity: String): String {
|
||||
val scalar = parseIdentity(identity)
|
||||
val pub = X25519PrivateKeyParameters(scalar, 0).generatePublicKey()
|
||||
return Bech32.encode(RECIPIENT_HRP, pub.encoded)
|
||||
}
|
||||
|
||||
// ── Encrypt ─────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Encrypt [input] to [output] for every recipient in [recipients] (each an
|
||||
* `age1…` string). Streams the payload — safe for arbitrarily large files.
|
||||
* Caller owns both streams and must close them.
|
||||
*/
|
||||
fun encrypt(
|
||||
input: InputStream,
|
||||
output: OutputStream,
|
||||
recipients: List<String>,
|
||||
random: SecureRandom = SecureRandom(),
|
||||
) {
|
||||
require(recipients.isNotEmpty()) { "at least one recipient required" }
|
||||
val fileKey = ByteArray(FILE_KEY_SIZE).also { random.nextBytes(it) }
|
||||
|
||||
val header = StringBuilder(VERSION_LINE).append('\n')
|
||||
for (recipient in recipients) {
|
||||
val recipientPub = parseRecipient(recipient)
|
||||
val ephemeral = X25519PrivateKeyParameters(random)
|
||||
val ephemeralShare = ephemeral.generatePublicKey().encoded
|
||||
val shared = agree(ephemeral.encoded, recipientPub)
|
||||
val wrapKey = hkdf(shared, ephemeralShare + recipientPub, X25519_INFO)
|
||||
val body = aeadSeal(wrapKey, ByteArray(12), fileKey)
|
||||
header.append("-> ").append("X25519").append(' ').append(b64(ephemeralShare)).append('\n')
|
||||
header.append(wrapBody(b64(body))).append('\n')
|
||||
}
|
||||
header.append("---")
|
||||
val headerBytes = header.toString().toByteArray(Charsets.US_ASCII)
|
||||
val mac = hmacSha256(hkdf(fileKey, ByteArray(0), "header"), headerBytes)
|
||||
output.write(headerBytes)
|
||||
output.write(" ".toByteArray(Charsets.US_ASCII))
|
||||
output.write(b64(mac).toByteArray(Charsets.US_ASCII))
|
||||
output.write('\n'.code)
|
||||
|
||||
val nonce = ByteArray(16).also { random.nextBytes(it) }
|
||||
output.write(nonce)
|
||||
streamEncrypt(hkdf(fileKey, nonce, "payload"), input, output)
|
||||
}
|
||||
|
||||
// ── Decrypt ───────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Decrypt [input] to [output] using the first of [identities] (each an
|
||||
* `AGE-SECRET-KEY-1…` string) whose recipient stanza unwraps. Throws
|
||||
* [AgeException] on any malformed input, bad MAC, corrupt payload, or when
|
||||
* no identity matches. Streams the payload.
|
||||
*/
|
||||
fun decrypt(
|
||||
input: InputStream,
|
||||
output: OutputStream,
|
||||
identities: List<String>,
|
||||
) {
|
||||
require(identities.isNotEmpty()) { "at least one identity required" }
|
||||
val scalars = identities.map { parseIdentity(it) }
|
||||
val src = if (input is BufferedInputStream) input else BufferedInputStream(input)
|
||||
|
||||
val reader = LineReader(src)
|
||||
if (reader.readLine() != VERSION_LINE) throw AgeException("unsupported version")
|
||||
|
||||
val stanzas = ArrayList<Stanza>()
|
||||
lateinit var mac: ByteArray
|
||||
var macInput: ByteArray? = null
|
||||
while (true) {
|
||||
val mark = reader.consumedSize()
|
||||
val line = reader.readLine()
|
||||
if (line.startsWith("---")) {
|
||||
if (!line.startsWith("--- ")) throw AgeException("malformed HMAC line")
|
||||
val macField = line.substring(4)
|
||||
if (macField.isEmpty() || macField.contains(' ')) throw AgeException("malformed HMAC line")
|
||||
mac = b64decode(macField)
|
||||
if (mac.size != 32) throw AgeException("bad HMAC length")
|
||||
macInput = reader.consumedPrefix(mark) + "---".toByteArray(Charsets.US_ASCII)
|
||||
break
|
||||
}
|
||||
stanzas.add(parseStanza(line, reader))
|
||||
}
|
||||
|
||||
val fileKey = unwrapFileKey(stanzas, scalars)
|
||||
?: throw AgeException("no matching identity")
|
||||
|
||||
val expectedMac = hmacSha256(hkdf(fileKey, ByteArray(0), "header"), macInput)
|
||||
if (!MessageDigest.isEqual(expectedMac, mac)) throw AgeException("HMAC mismatch")
|
||||
|
||||
val nonce = ByteArray(16)
|
||||
if (readFully(src, nonce) != 16) throw AgeException("missing payload nonce")
|
||||
streamDecrypt(hkdf(fileKey, nonce, "payload"), PushbackInputStream(src, 1), output)
|
||||
}
|
||||
|
||||
// ── Header parsing ──────────────────────────────────────────────────────
|
||||
|
||||
private class Stanza(val args: List<String>, val body: ByteArray)
|
||||
|
||||
private fun parseStanza(firstLine: String, reader: LineReader): Stanza {
|
||||
if (!firstLine.startsWith("-> ")) throw AgeException("malformed stanza")
|
||||
val args = firstLine.substring(3).split(' ')
|
||||
if (args.isEmpty() || args.any { it.isEmpty() || it.any { c -> c.code !in 33..126 } }) {
|
||||
throw AgeException("malformed stanza arguments")
|
||||
}
|
||||
val body = StringBuilder()
|
||||
while (true) {
|
||||
val line = reader.readLine()
|
||||
if (line.length > 64) throw AgeException("stanza body line too long")
|
||||
body.append(line)
|
||||
if (line.length < 64) break
|
||||
}
|
||||
return Stanza(args, b64decode(body.toString()))
|
||||
}
|
||||
|
||||
/** Try every X25519 stanza against every identity. Returns the 16-byte file key or null (no match). */
|
||||
private fun unwrapFileKey(stanzas: List<Stanza>, scalars: List<ByteArray>): ByteArray? {
|
||||
var sawRecipient = false
|
||||
for (stanza in stanzas) {
|
||||
if (stanza.args[0] != "X25519") continue // ignore unknown ("grease") stanzas
|
||||
sawRecipient = true
|
||||
if (stanza.args.size != 2) throw AgeException("X25519 stanza needs exactly one argument")
|
||||
val share = b64decode(stanza.args[1])
|
||||
if (share.size != 32) throw AgeException("X25519 share must be 32 bytes")
|
||||
for (scalar in scalars) {
|
||||
val shared = agree(scalar, share) // throws on all-zero (low-order point)
|
||||
val pub = X25519PrivateKeyParameters(scalar, 0).generatePublicKey().encoded
|
||||
val wrapKey = hkdf(shared, share + pub, X25519_INFO)
|
||||
val fileKey = try {
|
||||
aeadOpen(wrapKey, ByteArray(12), stanza.body)
|
||||
} catch (_: Exception) {
|
||||
continue // tag mismatch — this identity isn't the recipient
|
||||
}
|
||||
if (fileKey.size != FILE_KEY_SIZE) throw AgeException("bad file key size")
|
||||
return fileKey
|
||||
}
|
||||
}
|
||||
if (!sawRecipient) throw AgeException("no X25519 recipients")
|
||||
return null
|
||||
}
|
||||
|
||||
/** Reads `\n`-terminated ASCII lines from [src], rejecting `\r`, while tracking the raw bytes consumed. */
|
||||
private class LineReader(private val src: InputStream) {
|
||||
private val consumed = java.io.ByteArrayOutputStream()
|
||||
fun consumedSize(): Int = consumed.size()
|
||||
fun consumedPrefix(n: Int): ByteArray = consumed.toByteArray().copyOf(n)
|
||||
|
||||
fun readLine(): String {
|
||||
val line = StringBuilder()
|
||||
while (true) {
|
||||
val b = src.read()
|
||||
if (b == -1) throw AgeException("unexpected end of header")
|
||||
consumed.write(b)
|
||||
if (b == '\n'.code) break
|
||||
if (b == '\r'.code) throw AgeException("CR in header")
|
||||
line.append(b.toChar())
|
||||
}
|
||||
return line.toString()
|
||||
}
|
||||
}
|
||||
|
||||
// ── STREAM payload ──────────────────────────────────────────────────────
|
||||
|
||||
private fun streamEncrypt(streamKey: ByteArray, input: InputStream, output: OutputStream) {
|
||||
val pin = PushbackInputStream(input, 1)
|
||||
val buf = ByteArray(CHUNK_SIZE)
|
||||
var counter = 0L
|
||||
while (true) {
|
||||
val n = readFully(pin, buf)
|
||||
val last = n < CHUNK_SIZE || peekEof(pin)
|
||||
output.write(aeadSeal(streamKey, streamNonce(counter, last), buf.copyOf(n)))
|
||||
if (last) break
|
||||
counter++
|
||||
}
|
||||
}
|
||||
|
||||
private fun streamDecrypt(streamKey: ByteArray, pin: PushbackInputStream, output: OutputStream) {
|
||||
val buf = ByteArray(ENC_CHUNK_SIZE)
|
||||
var counter = 0L
|
||||
var firstChunk = true
|
||||
while (true) {
|
||||
val n = readFully(pin, buf)
|
||||
val last = n < ENC_CHUNK_SIZE || peekEof(pin)
|
||||
if (n == 0 && !firstChunk) throw AgeException("missing final chunk")
|
||||
val plain = try {
|
||||
aeadOpen(streamKey, streamNonce(counter, last), buf.copyOf(n))
|
||||
} catch (e: Exception) {
|
||||
throw AgeException("payload authentication failed", e)
|
||||
}
|
||||
if (plain.isEmpty() && !firstChunk) throw AgeException("empty final chunk")
|
||||
output.write(plain)
|
||||
if (last) break
|
||||
counter++
|
||||
firstChunk = false
|
||||
}
|
||||
}
|
||||
|
||||
/** STREAM nonce: 11-byte big-endian counter followed by a 1-byte last-chunk flag. */
|
||||
private fun streamNonce(counter: Long, last: Boolean): ByteArray {
|
||||
val nonce = ByteArray(12)
|
||||
var c = counter
|
||||
for (i in 10 downTo 0) {
|
||||
nonce[i] = (c and 0xff).toByte()
|
||||
c = c ushr 8
|
||||
}
|
||||
if (last) nonce[11] = 1
|
||||
return nonce
|
||||
}
|
||||
|
||||
private fun peekEof(pin: PushbackInputStream): Boolean {
|
||||
val b = pin.read()
|
||||
if (b == -1) return true
|
||||
pin.unread(b)
|
||||
return false
|
||||
}
|
||||
|
||||
// ── Primitives (BouncyCastle) ─────────────────────────────────────────────
|
||||
|
||||
private fun agree(scalar: ByteArray, peerPublic: ByteArray): ByteArray {
|
||||
val agreement = X25519Agreement()
|
||||
agreement.init(X25519PrivateKeyParameters(scalar, 0))
|
||||
val out = ByteArray(agreement.agreementSize)
|
||||
agreement.calculateAgreement(X25519PublicKeyParameters(peerPublic, 0), out, 0)
|
||||
if (out.all { it == 0.toByte() }) throw AgeException("all-zero X25519 shared secret")
|
||||
return out
|
||||
}
|
||||
|
||||
private fun hkdf(ikm: ByteArray, salt: ByteArray, info: String): ByteArray {
|
||||
val generator = HKDFBytesGenerator(SHA256Digest())
|
||||
generator.init(HKDFParameters(ikm, salt, info.toByteArray(Charsets.US_ASCII)))
|
||||
return ByteArray(32).also { generator.generateBytes(it, 0, it.size) }
|
||||
}
|
||||
|
||||
private fun hmacSha256(key: ByteArray, data: ByteArray): ByteArray {
|
||||
val hmac = HMac(SHA256Digest())
|
||||
hmac.init(KeyParameter(key))
|
||||
hmac.update(data, 0, data.size)
|
||||
return ByteArray(hmac.macSize).also { hmac.doFinal(it, 0) }
|
||||
}
|
||||
|
||||
private fun aeadSeal(key: ByteArray, nonce: ByteArray, plaintext: ByteArray): ByteArray {
|
||||
val cipher = ChaCha20Poly1305()
|
||||
cipher.init(true, AEADParameters(KeyParameter(key), 128, nonce))
|
||||
val out = ByteArray(cipher.getOutputSize(plaintext.size))
|
||||
val written = cipher.processBytes(plaintext, 0, plaintext.size, out, 0)
|
||||
cipher.doFinal(out, written)
|
||||
return out
|
||||
}
|
||||
|
||||
private fun aeadOpen(key: ByteArray, nonce: ByteArray, ciphertext: ByteArray): ByteArray {
|
||||
val cipher = ChaCha20Poly1305()
|
||||
cipher.init(false, AEADParameters(KeyParameter(key), 128, nonce))
|
||||
val out = ByteArray(cipher.getOutputSize(ciphertext.size))
|
||||
val written = cipher.processBytes(ciphertext, 0, ciphertext.size, out, 0)
|
||||
val finished = cipher.doFinal(out, written)
|
||||
return out.copyOf(written + finished)
|
||||
}
|
||||
|
||||
// ── Encoding helpers ──────────────────────────────────────────────────────
|
||||
|
||||
private fun parseRecipient(recipient: String): ByteArray {
|
||||
val (hrp, data) = try {
|
||||
Bech32.decode(recipient)
|
||||
} catch (e: IllegalArgumentException) {
|
||||
throw AgeException("invalid recipient", e)
|
||||
}
|
||||
if (hrp != RECIPIENT_HRP || data.size != 32) throw AgeException("invalid recipient")
|
||||
return data
|
||||
}
|
||||
|
||||
private fun parseIdentity(identity: String): ByteArray {
|
||||
val (hrp, data) = try {
|
||||
Bech32.decode(identity.trim())
|
||||
} catch (e: IllegalArgumentException) {
|
||||
throw AgeException("invalid identity", e)
|
||||
}
|
||||
if (hrp != IDENTITY_HRP || data.size != 32) throw AgeException("invalid identity")
|
||||
return data
|
||||
}
|
||||
|
||||
private fun b64(bytes: ByteArray): String = b64Encoder.encodeToString(bytes)
|
||||
|
||||
/** Strict canonical, unpadded base64 decode (age rejects padding and non-canonical encodings). */
|
||||
private fun b64decode(s: String): ByteArray {
|
||||
if (s.contains('=')) throw AgeException("base64 padding not allowed")
|
||||
val decoded = try {
|
||||
b64Decoder.decode(s)
|
||||
} catch (e: IllegalArgumentException) {
|
||||
throw AgeException("invalid base64", e)
|
||||
}
|
||||
if (b64Encoder.encodeToString(decoded) != s) throw AgeException("non-canonical base64")
|
||||
return decoded
|
||||
}
|
||||
|
||||
/** Wrap a base64 body to 64-char lines; the final (possibly empty) line is always < 64 chars. */
|
||||
private fun wrapBody(b64: String): String {
|
||||
val sb = StringBuilder()
|
||||
var i = 0
|
||||
while (b64.length - i >= 64) {
|
||||
sb.append(b64, i, i + 64).append('\n')
|
||||
i += 64
|
||||
}
|
||||
sb.append(b64, i, b64.length)
|
||||
return sb.toString()
|
||||
}
|
||||
|
||||
private fun readFully(src: InputStream, buf: ByteArray): Int {
|
||||
var off = 0
|
||||
while (off < buf.size) {
|
||||
val r = src.read(buf, off, buf.size - off)
|
||||
if (r == -1) break
|
||||
off += r
|
||||
}
|
||||
return off
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package sh.haven.core.security
|
||||
|
||||
/**
|
||||
* Bech32 (BIP-173, checksum constant 1 — *not* Bech32m) encode/decode, the
|
||||
* encoding age uses for recipients and identities:
|
||||
*
|
||||
* - recipient: `Bech32.encode("age", x25519PublicKey)` → `age1…`
|
||||
* - identity: `Bech32.encode("AGE-SECRET-KEY-", scalar)` → `AGE-SECRET-KEY-1…`
|
||||
* (age uppercases the identity; the checksum is computed over the
|
||||
* lowercase form, so [encode] lowercases the HRP for the checksum and
|
||||
* callers uppercase the whole string.)
|
||||
*
|
||||
* Only what age needs: a single HRP, 32-byte payloads, no length cap games
|
||||
* beyond the BIP-173 90-char limit (age strings are well under it). This is
|
||||
* a checksummed base32 codec, not cryptography.
|
||||
*/
|
||||
internal object Bech32 {
|
||||
private const val CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
|
||||
private val REVERSE: IntArray = IntArray(128) { -1 }.also { rev ->
|
||||
CHARSET.forEachIndexed { i, c -> rev[c.code] = i }
|
||||
}
|
||||
|
||||
/** Encode [data] (8-bit bytes) under human-readable prefix [hrp]. HRP is used as given. */
|
||||
fun encode(hrp: String, data: ByteArray): String {
|
||||
val values = convertBits(data, 8, 5, pad = true)
|
||||
?: throw IllegalArgumentException("bech32: cannot regroup bits")
|
||||
val checksum = createChecksum(hrp, values)
|
||||
val sb = StringBuilder(hrp).append('1')
|
||||
(values + checksum).forEach { sb.append(CHARSET[it]) }
|
||||
return sb.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode a Bech32 string into (hrp, 8-bit data). Accepts all-upper or
|
||||
* all-lower (mixed case is rejected per BIP-173); the returned HRP is
|
||||
* lowercased. Throws [IllegalArgumentException] on any malformed input.
|
||||
*/
|
||||
fun decode(input: String): Pair<String, ByteArray> {
|
||||
require(input.length in 8..90) { "bech32: bad length" }
|
||||
val hasLower = input.any { it in 'a'..'z' }
|
||||
val hasUpper = input.any { it in 'A'..'Z' }
|
||||
require(!(hasLower && hasUpper)) { "bech32: mixed case" }
|
||||
val s = input.lowercase()
|
||||
val sep = s.lastIndexOf('1')
|
||||
require(sep >= 1 && sep + 7 <= s.length) { "bech32: bad separator" }
|
||||
val hrp = s.substring(0, sep)
|
||||
val dataPart = s.substring(sep + 1)
|
||||
val values = IntArray(dataPart.length)
|
||||
for (i in dataPart.indices) {
|
||||
val v = REVERSE[dataPart[i].code]
|
||||
require(v != -1) { "bech32: bad char" }
|
||||
values[i] = v
|
||||
}
|
||||
require(verifyChecksum(hrp, values)) { "bech32: bad checksum" }
|
||||
val payload = convertBits(
|
||||
values.copyOfRange(0, values.size - 6).map { it.toByte() }.toByteArray(),
|
||||
5, 8, pad = false,
|
||||
) ?: throw IllegalArgumentException("bech32: bad padding")
|
||||
return hrp to ByteArray(payload.size) { payload[it].toByte() }
|
||||
}
|
||||
|
||||
private fun polymod(values: IntArray): Int {
|
||||
val gen = intArrayOf(0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3)
|
||||
var chk = 1
|
||||
for (v in values) {
|
||||
val top = chk ushr 25
|
||||
chk = ((chk and 0x1ffffff) shl 5) xor v
|
||||
for (i in 0..4) if (((top ushr i) and 1) != 0) chk = chk xor gen[i]
|
||||
}
|
||||
return chk
|
||||
}
|
||||
|
||||
private fun hrpExpand(hrp: String): IntArray {
|
||||
val out = IntArray(hrp.length * 2 + 1)
|
||||
for (i in hrp.indices) out[i] = hrp[i].code ushr 5
|
||||
out[hrp.length] = 0
|
||||
for (i in hrp.indices) out[hrp.length + 1 + i] = hrp[i].code and 31
|
||||
return out
|
||||
}
|
||||
|
||||
private fun verifyChecksum(hrp: String, values: IntArray): Boolean =
|
||||
polymod(hrpExpand(hrp) + values) == 1
|
||||
|
||||
private fun createChecksum(hrp: String, values: IntArray): IntArray {
|
||||
val enc = hrpExpand(hrp) + values + intArrayOf(0, 0, 0, 0, 0, 0)
|
||||
val mod = polymod(enc) xor 1
|
||||
return IntArray(6) { (mod ushr (5 * (5 - it))) and 31 }
|
||||
}
|
||||
|
||||
/** Regroup [data] from [from]-bit to [to]-bit groups. Returns null if a non-pad remainder has set bits. */
|
||||
private fun convertBits(data: ByteArray, from: Int, to: Int, pad: Boolean): IntArray? {
|
||||
var acc = 0
|
||||
var bits = 0
|
||||
val out = ArrayList<Int>()
|
||||
val maxv = (1 shl to) - 1
|
||||
for (b in data) {
|
||||
val value = b.toInt() and 0xff
|
||||
if ((value ushr from) != 0) return null
|
||||
acc = (acc shl from) or value
|
||||
bits += from
|
||||
while (bits >= to) {
|
||||
bits -= to
|
||||
out.add((acc ushr bits) and maxv)
|
||||
}
|
||||
}
|
||||
if (pad) {
|
||||
if (bits > 0) out.add((acc shl (to - bits)) and maxv)
|
||||
} else if (bits >= from || ((acc shl (to - bits)) and maxv) != 0) {
|
||||
return null
|
||||
}
|
||||
return out.toIntArray()
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package sh.haven.core.security
|
||||
|
||||
import android.content.Context
|
||||
import androidx.biometric.BiometricManager
|
||||
import androidx.biometric.BiometricPrompt
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.fragment.app.FragmentActivity
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
import kotlin.coroutines.resume
|
||||
|
||||
@Singleton
|
||||
class BiometricAuthenticator @Inject constructor() {
|
||||
|
||||
companion object {
|
||||
/** Accepts biometric (strong or weak) or device credential (PIN/password/pattern). */
|
||||
private const val ALLOWED_AUTHENTICATORS =
|
||||
BiometricManager.Authenticators.BIOMETRIC_STRONG or
|
||||
BiometricManager.Authenticators.BIOMETRIC_WEAK or
|
||||
BiometricManager.Authenticators.DEVICE_CREDENTIAL
|
||||
}
|
||||
|
||||
enum class Availability { AVAILABLE, NO_HARDWARE, NOT_ENROLLED }
|
||||
|
||||
sealed class AuthResult {
|
||||
data object Success : AuthResult()
|
||||
data class Failure(val message: String) : AuthResult()
|
||||
data object Cancelled : AuthResult()
|
||||
}
|
||||
|
||||
fun checkAvailability(context: Context): Availability {
|
||||
val biometricManager = BiometricManager.from(context)
|
||||
return when (biometricManager.canAuthenticate(ALLOWED_AUTHENTICATORS)) {
|
||||
BiometricManager.BIOMETRIC_SUCCESS -> Availability.AVAILABLE
|
||||
BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -> Availability.NOT_ENROLLED
|
||||
else -> Availability.NO_HARDWARE
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun authenticate(
|
||||
activity: FragmentActivity,
|
||||
title: String = "Unlock Haven",
|
||||
subtitle: String = "Authenticate to continue",
|
||||
): AuthResult = suspendCancellableCoroutine { cont ->
|
||||
val executor = ContextCompat.getMainExecutor(activity)
|
||||
|
||||
val callback = object : BiometricPrompt.AuthenticationCallback() {
|
||||
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
|
||||
if (cont.isActive) cont.resume(AuthResult.Success)
|
||||
}
|
||||
|
||||
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
|
||||
if (!cont.isActive) return
|
||||
val isCancellation = errorCode == BiometricPrompt.ERROR_USER_CANCELED ||
|
||||
errorCode == BiometricPrompt.ERROR_NEGATIVE_BUTTON ||
|
||||
errorCode == BiometricPrompt.ERROR_CANCELED
|
||||
if (isCancellation) {
|
||||
cont.resume(AuthResult.Cancelled)
|
||||
} else {
|
||||
cont.resume(AuthResult.Failure(errString.toString()))
|
||||
}
|
||||
}
|
||||
|
||||
// onAuthenticationFailed: no-op — prompt handles retry internally
|
||||
}
|
||||
|
||||
val prompt = BiometricPrompt(activity, executor, callback)
|
||||
val promptInfo = BiometricPrompt.PromptInfo.Builder()
|
||||
.setTitle(title)
|
||||
.setSubtitle(subtitle)
|
||||
.setAllowedAuthenticators(ALLOWED_AUTHENTICATORS)
|
||||
.build()
|
||||
|
||||
prompt.authenticate(promptInfo)
|
||||
|
||||
cont.invokeOnCancellation { prompt.cancelAuthentication() }
|
||||
}
|
||||
}
|
||||
+302
@@ -0,0 +1,302 @@
|
||||
package sh.haven.core.security
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Base64
|
||||
import com.google.crypto.tink.Aead
|
||||
import com.google.crypto.tink.KeyTemplates
|
||||
import com.google.crypto.tink.aead.AeadConfig
|
||||
import com.google.crypto.tink.integration.android.AndroidKeysetManager
|
||||
import java.security.GeneralSecurityException
|
||||
import java.security.InvalidKeyException
|
||||
import java.security.KeyStoreException
|
||||
import java.security.UnrecoverableKeyException
|
||||
|
||||
/**
|
||||
* Encrypts/decrypts credential strings (passwords) using Tink AEAD backed by Android Keystore.
|
||||
*
|
||||
* Uses its own Keystore master key (`haven_credential_master`), separate from
|
||||
* [KeyEncryption]'s `haven_ssh_key_master`, and distinct associated data, so
|
||||
* password ciphertext cannot be confused with SSH key ciphertext. (An earlier
|
||||
* version of this comment claimed the two shared a master key. They do not —
|
||||
* which matters when diagnosing a Keystore failure, because only one of the
|
||||
* two aliases may be broken.)
|
||||
*
|
||||
* Encrypted values are stored as "ENC:" + Base64(ciphertext) so they can live in
|
||||
* TEXT columns alongside legacy plaintext values. Plaintext values are migrated
|
||||
* transparently on first read/write.
|
||||
*/
|
||||
object CredentialEncryption {
|
||||
|
||||
private const val KEYSET_NAME = "haven_credential_keyset"
|
||||
private const val PREFERENCE_FILE = "haven_credential_keyset_prefs"
|
||||
private const val ANDROID_KEYSTORE = "AndroidKeyStore"
|
||||
private const val MASTER_KEY_ALIAS = "haven_credential_master"
|
||||
private const val MASTER_KEY_URI = "android-keystore://$MASTER_KEY_ALIAS"
|
||||
|
||||
private val ASSOCIATED_DATA = "haven-credential".toByteArray()
|
||||
private const val ENCRYPTED_PREFIX = "ENC:"
|
||||
|
||||
// Tink AEAD (AES256_GCM, TINK output prefix) ciphertext starts with a
|
||||
// 1-byte version 0x01 + 4-byte key id, followed by the 12-byte GCM nonce,
|
||||
// ciphertext, and 16-byte tag — so a genuine value is at least 33 bytes and
|
||||
// begins with 0x01. Used to reject a plaintext that merely happens to start
|
||||
// with "ENC:" (security-review #18).
|
||||
private const val TINK_PREFIX_VERSION: Byte = 0x01
|
||||
private const val TINK_MIN_CIPHERTEXT_LEN = 5 + 12 + 16
|
||||
|
||||
@Volatile
|
||||
private var aead: Aead? = null
|
||||
|
||||
/**
|
||||
* The Android Keystore refused to hand back the credential master key.
|
||||
*
|
||||
* Reported as #579: on some devices `haven_credential_master` becomes
|
||||
* unloadable, and Tink surfaces that as `InvalidKeyException: Keystore
|
||||
* cannot load the key with ID`. It used to escape [encrypt] uncaught and
|
||||
* kill the process on the main thread the moment anyone typed a passphrase
|
||||
* and pressed save.
|
||||
*
|
||||
* Extends `GeneralSecurityException` on purpose: callers that already catch
|
||||
* crypto failures broadly keep working unchanged.
|
||||
*/
|
||||
class KeystoreUnavailableException internal constructor(
|
||||
cause: Throwable,
|
||||
/**
|
||||
* True when the key is gone for good and [resetCredentialStorage] is
|
||||
* the only way forward. False means "try again once the device is
|
||||
* unlocked" — resetting then would destroy recoverable credentials.
|
||||
*/
|
||||
val permanent: Boolean,
|
||||
) : GeneralSecurityException(
|
||||
"Android Keystore cannot serve Haven's credential master key",
|
||||
cause,
|
||||
)
|
||||
|
||||
/** How a Keystore failure should be treated. */
|
||||
enum class Failure {
|
||||
/** Not a Keystore problem — the data or something else is at fault. */
|
||||
NONE,
|
||||
|
||||
/**
|
||||
* The key exists but cannot be used *right now* — typically the device
|
||||
* is locked and the key needs user authentication.
|
||||
*
|
||||
* ★Never reset on this. The credentials are perfectly recoverable once
|
||||
* the device is unlocked, and wiping the master key here would destroy
|
||||
* them for the sake of a lock screen.
|
||||
*/
|
||||
TRANSIENT,
|
||||
|
||||
/**
|
||||
* The key is gone or permanently unusable. Anything encrypted under it
|
||||
* is already undecryptable, so a reset costs nothing that was not
|
||||
* already lost — which is what makes recovery safe at all.
|
||||
*/
|
||||
PERMANENT,
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify a failure from [getAead].
|
||||
*
|
||||
* Walks the cause chain because Tink wraps the Keystore's exception in its
|
||||
* own. Kept pure and separate from the Keystore call so the decision is
|
||||
* unit-testable — none of the surrounding code is, on a JVM with no Android
|
||||
* Keystore in it.
|
||||
*
|
||||
* ★Transient subclasses are checked FIRST and deliberately. Both
|
||||
* `UserNotAuthenticatedException` and `KeyPermanentlyInvalidatedException`
|
||||
* extend `InvalidKeyException` (verified against android-36), so a
|
||||
* classifier that matched the parent first would call a locked device a
|
||||
* dead key and wipe recoverable credentials.
|
||||
*/
|
||||
internal fun classifyFailure(
|
||||
t: Throwable,
|
||||
/**
|
||||
* How to read a throwable's class name. Injectable ONLY so the ordering
|
||||
* below can be tested: the platform Keystore exceptions cannot be
|
||||
* instantiated on a JVM (android.jar ships stubs that throw), so without
|
||||
* this seam the one decision that risks data loss would have no test
|
||||
* that could fail.
|
||||
*/
|
||||
nameOf: (Throwable) -> String = { it::class.java.name },
|
||||
): Failure {
|
||||
var cause: Throwable? = t
|
||||
var hops = 0
|
||||
while (cause != null && hops < 16) {
|
||||
// ★Name check FIRST. UserNotAuthenticatedException and
|
||||
// KeyPermanentlyInvalidatedException both extend InvalidKeyException
|
||||
// (verified against android-36), so matching the parent first would
|
||||
// read a merely-locked device as a dead key — and recovery wipes the
|
||||
// master key, destroying credentials that were recoverable.
|
||||
classifyByName(nameOf(cause))?.let { return it }
|
||||
if (cause is UnrecoverableKeyException || cause is KeyStoreException) {
|
||||
return Failure.PERMANENT
|
||||
}
|
||||
// Tink reports a missing/unusable alias as a bare InvalidKeyException
|
||||
// ("Keystore cannot load the key with ID: ..."), which is #579.
|
||||
if (cause is InvalidKeyException) return Failure.PERMANENT
|
||||
cause = cause.cause
|
||||
hops++
|
||||
}
|
||||
return Failure.NONE
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify the platform Keystore exceptions by name, because they cannot be
|
||||
* referenced from a JVM unit test. Returns null when the name says nothing.
|
||||
*/
|
||||
internal fun classifyByName(className: String): Failure? = when (className) {
|
||||
"android.security.keystore.UserNotAuthenticatedException",
|
||||
"android.security.keystore.KeyNotYetValidException",
|
||||
"android.security.keystore.BackendBusyException",
|
||||
-> Failure.TRANSIENT
|
||||
|
||||
"android.security.keystore.KeyPermanentlyInvalidatedException",
|
||||
"android.security.keystore.KeyExpiredException",
|
||||
-> Failure.PERMANENT
|
||||
|
||||
else -> null
|
||||
}
|
||||
|
||||
/** True when [t] means the Keystore cannot serve our master key at all. */
|
||||
internal fun isKeystoreUnavailable(t: Throwable): Boolean =
|
||||
classifyFailure(t) != Failure.NONE
|
||||
|
||||
private fun getAead(context: Context): Aead {
|
||||
aead?.let { return it }
|
||||
synchronized(this) {
|
||||
aead?.let { return it }
|
||||
try {
|
||||
AeadConfig.register()
|
||||
val keysetHandle = AndroidKeysetManager.Builder()
|
||||
.withSharedPref(context, KEYSET_NAME, PREFERENCE_FILE)
|
||||
.withKeyTemplate(KeyTemplates.get("AES256_GCM"))
|
||||
.withMasterKeyUri(MASTER_KEY_URI)
|
||||
.build()
|
||||
.keysetHandle
|
||||
return keysetHandle.getPrimitive(Aead::class.java).also { aead = it }
|
||||
} catch (t: Throwable) {
|
||||
// Classify rather than swallow: a broken Keystore is a distinct
|
||||
// condition the UI can explain, and anything else still deserves
|
||||
// to surface as itself.
|
||||
val failure = classifyFailure(t)
|
||||
if (failure != Failure.NONE) {
|
||||
throw KeystoreUnavailableException(t, permanent = failure == Failure.PERMANENT)
|
||||
}
|
||||
throw t
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop the credential master key and the keyset it protected, so the next
|
||||
* call regenerates both (#579).
|
||||
*
|
||||
* **This makes every existing `ENC:` value permanently unreadable**, and it
|
||||
* is the only way back from a master key the Keystore will not serve.
|
||||
*
|
||||
* That reads worse than it is. If the master key cannot be loaded, the
|
||||
* keyset it wraps cannot be decrypted, so every credential under it is
|
||||
* *already* unreadable — this does not destroy recoverable data, it
|
||||
* restores the app's ability to store anything at all. That argument only
|
||||
* holds for [Failure.PERMANENT]; on a [Failure.TRANSIENT] failure the data
|
||||
* IS recoverable and calling this would be the thing that loses it.
|
||||
*
|
||||
* Deliberately not called automatically anywhere. The user re-enters their
|
||||
* passwords afterwards, so it is their decision to make, not a repair to
|
||||
* spring on them.
|
||||
*/
|
||||
fun resetCredentialStorage(context: Context) {
|
||||
synchronized(this) {
|
||||
aead = null
|
||||
// Order matters: drop the keyset first. If the process dies between
|
||||
// the two, a stale keyset with no master key is the state we already
|
||||
// know how to recover from, whereas a fresh master key over an old
|
||||
// keyset would look healthy and fail on every decrypt.
|
||||
runCatching {
|
||||
context.getSharedPreferences(PREFERENCE_FILE, Context.MODE_PRIVATE)
|
||||
.edit()
|
||||
.remove(KEYSET_NAME)
|
||||
.commit()
|
||||
}
|
||||
runCatching {
|
||||
val ks = java.security.KeyStore.getInstance(ANDROID_KEYSTORE)
|
||||
ks.load(null)
|
||||
if (ks.containsAlias(MASTER_KEY_ALIAS)) ks.deleteEntry(MASTER_KEY_ALIAS)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Encrypt a password string. Returns "ENC:" + Base64(ciphertext). */
|
||||
fun encrypt(context: Context, plaintext: String): String {
|
||||
val ciphertext = getAead(context).encrypt(plaintext.toByteArray(Charsets.UTF_8), ASSOCIATED_DATA)
|
||||
return ENCRYPTED_PREFIX + Base64.encodeToString(ciphertext, Base64.NO_WRAP)
|
||||
}
|
||||
|
||||
/**
|
||||
* Is credential storage usable right now?
|
||||
*
|
||||
* [Failure.NONE] when the master key loads. Anything else is the reason it
|
||||
* does not, and [Failure.PERMANENT] is the only state in which
|
||||
* [resetCredentialStorage] is the answer.
|
||||
*/
|
||||
fun probe(context: Context): Failure =
|
||||
try {
|
||||
getAead(context)
|
||||
Failure.NONE
|
||||
} catch (e: KeystoreUnavailableException) {
|
||||
if (e.permanent) Failure.PERMANENT else Failure.TRANSIENT
|
||||
} catch (t: Throwable) {
|
||||
classifyFailure(t)
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt, returning null when the value can never be read again.
|
||||
*
|
||||
* Null means *permanently* unreadable — the master key that wrapped this
|
||||
* ciphertext is gone, so no amount of retrying brings it back and the
|
||||
* credential has to be re-entered. Callers can safely treat that as "no
|
||||
* credential stored".
|
||||
*
|
||||
* A TRANSIENT failure throws instead, and that asymmetry is the whole
|
||||
* point. Returning null for a locked device would let the next save write
|
||||
* that null over ciphertext which was about to become readable again —
|
||||
* turning a lock screen into permanent data loss.
|
||||
*/
|
||||
fun decryptOrNull(context: Context, stored: String): String? =
|
||||
try {
|
||||
decrypt(context, stored)
|
||||
} catch (e: KeystoreUnavailableException) {
|
||||
if (e.permanent) null else throw e
|
||||
} catch (_: Exception) {
|
||||
// Corrupt ciphertext, bad Base64, an unparseable restored keyset:
|
||||
// all mean this particular value is not coming back.
|
||||
null
|
||||
}
|
||||
|
||||
/** Decrypt a password string. Handles both encrypted ("ENC:...") and legacy plaintext. */
|
||||
fun decrypt(context: Context, stored: String): String {
|
||||
if (!stored.startsWith(ENCRYPTED_PREFIX)) return stored // legacy plaintext
|
||||
val ciphertext = Base64.decode(stored.removePrefix(ENCRYPTED_PREFIX), Base64.NO_WRAP)
|
||||
return String(getAead(context).decrypt(ciphertext, ASSOCIATED_DATA), Charsets.UTF_8)
|
||||
}
|
||||
|
||||
/**
|
||||
* True if the value is Haven-encrypted ciphertext. Requires the "ENC:"
|
||||
* prefix AND a well-formed Tink AEAD body, so a plaintext credential that
|
||||
* merely starts with "ENC:" is (correctly) treated as plaintext and gets
|
||||
* encrypted on the next save rather than being left in the clear (#18).
|
||||
*/
|
||||
fun isEncrypted(stored: String): Boolean {
|
||||
if (!stored.startsWith(ENCRYPTED_PREFIX)) return false
|
||||
return try {
|
||||
// java.util.Base64 (not android.util.Base64) so this stays a pure
|
||||
// predicate callable from plain JVM unit tests; the standard-alphabet
|
||||
// decoder round-trips the NO_WRAP output that encrypt() writes.
|
||||
val body = java.util.Base64.getDecoder().decode(stored.removePrefix(ENCRYPTED_PREFIX))
|
||||
body.size >= TINK_MIN_CIPHERTEXT_LEN && body[0] == TINK_PREFIX_VERSION
|
||||
} catch (_: Exception) {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package sh.haven.core.security
|
||||
|
||||
import org.json.JSONObject
|
||||
import java.util.Base64
|
||||
|
||||
/**
|
||||
* Minimal JWT payload parser — extracts the `exp` and `email` claims
|
||||
* from a compact-serialised JWT (`header.payload.signature`).
|
||||
*
|
||||
* We deliberately don't verify the signature. The only consumer is the
|
||||
* Cloudflare Access flow, where the JWT comes either from the user's
|
||||
* own authenticated browser session (CookieManager) or is pasted from a
|
||||
* trusted `cloudflared` CLI run — in both cases we treat it as opaque
|
||||
* bearer material. Verification happens upstream when Cloudflare's edge
|
||||
* accepts or rejects the token on the WebSocket upgrade.
|
||||
*
|
||||
* Avoids pulling in a JWT library (jjwt, nimbus-jose) — both add several
|
||||
* MB of transitive deps for one base64-decode + JSON read.
|
||||
*/
|
||||
object JwtPayload {
|
||||
|
||||
data class Payload(
|
||||
/** Unix epoch second from the `exp` claim, or `0` if missing/unparseable. */
|
||||
val expiresAtSeconds: Long,
|
||||
/** Email claim if present (Cloudflare Access tokens usually carry one). */
|
||||
val email: String?,
|
||||
)
|
||||
|
||||
/**
|
||||
* Parse [jwt] and return its payload claims, or `null` if the token
|
||||
* isn't a well-formed JWS compact serialisation. Never throws —
|
||||
* callers handle the null branch as "treat token as opaque, no
|
||||
* expiry-aware UX".
|
||||
*/
|
||||
fun parse(jwt: String): Payload? {
|
||||
val parts = jwt.split('.')
|
||||
if (parts.size < 2) return null
|
||||
val payloadBytes = try {
|
||||
// JWS uses base64url with padding omitted.
|
||||
Base64.getUrlDecoder().decode(parts[1].trimEnd('='))
|
||||
} catch (_: IllegalArgumentException) {
|
||||
return null
|
||||
}
|
||||
val json = try {
|
||||
JSONObject(String(payloadBytes, Charsets.UTF_8))
|
||||
} catch (_: Throwable) {
|
||||
return null
|
||||
}
|
||||
return Payload(
|
||||
expiresAtSeconds = json.optLong("exp", 0L),
|
||||
email = json.optString("email").takeIf { it.isNotBlank() },
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package sh.haven.core.security
|
||||
|
||||
import android.content.Context
|
||||
import com.google.crypto.tink.Aead
|
||||
import com.google.crypto.tink.KeyTemplates
|
||||
import com.google.crypto.tink.aead.AeadConfig
|
||||
import com.google.crypto.tink.integration.android.AndroidKeysetManager
|
||||
|
||||
/**
|
||||
* Encrypts/decrypts SSH private key bytes using Tink AEAD backed by Android Keystore.
|
||||
*
|
||||
* Keys are encrypted with AES-256-GCM. The master key is stored in Android Keystore
|
||||
* (hardware-backed on devices with a secure element). This protects key material
|
||||
* at rest — even if the database is extracted, keys cannot be read without the
|
||||
* device's Keystore.
|
||||
*/
|
||||
object KeyEncryption {
|
||||
|
||||
private const val KEYSET_NAME = "haven_ssh_key_keyset"
|
||||
private const val PREFERENCE_FILE = "haven_ssh_key_keyset_prefs"
|
||||
private const val MASTER_KEY_URI = "android-keystore://haven_ssh_key_master"
|
||||
|
||||
// Associated data for AEAD — prevents ciphertext from being used in a different context
|
||||
private val ASSOCIATED_DATA = "haven-ssh-private-key".toByteArray()
|
||||
|
||||
@Volatile
|
||||
private var aead: Aead? = null
|
||||
|
||||
private fun getAead(context: Context): Aead {
|
||||
aead?.let { return it }
|
||||
synchronized(this) {
|
||||
aead?.let { return it }
|
||||
AeadConfig.register()
|
||||
val keysetHandle = AndroidKeysetManager.Builder()
|
||||
.withSharedPref(context, KEYSET_NAME, PREFERENCE_FILE)
|
||||
.withKeyTemplate(KeyTemplates.get("AES256_GCM"))
|
||||
.withMasterKeyUri(MASTER_KEY_URI)
|
||||
.build()
|
||||
.keysetHandle
|
||||
return keysetHandle.getPrimitive(Aead::class.java).also { aead = it }
|
||||
}
|
||||
}
|
||||
|
||||
/** Encrypt private key bytes. Returns ciphertext that can only be decrypted on this device. */
|
||||
fun encrypt(context: Context, plaintext: ByteArray): ByteArray {
|
||||
return getAead(context).encrypt(plaintext, ASSOCIATED_DATA)
|
||||
}
|
||||
|
||||
/** Decrypt private key bytes. Throws GeneralSecurityException if tampered or wrong device. */
|
||||
fun decrypt(context: Context, ciphertext: ByteArray): ByteArray {
|
||||
return getAead(context).decrypt(ciphertext, ASSOCIATED_DATA)
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if bytes look like they're already encrypted (Tink ciphertext).
|
||||
* Tink AEAD ciphertext starts with a version byte (0x01) followed by a 4-byte key ID.
|
||||
* Plain PEM/OpenSSH keys start with '-' (0x2D) or raw DER starts with 0x30.
|
||||
*/
|
||||
fun isEncrypted(bytes: ByteArray): Boolean {
|
||||
if (bytes.isEmpty()) return false
|
||||
// Plain key formats start with '-' (PEM) or 0x30 (DER SEQUENCE)
|
||||
val first = bytes[0]
|
||||
return first != '-'.code.toByte() && first != 0x30.toByte()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
package sh.haven.core.security
|
||||
|
||||
/**
|
||||
* Conceptual store an entry lives in. Today there are two physical
|
||||
* tables backing key material — the `ssh_keys` Room table (carrying
|
||||
* both regular SSH private keys and FIDO2 SK credentials) and the
|
||||
* `connection_profiles` table's password fields. The [KeystoreStore]
|
||||
* label expresses the conceptual grouping so audit / wipe / export
|
||||
* code can reason about each independently without caring about the
|
||||
* storage layout underneath.
|
||||
*/
|
||||
enum class KeystoreStore {
|
||||
/** Local SSH key material — both regular private keys and FIDO2 SK credentials. */
|
||||
SSH_KEYS,
|
||||
/** Per-profile passwords (sshPassword, vncPassword, smbPassword, rdpPassword). */
|
||||
PROFILE_CREDENTIALS,
|
||||
/** OATH-TOTP shared secrets backing the `totp_secrets` table (#178). */
|
||||
TOTP_SECRETS,
|
||||
/** age X25519 file-encryption identities backing the `age_identities` table. */
|
||||
AGE_IDENTITIES,
|
||||
}
|
||||
|
||||
/**
|
||||
* Specific kind of key material an entry represents. Within a single
|
||||
* [KeystoreStore] the kinds may differ: e.g. [KeystoreStore.SSH_KEYS]
|
||||
* holds both [SSH_PRIVATE] and [SSH_FIDO_SK].
|
||||
*/
|
||||
enum class KeyKind {
|
||||
/** Regular SSH private key (Ed25519, RSA, ECDSA). Encrypted at rest with [KeyEncryption]. */
|
||||
SSH_PRIVATE,
|
||||
/** FIDO2 SK SSH credential — credential ID + public key. The actual signing key lives on the security key, not on this device. */
|
||||
SSH_FIDO_SK,
|
||||
/** A profile password (SSH/VNC/SMB/RDP). Encrypted at rest with [CredentialEncryption]. */
|
||||
PROFILE_PASSWORD,
|
||||
/** An OATH-TOTP shared secret (base32). Encrypted at rest with [CredentialEncryption]. */
|
||||
TOTP_SECRET,
|
||||
/** An age X25519 file-encryption identity (`AGE-SECRET-KEY-1…`). Encrypted at rest with [CredentialEncryption]. */
|
||||
AGE_IDENTITY,
|
||||
}
|
||||
|
||||
/**
|
||||
* Capability / protection flag attached to a [KeystoreEntry]. Aggregated
|
||||
* for audit display ("this key requires biometric unlock", "this FIDO
|
||||
* credential demands user verification").
|
||||
*/
|
||||
enum class KeystoreFlag {
|
||||
/** Master key lives in Android Keystore (hardware-backed when the device has a TEE / secure element). */
|
||||
HARDWARE_BACKED,
|
||||
/** Private key bytes are passphrase-encrypted; user is prompted at use time. */
|
||||
REQUIRES_PASSPHRASE,
|
||||
/** FIDO2 SK key has the user-presence-required flag set (touch the key). */
|
||||
REQUIRES_USER_PRESENCE,
|
||||
/** FIDO2 SK key has the user-verification-required flag set (PIN or biometric). */
|
||||
REQUIRES_USER_VERIFICATION,
|
||||
/** User has opted this entry into a per-fetch BiometricPrompt (#129 stage 5). */
|
||||
BIOMETRIC_PROTECTED,
|
||||
}
|
||||
|
||||
/**
|
||||
* One entry in the unified keystore. Carries enough metadata for the
|
||||
* security audit screen to render the entry plus dispatch wipe/export
|
||||
* back to the right [KeystoreStore]. Never carries plaintext key
|
||||
* material — auditors see what's there, not the secrets.
|
||||
*/
|
||||
data class KeystoreEntry(
|
||||
val id: String,
|
||||
val store: KeystoreStore,
|
||||
val keyKind: KeyKind,
|
||||
val label: String,
|
||||
/** "Ed25519", "RSA-2048", "ed25519-sk", "AES-256-GCM" (for credentials), etc. */
|
||||
val algorithm: String,
|
||||
/** OpenSSH `ssh-ed25519 …` line for SSH keys; null for opaque credentials. */
|
||||
val publicMaterial: String? = null,
|
||||
/** SHA256 fingerprint where derivable (SSH keys); null for credentials. */
|
||||
val fingerprint: String? = null,
|
||||
/** Epoch millis when the entry was created; null when not tracked. */
|
||||
val createdAt: Long? = null,
|
||||
/** Capability / protection flags. See [KeystoreFlag]. */
|
||||
val flags: Set<KeystoreFlag> = emptySet(),
|
||||
)
|
||||
|
||||
/**
|
||||
* Snapshot of every [KeystoreEntry] across every section at a single
|
||||
* point in time, suitable for export, audit-log archival, or
|
||||
* round-tripping into a JSON backup. Carries only metadata — the same
|
||||
* "no plaintext key material" invariant [KeystoreEntry] enforces is
|
||||
* preserved here. The user can hand this file to anyone (an auditor,
|
||||
* a security review, themselves on another device) without leaking
|
||||
* secrets.
|
||||
*/
|
||||
data class KeystoreAuditSnapshot(
|
||||
/** Epoch millis when the snapshot was taken. */
|
||||
val capturedAt: Long,
|
||||
/** Optional app version label. Useful for distinguishing snapshots taken across upgrades; null when not supplied. */
|
||||
val appVersion: String? = null,
|
||||
val entries: List<KeystoreEntry>,
|
||||
) {
|
||||
/** Counts per [KeystoreStore], for at-a-glance audit summaries. */
|
||||
val countsByStore: Map<KeystoreStore, Int>
|
||||
get() = entries.groupingBy { it.store }.eachCount()
|
||||
|
||||
/** Counts per [KeyKind], distinguishing SSH_PRIVATE vs SSH_FIDO_SK vs PROFILE_PASSWORD. */
|
||||
val countsByKind: Map<KeyKind, Int>
|
||||
get() = entries.groupingBy { it.keyKind }.eachCount()
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of a [KeystoreSection.fetch] / [Keystore.fetch] call. The
|
||||
* sealed shape forces callers to handle every state explicitly: a
|
||||
* successful fetch returns either decrypted bytes or a decrypted
|
||||
* password value, a missing entry returns [NotFound], and a decrypt /
|
||||
* IO error surfaces as [Failed].
|
||||
*
|
||||
* The plaintext-bearing variants ([Bytes], [Password]) are the *only*
|
||||
* surface in this package that exposes secret material. Callers MUST
|
||||
* treat them as secret — never log, never persist outside the source
|
||||
* store, and zero / overwrite when done where feasible.
|
||||
*/
|
||||
sealed class KeystoreFetch {
|
||||
/**
|
||||
* Plaintext key material. For [KeyKind.SSH_PRIVATE] the bytes are
|
||||
* the decrypted private key (PEM / OpenSSH); for
|
||||
* [KeyKind.SSH_FIDO_SK] the bytes are the serialized SK descriptor
|
||||
* (credential ID + public key, no signing material). The
|
||||
* corresponding [KeystoreEntry.keyKind] tells callers which they
|
||||
* have.
|
||||
*/
|
||||
class Bytes(val data: ByteArray) : KeystoreFetch()
|
||||
|
||||
/** Plaintext password value for a profile credential. */
|
||||
class Password(val value: String) : KeystoreFetch()
|
||||
|
||||
/** Entry id not registered in this section / store. */
|
||||
data object NotFound : KeystoreFetch()
|
||||
|
||||
/**
|
||||
* Fetch failed. [reason] is a short human-readable label suitable
|
||||
* for surfacing in the audit log; it never carries cipher state or
|
||||
* the secret itself.
|
||||
*/
|
||||
class Failed(val reason: String) : KeystoreFetch()
|
||||
|
||||
/**
|
||||
* The entry is gated behind a human ack that was not given: the
|
||||
* biometric prompt was denied, or it could not be shown at all
|
||||
* because no Activity was foreground.
|
||||
*
|
||||
* Separate from [Failed] on purpose. #559: every failure used to
|
||||
* flatten to the same value, and by the time a connect path saw it
|
||||
* there was no way to tell "the user said no" from "there is no
|
||||
* such key". It treated a denial as a missing credential and
|
||||
* carried on with the next one, so declining the prompt silently
|
||||
* became "use something else" instead of "stop". Whether that is
|
||||
* the right response genuinely differs by caller — a backup should
|
||||
* skip a locked key, an SSH connect should not start — so the
|
||||
* distinction has to survive up to the caller that can decide.
|
||||
*
|
||||
* [reason] is user-facing and secret-free.
|
||||
*/
|
||||
class Denied(val reason: String) : KeystoreFetch()
|
||||
}
|
||||
|
||||
/**
|
||||
* One conceptual region of the unified [Keystore]. Each region wraps a
|
||||
* concrete persistent store (Room DAO / SharedPrefs / etc.) and
|
||||
* translates between its native shape and [KeystoreEntry].
|
||||
*
|
||||
* Implementations live in higher modules where the relevant DAO is
|
||||
* accessible (e.g. `core/data` for `ssh_keys` and `connection_profiles`
|
||||
* — `core/security` is dep-leaf and intentionally cannot reach Room
|
||||
* entities).
|
||||
*/
|
||||
interface KeystoreSection {
|
||||
val store: KeystoreStore
|
||||
suspend fun enumerate(): List<KeystoreEntry>
|
||||
/**
|
||||
* Wipe the entry identified by [entryId] from this section. For SSH
|
||||
* keys this deletes the row. For profile credentials it clears the
|
||||
* password field but leaves the profile in place. Returns true when
|
||||
* something was actually wiped.
|
||||
*/
|
||||
suspend fun wipe(entryId: String): Boolean
|
||||
|
||||
/**
|
||||
* Retrieve the secret material for [entryId]. Implementations
|
||||
* decrypt at-rest material and return the plaintext via
|
||||
* [KeystoreFetch.Bytes] or [KeystoreFetch.Password]; missing or
|
||||
* failed lookups surface through [KeystoreFetch.NotFound] /
|
||||
* [KeystoreFetch.Failed].
|
||||
*
|
||||
* Stage 4 of issue #129 will layer per-entry biometric gating on
|
||||
* top of this method. The current contract is unconditional:
|
||||
* whoever calls [fetch] gets the material if the lookup succeeds.
|
||||
*/
|
||||
suspend fun fetch(entryId: String): KeystoreFetch
|
||||
}
|
||||
|
||||
/**
|
||||
* Unified read-only view across every [KeystoreSection]. Composed at
|
||||
* the application layer (typically `core/data`) so the security audit
|
||||
* screen, agent transport, and any future export tooling all consult
|
||||
* the same surface.
|
||||
*
|
||||
* Adapters that convert between section-native shapes (e.g. [SshKey]
|
||||
* rows, [ConnectionProfile] password columns, FIDO `SkKeyData` blobs)
|
||||
* and [KeystoreEntry] live in their respective modules; this interface
|
||||
* is the seam.
|
||||
*/
|
||||
interface Keystore {
|
||||
suspend fun enumerate(): List<KeystoreEntry>
|
||||
/**
|
||||
* Wipe the entry identified by [entryId] in [store]. Routes to the
|
||||
* matching [KeystoreSection]. Returns true when something was
|
||||
* actually wiped — false for unknown ids or no-op stores.
|
||||
*/
|
||||
suspend fun wipe(store: KeystoreStore, entryId: String): Boolean
|
||||
|
||||
/**
|
||||
* Capture a [KeystoreAuditSnapshot] of every entry across every
|
||||
* section. Intended for export, periodic audit archival, or backup
|
||||
* to a host that's syncing the user's metadata (without the
|
||||
* secrets themselves). Implementations should populate
|
||||
* [KeystoreAuditSnapshot.appVersion] when they have access to a
|
||||
* stable version label; otherwise leave it null and let the caller
|
||||
* supply one.
|
||||
*/
|
||||
suspend fun exportAudit(): KeystoreAuditSnapshot
|
||||
|
||||
/**
|
||||
* Retrieve secret material for a single entry. Routes to the
|
||||
* matching [KeystoreSection]. Returns [KeystoreFetch.NotFound] for
|
||||
* unknown stores or missing entry ids; [KeystoreFetch.Failed] for
|
||||
* decrypt errors (with a human-readable, secret-free reason); and
|
||||
* [KeystoreFetch.Denied] when an entry is gated behind biometric
|
||||
* auth and the prompt was denied or could not be shown.
|
||||
*/
|
||||
suspend fun fetch(store: KeystoreStore, entryId: String): KeystoreFetch
|
||||
|
||||
/**
|
||||
* Toggle [KeystoreFlag.BIOMETRIC_PROTECTED] on a single entry.
|
||||
* Currently supported only on [KeystoreStore.SSH_KEYS]; other
|
||||
* stores return false (no-op). Returns true when the value
|
||||
* actually changed.
|
||||
*/
|
||||
suspend fun setBiometricProtected(
|
||||
store: KeystoreStore,
|
||||
entryId: String,
|
||||
protected: Boolean,
|
||||
): Boolean
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package sh.haven.core.security
|
||||
|
||||
import java.net.URI
|
||||
import java.net.URLDecoder
|
||||
|
||||
/**
|
||||
* Parser for `otpauth://totp/...` URIs (the Key Uri Format used by Google
|
||||
* Authenticator and every compatible app / QR code) and for bare base32
|
||||
* secrets pasted on their own.
|
||||
*
|
||||
* Returns a transport [Parsed] struct rather than a Room entity —
|
||||
* `core/security` is dependency-leaf and intentionally can't reach
|
||||
* `core/data` types; the caller maps [Parsed] onto its storage row.
|
||||
*
|
||||
* Format: `otpauth://totp/LABEL?secret=BASE32&issuer=…&algorithm=…&digits=…&period=…`
|
||||
* where `LABEL` is usually `Issuer:account`. Only `secret` is required.
|
||||
* `hotp://` and missing/empty secrets are rejected (return null).
|
||||
*/
|
||||
object OtpAuthUri {
|
||||
|
||||
data class Parsed(
|
||||
val secret: String,
|
||||
val issuer: String?,
|
||||
val accountName: String?,
|
||||
val algorithm: Totp.Algorithm,
|
||||
val digits: Int,
|
||||
val periodSeconds: Int,
|
||||
) {
|
||||
/** Display label: "issuer (account)" / "issuer" / "account" / "Authenticator". */
|
||||
val label: String
|
||||
get() = when {
|
||||
!issuer.isNullOrBlank() && !accountName.isNullOrBlank() -> "$issuer ($accountName)"
|
||||
!issuer.isNullOrBlank() -> issuer
|
||||
!accountName.isNullOrBlank() -> accountName
|
||||
else -> "Authenticator"
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse [input] as either an `otpauth://totp/...` URI or a bare base32
|
||||
* secret. Returns null when the input is neither a valid TOTP URI nor
|
||||
* a decodable base32 string. Never throws.
|
||||
*/
|
||||
fun parse(input: String): Parsed? {
|
||||
val trimmed = input.trim()
|
||||
if (trimmed.isEmpty()) return null
|
||||
return if (trimmed.startsWith("otpauth://", ignoreCase = true)) {
|
||||
parseUri(trimmed)
|
||||
} else {
|
||||
// Bare secret paste — accept only if it decodes as base32.
|
||||
if (Totp.isValidSecret(trimmed)) {
|
||||
Parsed(
|
||||
secret = trimmed.replace(" ", ""),
|
||||
issuer = null,
|
||||
accountName = null,
|
||||
algorithm = Totp.Algorithm.SHA1,
|
||||
digits = 6,
|
||||
periodSeconds = 30,
|
||||
)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseUri(raw: String): Parsed? {
|
||||
val uri = try {
|
||||
URI(raw)
|
||||
} catch (_: Throwable) {
|
||||
return null
|
||||
}
|
||||
// type is the authority/host: otpauth://totp/... — reject hotp and anything else.
|
||||
if (!uri.host.equals("totp", ignoreCase = true)) return null
|
||||
|
||||
val query = parseQuery(uri.rawQuery)
|
||||
val secret = query["secret"]?.takeIf { Totp.isValidSecret(it) } ?: return null
|
||||
|
||||
// Label path: "/Issuer:account" (issuer prefix optional).
|
||||
val label = uri.path?.trimStart('/')?.let {
|
||||
try {
|
||||
URLDecoder.decode(it, "UTF-8")
|
||||
} catch (_: Throwable) {
|
||||
it
|
||||
}
|
||||
}.orEmpty()
|
||||
val labelIssuer = label.substringBefore(':', missingDelimiterValue = "").trim().ifEmpty { null }
|
||||
val account = label.substringAfter(':', missingDelimiterValue = label).trim().ifEmpty { null }
|
||||
|
||||
// Explicit issuer= param wins over the label prefix.
|
||||
val issuer = query["issuer"]?.trim()?.ifEmpty { null } ?: labelIssuer
|
||||
|
||||
return Parsed(
|
||||
secret = secret.replace(" ", ""),
|
||||
issuer = issuer,
|
||||
accountName = account,
|
||||
algorithm = Totp.Algorithm.fromLabel(query["algorithm"]),
|
||||
digits = query["digits"]?.toIntOrNull()?.takeIf { it in 1..9 } ?: 6,
|
||||
periodSeconds = query["period"]?.toIntOrNull()?.takeIf { it > 0 } ?: 30,
|
||||
)
|
||||
}
|
||||
|
||||
private fun parseQuery(rawQuery: String?): Map<String, String> {
|
||||
if (rawQuery.isNullOrEmpty()) return emptyMap()
|
||||
return rawQuery.split('&').mapNotNull { pair ->
|
||||
val eq = pair.indexOf('=')
|
||||
if (eq < 0) return@mapNotNull null
|
||||
val key = pair.substring(0, eq)
|
||||
val value = try {
|
||||
URLDecoder.decode(pair.substring(eq + 1), "UTF-8")
|
||||
} catch (_: Throwable) {
|
||||
pair.substring(eq + 1)
|
||||
}
|
||||
key to value
|
||||
}.toMap()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package sh.haven.core.security
|
||||
|
||||
/**
|
||||
* POSIX single-quote escape: wraps [s] in `'...'` and rewrites every `'`
|
||||
* inside as `'\''`. Safe for any byte sequence — including spaces, `$`,
|
||||
* backticks, backslashes and newlines — when pasted into a POSIX shell.
|
||||
*/
|
||||
fun posixShellQuote(s: String): String = "'" + s.replace("'", "'\\''") + "'"
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
package sh.haven.core.security
|
||||
|
||||
import org.bouncycastle.crypto.generators.Ed25519KeyPairGenerator
|
||||
import org.bouncycastle.crypto.params.Ed25519KeyGenerationParameters
|
||||
import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters
|
||||
import org.bouncycastle.crypto.params.Ed25519PublicKeyParameters
|
||||
import java.security.KeyPair
|
||||
import java.security.KeyPairGenerator
|
||||
import java.security.SecureRandom
|
||||
import java.security.interfaces.ECPublicKey
|
||||
import java.security.interfaces.RSAPublicKey
|
||||
import java.util.Base64
|
||||
|
||||
/**
|
||||
* Generates SSH keypairs using BouncyCastle (Ed25519) or JCA (RSA, ECDSA).
|
||||
* Private keys are returned as raw bytes — caller is responsible for encryption.
|
||||
*/
|
||||
object SshKeyGenerator {
|
||||
|
||||
enum class KeyType(val displayName: String, val sshName: String) {
|
||||
ED25519("Ed25519", "ssh-ed25519"),
|
||||
RSA_4096("RSA 4096", "ssh-rsa"),
|
||||
ECDSA_384("ECDSA P-384", "ecdsa-sha2-nistp384"),
|
||||
}
|
||||
|
||||
data class GeneratedKey(
|
||||
val type: KeyType,
|
||||
val privateKeyBytes: ByteArray,
|
||||
val publicKeyOpenSsh: String,
|
||||
val fingerprintSha256: String,
|
||||
) {
|
||||
override fun equals(other: Any?): Boolean {
|
||||
if (this === other) return true
|
||||
if (other !is GeneratedKey) return false
|
||||
return type == other.type &&
|
||||
privateKeyBytes.contentEquals(other.privateKeyBytes) &&
|
||||
publicKeyOpenSsh == other.publicKeyOpenSsh
|
||||
}
|
||||
|
||||
override fun hashCode(): Int = privateKeyBytes.contentHashCode()
|
||||
}
|
||||
|
||||
fun generate(type: KeyType, comment: String = ""): GeneratedKey {
|
||||
return when (type) {
|
||||
KeyType.ED25519 -> generateEd25519(comment)
|
||||
KeyType.RSA_4096 -> generateRsa(comment)
|
||||
KeyType.ECDSA_384 -> generateEcdsa(comment)
|
||||
}
|
||||
}
|
||||
|
||||
private fun generateEd25519(comment: String): GeneratedKey {
|
||||
val generator = Ed25519KeyPairGenerator()
|
||||
generator.init(Ed25519KeyGenerationParameters(SecureRandom()))
|
||||
val keyPair = generator.generateKeyPair()
|
||||
|
||||
val privateKey = keyPair.private as Ed25519PrivateKeyParameters
|
||||
val publicKey = keyPair.public as Ed25519PublicKeyParameters
|
||||
|
||||
val pubKeyBlob = encodeEd25519PublicKey(publicKey.encoded)
|
||||
val pubKeyB64 = Base64.getEncoder().encodeToString(pubKeyBlob)
|
||||
val pubLine = "ssh-ed25519 $pubKeyB64${if (comment.isNotEmpty()) " $comment" else ""}"
|
||||
|
||||
val fingerprint = fingerprintSha256(pubKeyBlob)
|
||||
|
||||
return GeneratedKey(
|
||||
type = KeyType.ED25519,
|
||||
privateKeyBytes = privateKey.encoded,
|
||||
publicKeyOpenSsh = pubLine,
|
||||
fingerprintSha256 = fingerprint,
|
||||
)
|
||||
}
|
||||
|
||||
private fun generateRsa(comment: String): GeneratedKey {
|
||||
val kpg = KeyPairGenerator.getInstance("RSA")
|
||||
kpg.initialize(4096, SecureRandom())
|
||||
val keyPair: KeyPair = kpg.generateKeyPair()
|
||||
|
||||
val rsaPub = keyPair.public as RSAPublicKey
|
||||
val pubKeyBlob = encodeRsaPublicKey(rsaPub)
|
||||
val pubKeyB64 = Base64.getEncoder().encodeToString(pubKeyBlob)
|
||||
val pubLine = "ssh-rsa $pubKeyB64${if (comment.isNotEmpty()) " $comment" else ""}"
|
||||
|
||||
val fingerprint = fingerprintSha256(pubKeyBlob)
|
||||
|
||||
return GeneratedKey(
|
||||
type = KeyType.RSA_4096,
|
||||
privateKeyBytes = keyPair.private.encoded,
|
||||
publicKeyOpenSsh = pubLine,
|
||||
fingerprintSha256 = fingerprint,
|
||||
)
|
||||
}
|
||||
|
||||
private fun generateEcdsa(comment: String): GeneratedKey {
|
||||
val kpg = KeyPairGenerator.getInstance("EC")
|
||||
kpg.initialize(384, SecureRandom())
|
||||
val keyPair: KeyPair = kpg.generateKeyPair()
|
||||
|
||||
val ecPub = keyPair.public as ECPublicKey
|
||||
val pubKeyBlob = encodeEcdsaPublicKey(ecPub)
|
||||
val pubKeyB64 = Base64.getEncoder().encodeToString(pubKeyBlob)
|
||||
val pubLine = "ecdsa-sha2-nistp384 $pubKeyB64${if (comment.isNotEmpty()) " $comment" else ""}"
|
||||
|
||||
val fingerprint = fingerprintSha256(pubKeyBlob)
|
||||
|
||||
return GeneratedKey(
|
||||
type = KeyType.ECDSA_384,
|
||||
privateKeyBytes = keyPair.private.encoded,
|
||||
publicKeyOpenSsh = pubLine,
|
||||
fingerprintSha256 = fingerprint,
|
||||
)
|
||||
}
|
||||
|
||||
// SSH wire encoding helpers
|
||||
|
||||
private fun encodeEd25519PublicKey(rawPublicKey: ByteArray): ByteArray {
|
||||
val keyType = "ssh-ed25519".toByteArray()
|
||||
val buf = ByteArray(4 + keyType.size + 4 + rawPublicKey.size)
|
||||
var offset = 0
|
||||
offset = writeBytes(buf, offset, keyType)
|
||||
offset = writeBytes(buf, offset, rawPublicKey)
|
||||
return buf
|
||||
}
|
||||
|
||||
private fun encodeRsaPublicKey(key: RSAPublicKey): ByteArray {
|
||||
val keyType = "ssh-rsa".toByteArray()
|
||||
val e = key.publicExponent.toByteArray()
|
||||
val n = key.modulus.toByteArray()
|
||||
val buf = ByteArray(4 + keyType.size + 4 + e.size + 4 + n.size)
|
||||
var offset = 0
|
||||
offset = writeBytes(buf, offset, keyType)
|
||||
offset = writeBytes(buf, offset, e)
|
||||
writeBytes(buf, offset, n)
|
||||
return buf
|
||||
}
|
||||
|
||||
private fun encodeEcdsaPublicKey(key: ECPublicKey): ByteArray {
|
||||
val keyType = "ecdsa-sha2-nistp384".toByteArray()
|
||||
val curveName = "nistp384".toByteArray()
|
||||
val point = key.w
|
||||
val x = point.affineX.toByteArray()
|
||||
val y = point.affineY.toByteArray()
|
||||
// Uncompressed point: 0x04 || x || y (padded to 48 bytes each)
|
||||
val xPad = x.padStartTo(48)
|
||||
val yPad = y.padStartTo(48)
|
||||
val pointBytes = ByteArray(1 + 48 + 48)
|
||||
pointBytes[0] = 0x04
|
||||
xPad.copyInto(pointBytes, 1)
|
||||
yPad.copyInto(pointBytes, 49)
|
||||
|
||||
val buf = ByteArray(4 + keyType.size + 4 + curveName.size + 4 + pointBytes.size)
|
||||
var offset = 0
|
||||
offset = writeBytes(buf, offset, keyType)
|
||||
offset = writeBytes(buf, offset, curveName)
|
||||
writeBytes(buf, offset, pointBytes)
|
||||
return buf
|
||||
}
|
||||
|
||||
private fun writeBytes(buf: ByteArray, offset: Int, data: ByteArray): Int {
|
||||
buf[offset] = (data.size shr 24 and 0xFF).toByte()
|
||||
buf[offset + 1] = (data.size shr 16 and 0xFF).toByte()
|
||||
buf[offset + 2] = (data.size shr 8 and 0xFF).toByte()
|
||||
buf[offset + 3] = (data.size and 0xFF).toByte()
|
||||
data.copyInto(buf, offset + 4)
|
||||
return offset + 4 + data.size
|
||||
}
|
||||
|
||||
private fun ByteArray.padStartTo(length: Int): ByteArray {
|
||||
if (this.size >= length) return this.takeLast(length).toByteArray()
|
||||
val padded = ByteArray(length)
|
||||
this.copyInto(padded, length - this.size)
|
||||
return padded
|
||||
}
|
||||
|
||||
internal fun fingerprintSha256(publicKeyBlob: ByteArray): String {
|
||||
val digest = java.security.MessageDigest.getInstance("SHA-256").digest(publicKeyBlob)
|
||||
val b64 = Base64.getEncoder().withoutPadding().encodeToString(digest)
|
||||
return "SHA256:$b64"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package sh.haven.core.security
|
||||
|
||||
import javax.crypto.Mac
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
|
||||
/**
|
||||
* Time-based one-time password generator (RFC 6238, built on the HOTP
|
||||
* truncation of RFC 4226). Pure JVM — uses [javax.crypto.Mac] for the
|
||||
* HMAC and a hand-rolled RFC 4648 base32 decode, so it adds no
|
||||
* dependency and is unit-testable off-device against the published
|
||||
* RFC 6238 Appendix-B test vectors.
|
||||
*
|
||||
* The only consumer is the SSH keyboard-interactive auto-fill path
|
||||
* (#178): when a profile's auth chain carries a TOTP secret, the live
|
||||
* code is generated at the moment the server issues the "Verification
|
||||
* code:" prompt and fed back to JSch.
|
||||
*/
|
||||
object Totp {
|
||||
|
||||
/** Hash backing the HMAC. The vast majority of authenticators use [SHA1]. */
|
||||
enum class Algorithm(internal val macName: String) {
|
||||
SHA1("HmacSHA1"),
|
||||
SHA256("HmacSHA256"),
|
||||
SHA512("HmacSHA512"),
|
||||
;
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* Parse an `otpauth://` `algorithm` value (case-insensitive),
|
||||
* defaulting to [SHA1] for null / blank / unrecognised input —
|
||||
* matching the otpauth de-facto default.
|
||||
*/
|
||||
fun fromLabel(label: String?): Algorithm = when (label?.trim()?.uppercase()) {
|
||||
"SHA256" -> SHA256
|
||||
"SHA512" -> SHA512
|
||||
else -> SHA1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate the TOTP code for [secretBase32] at [atMillis].
|
||||
*
|
||||
* @param secretBase32 the shared secret, RFC 4648 base32 (padding and
|
||||
* ASCII whitespace tolerated, case-insensitive).
|
||||
* @param digits code length (otpauth default 6; 8 also common).
|
||||
* @param periodSeconds time step (otpauth default 30).
|
||||
* @throws IllegalArgumentException if the secret isn't valid base32 or
|
||||
* [digits] is out of the supported 1..9 range.
|
||||
*/
|
||||
fun generate(
|
||||
secretBase32: String,
|
||||
atMillis: Long = System.currentTimeMillis(),
|
||||
algorithm: Algorithm = Algorithm.SHA1,
|
||||
digits: Int = 6,
|
||||
periodSeconds: Int = 30,
|
||||
): String {
|
||||
require(digits in 1..9) { "digits must be 1..9, was $digits" }
|
||||
require(periodSeconds > 0) { "periodSeconds must be positive, was $periodSeconds" }
|
||||
val key = decodeBase32(secretBase32)
|
||||
require(key.isNotEmpty()) { "TOTP secret is empty" }
|
||||
|
||||
val counter = (atMillis / 1000L) / periodSeconds
|
||||
val counterBytes = ByteArray(8)
|
||||
var c = counter
|
||||
for (i in 7 downTo 0) {
|
||||
counterBytes[i] = (c and 0xff).toByte()
|
||||
c = c ushr 8
|
||||
}
|
||||
|
||||
val mac = Mac.getInstance(algorithm.macName)
|
||||
mac.init(SecretKeySpec(key, algorithm.macName))
|
||||
val hash = mac.doFinal(counterBytes)
|
||||
|
||||
// RFC 4226 §5.3 dynamic truncation.
|
||||
val offset = (hash[hash.size - 1].toInt() and 0x0f)
|
||||
val binary = ((hash[offset].toInt() and 0x7f) shl 24) or
|
||||
((hash[offset + 1].toInt() and 0xff) shl 16) or
|
||||
((hash[offset + 2].toInt() and 0xff) shl 8) or
|
||||
(hash[offset + 3].toInt() and 0xff)
|
||||
|
||||
var mod = 1
|
||||
repeat(digits) { mod *= 10 }
|
||||
return (binary % mod).toString().padStart(digits, '0')
|
||||
}
|
||||
|
||||
/** Seconds remaining in the current [periodSeconds] window at [atMillis]. */
|
||||
fun secondsRemaining(
|
||||
atMillis: Long = System.currentTimeMillis(),
|
||||
periodSeconds: Int = 30,
|
||||
): Int {
|
||||
val intoStep = (atMillis / 1000L) % periodSeconds
|
||||
return (periodSeconds - intoStep).toInt()
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate that [secretBase32] decodes to non-empty key material —
|
||||
* used to reject bad pastes before persisting. Never throws.
|
||||
*/
|
||||
fun isValidSecret(secretBase32: String): Boolean = try {
|
||||
decodeBase32(secretBase32).isNotEmpty()
|
||||
} catch (_: IllegalArgumentException) {
|
||||
false
|
||||
}
|
||||
|
||||
private const val BASE32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
|
||||
|
||||
/** RFC 4648 base32 decode. Tolerates whitespace, lowercase, and `=` padding. */
|
||||
private fun decodeBase32(input: String): ByteArray {
|
||||
val cleaned = input.trim()
|
||||
.replace(" ", "")
|
||||
.replace("-", "")
|
||||
.trimEnd('=')
|
||||
.uppercase()
|
||||
if (cleaned.isEmpty()) return ByteArray(0)
|
||||
|
||||
val out = ArrayList<Byte>(cleaned.length * 5 / 8)
|
||||
var buffer = 0
|
||||
var bitsLeft = 0
|
||||
for (ch in cleaned) {
|
||||
val value = BASE32_ALPHABET.indexOf(ch)
|
||||
require(value >= 0) { "invalid base32 character: '$ch'" }
|
||||
buffer = (buffer shl 5) or value
|
||||
bitsLeft += 5
|
||||
if (bitsLeft >= 8) {
|
||||
bitsLeft -= 8
|
||||
out.add(((buffer ushr bitsLeft) and 0xff).toByte())
|
||||
}
|
||||
}
|
||||
return out.toByteArray()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package sh.haven.core.security
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Test
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
import java.security.SecureRandom
|
||||
|
||||
/**
|
||||
* Validates [AgeFile] against the official C2SP/CCTV age test vectors plus
|
||||
* encrypt→decrypt round-trips. The vectors in `resources/age-testkit/` are the
|
||||
* non-armored, non-passphrase, non-hybrid (X25519-only) subset — the features
|
||||
* v1 implements; the CCTV README explicitly permits ignoring the rest.
|
||||
*/
|
||||
class AgeFileTest {
|
||||
|
||||
// A reference keypair produced by `age-keygen` — pins Bech32 encoding to the real tool.
|
||||
private val katSecret = "AGE-SECRET-KEY-14Q3LWAMDVQV82QS2LSYP8HGAU9N93KRAGALF5FK7MTWC5TSW8RRQRFSTJL"
|
||||
private val katRecipient = "age106rgar49huet90z0fv0ujr598ddxwljtausq8jm6cxys86uwqausdt06yz"
|
||||
|
||||
@Test
|
||||
fun cctvVectors() {
|
||||
val dir = File(javaClass.getResource("/age-testkit")!!.toURI())
|
||||
val files = dir.listFiles()!!.filter { it.isFile }.sortedBy { it.name }
|
||||
assertTrue("expected vendored vectors", files.size > 50)
|
||||
var checked = 0
|
||||
for (file in files) {
|
||||
val raw = file.readBytes()
|
||||
val sep = indexOfDoubleNewline(raw)
|
||||
val headerText = String(raw, 0, sep, Charsets.US_ASCII)
|
||||
var ageBytes = raw.copyOfRange(sep + 2, raw.size)
|
||||
val fields = headerText.lineSequence()
|
||||
.filter { it.contains(": ") }
|
||||
.map { it.substringBefore(": ") to it.substringAfter(": ") }
|
||||
.toList()
|
||||
val expect = fields.first { it.first == "expect" }.second
|
||||
val identities = fields.filter { it.first == "identity" }.map { it.second }
|
||||
val payloadHash = fields.firstOrNull { it.first == "payload" }?.second
|
||||
// Large vectors are zlib-compressed (CCTV `compressed: zlib` header).
|
||||
if (fields.any { it.first == "compressed" && it.second == "zlib" }) {
|
||||
ageBytes = java.util.zip.InflaterInputStream(ByteArrayInputStream(ageBytes)).readBytes()
|
||||
}
|
||||
|
||||
if (expect == "success") {
|
||||
val out = ByteArrayOutputStream()
|
||||
try {
|
||||
AgeFile.decrypt(ByteArrayInputStream(ageBytes), out, identities)
|
||||
} catch (e: Throwable) {
|
||||
fail("${file.name}: expected success but threw $e")
|
||||
}
|
||||
assertEquals("${file.name}: payload hash", payloadHash, sha256hex(out.toByteArray()))
|
||||
} else {
|
||||
try {
|
||||
AgeFile.decrypt(ByteArrayInputStream(ageBytes), ByteArrayOutputStream(), identities)
|
||||
fail("${file.name}: expected '$expect' failure but decrypt succeeded")
|
||||
} catch (_: Throwable) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
checked++
|
||||
}
|
||||
println("AgeFile: validated $checked CCTV vectors")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun recipientDerivationMatchesAgeKeygen() {
|
||||
assertEquals(katRecipient, AgeFile.recipientFor(katSecret))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun generatedIdentityRoundTripsThroughBech32() {
|
||||
val id = AgeFile.generateIdentity(SecureRandom())
|
||||
assertTrue(id.secret.startsWith("AGE-SECRET-KEY-1"))
|
||||
assertTrue(id.recipient.startsWith("age1"))
|
||||
assertEquals(id.recipient, AgeFile.recipientFor(id.secret))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun roundTripAcrossStreamBoundaries() {
|
||||
val id = AgeFile.generateIdentity()
|
||||
val chunk = 64 * 1024
|
||||
val sizes = listOf(0, 1, 100, chunk - 1, chunk, chunk + 1, 2 * chunk, 2 * chunk + 7, 3 * chunk)
|
||||
for (size in sizes) {
|
||||
val plain = ByteArray(size).also { SecureRandom().nextBytes(it) }
|
||||
val ct = ByteArrayOutputStream()
|
||||
AgeFile.encrypt(ByteArrayInputStream(plain), ct, listOf(id.recipient))
|
||||
val pt = ByteArrayOutputStream()
|
||||
AgeFile.decrypt(ByteArrayInputStream(ct.toByteArray()), pt, listOf(id.secret))
|
||||
assertArrayEquals("round-trip size=$size", plain, pt.toByteArray())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun multipleRecipientsAndNoMatch() {
|
||||
val a = AgeFile.generateIdentity()
|
||||
val b = AgeFile.generateIdentity()
|
||||
val stranger = AgeFile.generateIdentity()
|
||||
val plain = "shared secret".toByteArray()
|
||||
|
||||
val ct = ByteArrayOutputStream()
|
||||
AgeFile.encrypt(ByteArrayInputStream(plain), ct, listOf(a.recipient, b.recipient))
|
||||
val bytes = ct.toByteArray()
|
||||
|
||||
for (id in listOf(a, b)) {
|
||||
val out = ByteArrayOutputStream()
|
||||
AgeFile.decrypt(ByteArrayInputStream(bytes), out, listOf(id.secret))
|
||||
assertArrayEquals(plain, out.toByteArray())
|
||||
}
|
||||
try {
|
||||
AgeFile.decrypt(ByteArrayInputStream(bytes), ByteArrayOutputStream(), listOf(stranger.secret))
|
||||
fail("stranger should not decrypt")
|
||||
} catch (_: Throwable) {
|
||||
}
|
||||
}
|
||||
|
||||
private fun indexOfDoubleNewline(raw: ByteArray): Int {
|
||||
for (i in 0 until raw.size - 1) if (raw[i] == '\n'.code.toByte() && raw[i + 1] == '\n'.code.toByte()) return i
|
||||
error("no header separator")
|
||||
}
|
||||
|
||||
private fun sha256hex(data: ByteArray): String =
|
||||
MessageDigest.getInstance("SHA-256").digest(data).joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
package sh.haven.core.security
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.io.IOException
|
||||
import java.security.GeneralSecurityException
|
||||
import java.security.InvalidKeyException
|
||||
import java.security.KeyStoreException
|
||||
import java.security.UnrecoverableKeyException
|
||||
|
||||
/**
|
||||
* #579: a Keystore that will not serve `haven_credential_master` used to kill
|
||||
* the process from inside a save. This classifier is the decision between
|
||||
* "tell the user the keystore is broken" and "let it surface as itself", so it
|
||||
* is the part worth pinning — the Keystore call around it cannot run on a JVM.
|
||||
*/
|
||||
class CredentialKeystoreFailureTest {
|
||||
|
||||
/** The exact exception from the #579 report. */
|
||||
@Test
|
||||
fun `the reported InvalidKeyException is recognised`() {
|
||||
val reported = InvalidKeyException(
|
||||
"Keystore cannot load the key with ID: haven_credential_master",
|
||||
)
|
||||
assertTrue(CredentialEncryption.isKeystoreUnavailable(reported))
|
||||
}
|
||||
|
||||
/**
|
||||
* Tink does not throw the Keystore's exception directly — it wraps it. A
|
||||
* classifier that only looked at the top frame would have missed the real
|
||||
* report entirely.
|
||||
*/
|
||||
@Test
|
||||
fun `a wrapped keystore failure is recognised through the cause chain`() {
|
||||
val wrapped = GeneralSecurityException(
|
||||
"keyset read failed",
|
||||
IllegalStateException("tink", InvalidKeyException("Keystore cannot load the key")),
|
||||
)
|
||||
assertTrue(CredentialEncryption.isKeystoreUnavailable(wrapped))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `other keystore failure types are recognised`() {
|
||||
assertTrue(CredentialEncryption.isKeystoreUnavailable(KeyStoreException("uninitialised")))
|
||||
assertTrue(CredentialEncryption.isKeystoreUnavailable(UnrecoverableKeyException("bad")))
|
||||
}
|
||||
|
||||
/**
|
||||
* Corrupt ciphertext and IO failures are NOT a broken keystore. Classifying
|
||||
* them as one would tell the user their device is at fault and, worse,
|
||||
* would mask a real bug behind a soothing message.
|
||||
*/
|
||||
@Test
|
||||
fun `data and IO failures are not treated as a keystore failure`() {
|
||||
assertFalse(CredentialEncryption.isKeystoreUnavailable(IOException("keyset file truncated")))
|
||||
assertFalse(CredentialEncryption.isKeystoreUnavailable(IllegalArgumentException("bad base64")))
|
||||
assertFalse(CredentialEncryption.isKeystoreUnavailable(GeneralSecurityException("decryption failed")))
|
||||
}
|
||||
|
||||
/** A self-referencing cause chain must not hang the classifier. */
|
||||
@Test
|
||||
fun `a cyclic cause chain terminates`() {
|
||||
val a = IllegalStateException("a")
|
||||
val b = IllegalStateException("b", a)
|
||||
a.initCause(b)
|
||||
assertFalse(CredentialEncryption.isKeystoreUnavailable(b))
|
||||
}
|
||||
|
||||
// ---- permanent vs transient: the distinction that decides data loss ----
|
||||
|
||||
/**
|
||||
* ★The most important test here. `UserNotAuthenticatedException` extends
|
||||
* `InvalidKeyException` (verified against android-36), so a classifier that
|
||||
* matched the parent first would call a merely-locked device a dead key.
|
||||
* Recovery wipes the master key, so getting this wrong destroys credentials
|
||||
* that were perfectly recoverable once the user unlocked the phone.
|
||||
*/
|
||||
@Test
|
||||
fun `a locked device is TRANSIENT, never permanent`() {
|
||||
assertEquals(
|
||||
CredentialEncryption.Failure.TRANSIENT,
|
||||
CredentialEncryption.classifyByName(
|
||||
"android.security.keystore.UserNotAuthenticatedException",
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a permanently invalidated key is PERMANENT`() {
|
||||
assertEquals(
|
||||
CredentialEncryption.Failure.PERMANENT,
|
||||
CredentialEncryption.classifyByName(
|
||||
"android.security.keystore.KeyPermanentlyInvalidatedException",
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `other transient keystore states are not treated as permanent`() {
|
||||
for (name in listOf(
|
||||
"android.security.keystore.KeyNotYetValidException",
|
||||
"android.security.keystore.BackendBusyException",
|
||||
)) {
|
||||
assertEquals(
|
||||
"$name must not authorise a reset",
|
||||
CredentialEncryption.Failure.TRANSIENT,
|
||||
CredentialEncryption.classifyByName(name),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** An unrelated class name must not decide anything on its own. */
|
||||
@Test
|
||||
fun `an unknown class name yields no verdict`() {
|
||||
assertNull(CredentialEncryption.classifyByName("java.lang.IllegalStateException"))
|
||||
assertNull(CredentialEncryption.classifyByName(""))
|
||||
}
|
||||
|
||||
/** The #579 exception itself: a bare InvalidKeyException from Tink. */
|
||||
@Test
|
||||
fun `the reported failure classifies as PERMANENT so recovery is offered`() {
|
||||
assertEquals(
|
||||
CredentialEncryption.Failure.PERMANENT,
|
||||
CredentialEncryption.classifyFailure(
|
||||
InvalidKeyException("Keystore cannot load the key with ID: haven_credential_master"),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a non-keystore failure classifies as NONE`() {
|
||||
assertEquals(
|
||||
CredentialEncryption.Failure.NONE,
|
||||
CredentialEncryption.classifyFailure(IOException("keyset file truncated")),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* ★The test that guards against data loss.
|
||||
*
|
||||
* A locked device raises `UserNotAuthenticatedException`, which IS an
|
||||
* `InvalidKeyException`. If classifyFailure checked the parent type before
|
||||
* the specific name, it would report PERMANENT, recovery would wipe the
|
||||
* master key, and credentials that only needed an unlock would be gone.
|
||||
*
|
||||
* The platform class cannot be constructed here, so the name is injected —
|
||||
* the throwable stands in for one whose class name is the transient type.
|
||||
*/
|
||||
@Test
|
||||
fun `classifyFailure reads a locked device as TRANSIENT despite it being an InvalidKeyException`() {
|
||||
val locked = InvalidKeyException("user not authenticated")
|
||||
assertEquals(
|
||||
"an InvalidKeyException subclass that means 'locked' must never authorise a reset",
|
||||
CredentialEncryption.Failure.TRANSIENT,
|
||||
CredentialEncryption.classifyFailure(locked) {
|
||||
"android.security.keystore.UserNotAuthenticatedException"
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/** The same seam, proving a permanently invalidated key still reaches PERMANENT. */
|
||||
@Test
|
||||
fun `classifyFailure reads a permanently invalidated key as PERMANENT`() {
|
||||
val dead = InvalidKeyException("key permanently invalidated")
|
||||
assertEquals(
|
||||
CredentialEncryption.Failure.PERMANENT,
|
||||
CredentialEncryption.classifyFailure(dead) {
|
||||
"android.security.keystore.KeyPermanentlyInvalidatedException"
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package sh.haven.core.security
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
import java.util.Base64
|
||||
|
||||
class JwtPayloadTest {
|
||||
|
||||
/** Build a JWT-shaped string with the given payload claims. Signature is filler. */
|
||||
private fun jwt(payload: String): String {
|
||||
val enc = Base64.getUrlEncoder().withoutPadding()
|
||||
val header = enc.encodeToString("""{"alg":"none"}""".toByteArray())
|
||||
val body = enc.encodeToString(payload.toByteArray())
|
||||
val sig = enc.encodeToString("sig".toByteArray())
|
||||
return "$header.$body.$sig"
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `parses exp and email claims`() {
|
||||
val token = jwt("""{"exp":1737934800,"email":"alice@example.com","sub":"abc"}""")
|
||||
val parsed = JwtPayload.parse(token)!!
|
||||
assertEquals(1737934800L, parsed.expiresAtSeconds)
|
||||
assertEquals("alice@example.com", parsed.email)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `missing exp returns zero, missing email returns null`() {
|
||||
val token = jwt("""{"sub":"abc"}""")
|
||||
val parsed = JwtPayload.parse(token)!!
|
||||
assertEquals(0L, parsed.expiresAtSeconds)
|
||||
assertNull(parsed.email)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unparseable JWT returns null instead of throwing`() {
|
||||
assertNull(JwtPayload.parse(""))
|
||||
assertNull(JwtPayload.parse("only-one-segment"))
|
||||
assertNull(JwtPayload.parse("not.valid.b64!"))
|
||||
assertNull(JwtPayload.parse("aGVsbG8.bm90LWpzb24.sig")) // payload base64-decodes to "not-json"
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `tolerates trailing padding on base64url segments`() {
|
||||
// Some JWT producers include padding even though the spec omits it.
|
||||
val enc = Base64.getUrlEncoder() // with padding
|
||||
val header = enc.encodeToString("""{"alg":"none"}""".toByteArray())
|
||||
val body = enc.encodeToString("""{"exp":42}""".toByteArray())
|
||||
val token = "$header.$body.sig"
|
||||
val parsed = JwtPayload.parse(token)!!
|
||||
assertEquals(42L, parsed.expiresAtSeconds)
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package sh.haven.core.security
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class KeyEncryptionTest {
|
||||
|
||||
// ---- isEncrypted() ----
|
||||
|
||||
@Test
|
||||
fun `isEncrypted returns false for PEM key starting with dash`() {
|
||||
// PEM headers start with '-' (0x2D), e.g. "-----BEGIN OPENSSH PRIVATE KEY-----"
|
||||
val pem = "-----BEGIN OPENSSH PRIVATE KEY-----\n...".toByteArray()
|
||||
assertFalse(KeyEncryption.isEncrypted(pem))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `isEncrypted returns false for DER key starting with 0x30`() {
|
||||
// DER keys start with 0x30 (ASN.1 SEQUENCE tag)
|
||||
val der = byteArrayOf(0x30, 0x82.toByte(), 0x00, 0x00)
|
||||
assertFalse(KeyEncryption.isEncrypted(der))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `isEncrypted returns true for Tink ciphertext starting with 0x01`() {
|
||||
// Tink AEAD ciphertext starts with version byte 0x01 followed by a 4-byte key ID
|
||||
val tinkCiphertext = byteArrayOf(0x01, 0x00, 0x00, 0x00, 0x42, 0x99.toByte(), 0xAB.toByte())
|
||||
assertTrue(KeyEncryption.isEncrypted(tinkCiphertext))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `isEncrypted returns true for bytes that are not PEM or DER`() {
|
||||
// Any first byte that is neither '-' (0x2D) nor 0x30 is treated as encrypted
|
||||
val arbitrary = byteArrayOf(0x00, 0x01, 0x02, 0x03)
|
||||
assertTrue(KeyEncryption.isEncrypted(arbitrary))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `isEncrypted returns false for empty array`() {
|
||||
assertFalse(KeyEncryption.isEncrypted(byteArrayOf()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `isEncrypted returns false for single dash byte`() {
|
||||
val singleDash = byteArrayOf('-'.code.toByte())
|
||||
assertFalse(KeyEncryption.isEncrypted(singleDash))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `isEncrypted returns false for single DER sequence byte`() {
|
||||
val singleDer = byteArrayOf(0x30)
|
||||
assertFalse(KeyEncryption.isEncrypted(singleDer))
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package sh.haven.core.security
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Pin the [KeystoreAuditSnapshot] data class — particularly its
|
||||
* derived [KeystoreAuditSnapshot.countsByStore] and
|
||||
* [KeystoreAuditSnapshot.countsByKind] counters which the future audit
|
||||
* UI consumes for at-a-glance summaries.
|
||||
*/
|
||||
class KeystoreAuditSnapshotTest {
|
||||
|
||||
private fun entry(
|
||||
id: String,
|
||||
store: KeystoreStore,
|
||||
kind: KeyKind,
|
||||
) = KeystoreEntry(
|
||||
id = id, store = store, keyKind = kind,
|
||||
label = id, algorithm = "test",
|
||||
)
|
||||
|
||||
@Test
|
||||
fun `countsByStore groups entries by store`() {
|
||||
val snapshot = KeystoreAuditSnapshot(
|
||||
capturedAt = 1000L,
|
||||
entries = listOf(
|
||||
entry("a", KeystoreStore.SSH_KEYS, KeyKind.SSH_PRIVATE),
|
||||
entry("b", KeystoreStore.SSH_KEYS, KeyKind.SSH_FIDO_SK),
|
||||
entry("c", KeystoreStore.PROFILE_CREDENTIALS, KeyKind.PROFILE_PASSWORD),
|
||||
entry("d", KeystoreStore.PROFILE_CREDENTIALS, KeyKind.PROFILE_PASSWORD),
|
||||
entry("e", KeystoreStore.PROFILE_CREDENTIALS, KeyKind.PROFILE_PASSWORD),
|
||||
),
|
||||
)
|
||||
assertEquals(2, snapshot.countsByStore[KeystoreStore.SSH_KEYS])
|
||||
assertEquals(3, snapshot.countsByStore[KeystoreStore.PROFILE_CREDENTIALS])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `countsByKind groups entries by key kind`() {
|
||||
// SSH_FIDO_SK and SSH_PRIVATE both live in SSH_KEYS but distinct
|
||||
// KeyKinds — the audit screen wants to surface "you have 1 FIDO
|
||||
// credential and 4 regular SSH keys" without re-walking the
|
||||
// entries list.
|
||||
val snapshot = KeystoreAuditSnapshot(
|
||||
capturedAt = 0L,
|
||||
entries = listOf(
|
||||
entry("a", KeystoreStore.SSH_KEYS, KeyKind.SSH_PRIVATE),
|
||||
entry("b", KeystoreStore.SSH_KEYS, KeyKind.SSH_PRIVATE),
|
||||
entry("c", KeystoreStore.SSH_KEYS, KeyKind.SSH_FIDO_SK),
|
||||
entry("d", KeystoreStore.PROFILE_CREDENTIALS, KeyKind.PROFILE_PASSWORD),
|
||||
),
|
||||
)
|
||||
assertEquals(2, snapshot.countsByKind[KeyKind.SSH_PRIVATE])
|
||||
assertEquals(1, snapshot.countsByKind[KeyKind.SSH_FIDO_SK])
|
||||
assertEquals(1, snapshot.countsByKind[KeyKind.PROFILE_PASSWORD])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `empty snapshot has empty count maps`() {
|
||||
val snapshot = KeystoreAuditSnapshot(capturedAt = 0L, entries = emptyList())
|
||||
assertTrue(snapshot.countsByStore.isEmpty())
|
||||
assertTrue(snapshot.countsByKind.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `appVersion defaults to null when not supplied`() {
|
||||
// The aggregator at core/data has no stable handle on the app's
|
||||
// BuildConfig; its callers fill in the version label after the
|
||||
// snapshot returns. The default null preserves that contract.
|
||||
val snapshot = KeystoreAuditSnapshot(capturedAt = 0L, entries = emptyList())
|
||||
assertEquals(null, snapshot.appVersion)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package sh.haven.core.security
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
class OtpAuthUriTest {
|
||||
|
||||
@Test
|
||||
fun parsesFullUri() {
|
||||
val p = OtpAuthUri.parse(
|
||||
"otpauth://totp/ACME%20Co:alice@acme.com" +
|
||||
"?secret=GEZDGNBVGY3TQOJQ&issuer=ACME%20Co&algorithm=SHA256&digits=8&period=60",
|
||||
)!!
|
||||
assertEquals("GEZDGNBVGY3TQOJQ", p.secret)
|
||||
assertEquals("ACME Co", p.issuer)
|
||||
assertEquals("alice@acme.com", p.accountName)
|
||||
assertEquals(Totp.Algorithm.SHA256, p.algorithm)
|
||||
assertEquals(8, p.digits)
|
||||
assertEquals(60, p.periodSeconds)
|
||||
assertEquals("ACME Co (alice@acme.com)", p.label)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun appliesOtpauthDefaults() {
|
||||
val p = OtpAuthUri.parse("otpauth://totp/alice?secret=GEZDGNBVGY3TQOJQ")!!
|
||||
assertEquals(Totp.Algorithm.SHA1, p.algorithm)
|
||||
assertEquals(6, p.digits)
|
||||
assertEquals(30, p.periodSeconds)
|
||||
assertNull(p.issuer)
|
||||
assertEquals("alice", p.accountName)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun issuerParamWinsOverLabelPrefix() {
|
||||
val p = OtpAuthUri.parse("otpauth://totp/Wrong:bob?secret=GEZDGNBVGY3TQOJQ&issuer=Right")!!
|
||||
assertEquals("Right", p.issuer)
|
||||
assertEquals("bob", p.accountName)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun acceptsBareBase32() {
|
||||
val p = OtpAuthUri.parse("gezd gnbv gy3t qojq")!!
|
||||
assertEquals("gezdgnbvgy3tqojq", p.secret)
|
||||
assertNull(p.issuer)
|
||||
assertEquals(Totp.Algorithm.SHA1, p.algorithm)
|
||||
assertEquals("Authenticator", p.label)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rejectsHotp() {
|
||||
assertNull(OtpAuthUri.parse("otpauth://hotp/alice?secret=GEZDGNBVGY3TQOJQ&counter=0"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rejectsMissingOrInvalidSecret() {
|
||||
assertNull(OtpAuthUri.parse("otpauth://totp/alice?issuer=ACME"))
|
||||
assertNull(OtpAuthUri.parse("otpauth://totp/alice?secret=!!!notbase32!!!"))
|
||||
assertNull(OtpAuthUri.parse(""))
|
||||
assertNull(OtpAuthUri.parse("https://example.com"))
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package sh.haven.core.security
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class PosixShellQuoteTest {
|
||||
|
||||
@Test fun emptyString() {
|
||||
assertEquals("''", posixShellQuote(""))
|
||||
}
|
||||
|
||||
@Test fun plainPath() {
|
||||
assertEquals("'/tmp/file.txt'", posixShellQuote("/tmp/file.txt"))
|
||||
}
|
||||
|
||||
@Test fun pathWithSpaces() {
|
||||
assertEquals("'/tmp/my file.txt'", posixShellQuote("/tmp/my file.txt"))
|
||||
}
|
||||
|
||||
@Test fun singleQuoteInside() {
|
||||
assertEquals("'it'\\''s.txt'", posixShellQuote("it's.txt"))
|
||||
}
|
||||
|
||||
@Test fun multipleSingleQuotes() {
|
||||
assertEquals("''\\'''\\'''", posixShellQuote("''"))
|
||||
}
|
||||
|
||||
@Test fun shellMetacharsArePreserved() {
|
||||
assertEquals("'\$HOME/`id`/\\n'", posixShellQuote("\$HOME/`id`/\\n"))
|
||||
}
|
||||
|
||||
@Test fun rcloneRemoteReference() {
|
||||
assertEquals("'gdrive:Photos/holiday 2025/IMG_001.jpg'",
|
||||
posixShellQuote("gdrive:Photos/holiday 2025/IMG_001.jpg"))
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
package sh.haven.core.security
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class SshKeyGeneratorTest {
|
||||
|
||||
@Test
|
||||
fun `generate Ed25519 produces valid public key line`() {
|
||||
val key = SshKeyGenerator.generate(SshKeyGenerator.KeyType.ED25519)
|
||||
assertTrue(
|
||||
"Public key should start with ssh-ed25519",
|
||||
key.publicKeyOpenSsh.startsWith("ssh-ed25519 ")
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `generate Ed25519 produces 32-byte private key`() {
|
||||
val key = SshKeyGenerator.generate(SshKeyGenerator.KeyType.ED25519)
|
||||
assertEquals(
|
||||
"Ed25519 private key should be 32 bytes",
|
||||
32, key.privateKeyBytes.size
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `generate Ed25519 with comment appends it`() {
|
||||
val key = SshKeyGenerator.generate(SshKeyGenerator.KeyType.ED25519, "user@haven")
|
||||
assertTrue(
|
||||
"Public key line should end with comment",
|
||||
key.publicKeyOpenSsh.endsWith(" user@haven")
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `generate Ed25519 produces SHA256 fingerprint`() {
|
||||
val key = SshKeyGenerator.generate(SshKeyGenerator.KeyType.ED25519)
|
||||
assertTrue(
|
||||
"Fingerprint should start with SHA256:",
|
||||
key.fingerprintSha256.startsWith("SHA256:")
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `generate Ed25519 produces unique keys each time`() {
|
||||
val key1 = SshKeyGenerator.generate(SshKeyGenerator.KeyType.ED25519)
|
||||
val key2 = SshKeyGenerator.generate(SshKeyGenerator.KeyType.ED25519)
|
||||
assertNotEquals(
|
||||
"Two generated keys should differ",
|
||||
key1.publicKeyOpenSsh, key2.publicKeyOpenSsh
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `generate RSA produces valid public key line`() {
|
||||
val key = SshKeyGenerator.generate(SshKeyGenerator.KeyType.RSA_4096)
|
||||
assertTrue(
|
||||
"Public key should start with ssh-rsa",
|
||||
key.publicKeyOpenSsh.startsWith("ssh-rsa ")
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `generate RSA private key is non-empty`() {
|
||||
val key = SshKeyGenerator.generate(SshKeyGenerator.KeyType.RSA_4096)
|
||||
assertTrue(
|
||||
"RSA private key should be substantial (>1000 bytes)",
|
||||
key.privateKeyBytes.size > 1000
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `generate ECDSA produces valid public key line`() {
|
||||
val key = SshKeyGenerator.generate(SshKeyGenerator.KeyType.ECDSA_384)
|
||||
assertTrue(
|
||||
"Public key should start with ecdsa-sha2-nistp384",
|
||||
key.publicKeyOpenSsh.startsWith("ecdsa-sha2-nistp384 ")
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `generate ECDSA produces SHA256 fingerprint`() {
|
||||
val key = SshKeyGenerator.generate(SshKeyGenerator.KeyType.ECDSA_384)
|
||||
assertTrue(
|
||||
"Fingerprint should start with SHA256:",
|
||||
key.fingerprintSha256.startsWith("SHA256:")
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `all key types set correct type field`() {
|
||||
SshKeyGenerator.KeyType.entries.forEach { type ->
|
||||
val key = SshKeyGenerator.generate(type)
|
||||
assertEquals("Generated key type should match requested type", type, key.type)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fingerprint is deterministic for same key blob`() {
|
||||
val blob = "deterministic-test-data".toByteArray()
|
||||
val fp1 = SshKeyGenerator.fingerprintSha256(blob)
|
||||
val fp2 = SshKeyGenerator.fingerprintSha256(blob)
|
||||
assertEquals("Same input should produce same fingerprint", fp1, fp2)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fingerprint differs for different key blobs`() {
|
||||
val fp1 = SshKeyGenerator.fingerprintSha256("key-a".toByteArray())
|
||||
val fp2 = SshKeyGenerator.fingerprintSha256("key-b".toByteArray())
|
||||
assertNotEquals("Different inputs should produce different fingerprints", fp1, fp2)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package sh.haven.core.security
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Validates [Totp] against the RFC 6238 Appendix-B reference vectors.
|
||||
* The seeds are the RFC's ASCII strings, base32-encoded here (TOTP
|
||||
* secrets are conventionally base32) via a local encoder that is itself
|
||||
* sanity-checked against a known constant.
|
||||
*/
|
||||
class TotpTest {
|
||||
|
||||
// RFC 6238 Appendix-B seeds (ASCII), per algorithm.
|
||||
private val seedSha1 = "12345678901234567890".toByteArray()
|
||||
private val seedSha256 = "12345678901234567890123456789012".toByteArray()
|
||||
private val seedSha512 = "1234567890123456789012345678901234567890123456789012345678901234".toByteArray()
|
||||
|
||||
private val secretSha1 = base32Encode(seedSha1)
|
||||
private val secretSha256 = base32Encode(seedSha256)
|
||||
private val secretSha512 = base32Encode(seedSha512)
|
||||
|
||||
@Test
|
||||
fun base32Encoder_matchesKnownConstant() {
|
||||
// Sanity-check the test's own encoder before relying on it.
|
||||
assertEquals("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", secretSha1)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rfc6238_sha1_vectors() {
|
||||
assertEquals("94287082", code(secretSha1, 59L, Totp.Algorithm.SHA1))
|
||||
assertEquals("07081804", code(secretSha1, 1111111109L, Totp.Algorithm.SHA1))
|
||||
assertEquals("14050471", code(secretSha1, 1111111111L, Totp.Algorithm.SHA1))
|
||||
assertEquals("89005924", code(secretSha1, 1234567890L, Totp.Algorithm.SHA1))
|
||||
assertEquals("69279037", code(secretSha1, 2000000000L, Totp.Algorithm.SHA1))
|
||||
assertEquals("65353130", code(secretSha1, 20000000000L, Totp.Algorithm.SHA1))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rfc6238_sha256_vectors() {
|
||||
assertEquals("46119246", code(secretSha256, 59L, Totp.Algorithm.SHA256))
|
||||
assertEquals("68084774", code(secretSha256, 1111111109L, Totp.Algorithm.SHA256))
|
||||
assertEquals("91819424", code(secretSha256, 1234567890L, Totp.Algorithm.SHA256))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rfc6238_sha512_vectors() {
|
||||
assertEquals("90693936", code(secretSha512, 59L, Totp.Algorithm.SHA512))
|
||||
assertEquals("25091201", code(secretSha512, 1111111109L, Totp.Algorithm.SHA512))
|
||||
assertEquals("93441116", code(secretSha512, 1234567890L, Totp.Algorithm.SHA512))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun defaultSixDigitCode_isZeroPaddedToWidth() {
|
||||
val c = Totp.generate(secretSha1, atMillis = 1234567890L * 1000L)
|
||||
assertEquals(6, c.length)
|
||||
assertTrue(c.all { it.isDigit() })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun tolerates_lowercase_spaces_and_padding() {
|
||||
val canonical = Totp.generate(secretSha1, atMillis = 59_000L)
|
||||
val messy = Totp.generate(
|
||||
secretSha1.lowercase().chunked(4).joinToString(" ") + "===",
|
||||
atMillis = 59_000L,
|
||||
)
|
||||
assertEquals(canonical, messy)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun isValidSecret_rejectsGarbage() {
|
||||
assertTrue(Totp.isValidSecret(secretSha1))
|
||||
assertFalse(Totp.isValidSecret("not base 32 !!!"))
|
||||
assertFalse(Totp.isValidSecret(""))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun secondsRemaining_isWithinPeriod() {
|
||||
assertEquals(1, Totp.secondsRemaining(atMillis = 59_000L, periodSeconds = 30))
|
||||
assertEquals(30, Totp.secondsRemaining(atMillis = 30_000L, periodSeconds = 30))
|
||||
}
|
||||
|
||||
private fun code(secret: String, timeSeconds: Long, algo: Totp.Algorithm): String =
|
||||
Totp.generate(secret, atMillis = timeSeconds * 1000L, algorithm = algo, digits = 8, periodSeconds = 30)
|
||||
|
||||
private fun base32Encode(data: ByteArray): String {
|
||||
val alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
|
||||
val sb = StringBuilder()
|
||||
var buffer = 0
|
||||
var bitsLeft = 0
|
||||
for (b in data) {
|
||||
buffer = (buffer shl 8) or (b.toInt() and 0xff)
|
||||
bitsLeft += 8
|
||||
while (bitsLeft >= 5) {
|
||||
bitsLeft -= 5
|
||||
sb.append(alphabet[(buffer ushr bitsLeft) and 0x1f])
|
||||
}
|
||||
}
|
||||
if (bitsLeft > 0) {
|
||||
sb.append(alphabet[(buffer shl (5 - bitsLeft)) and 0x1f])
|
||||
}
|
||||
return sb.toString()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
comment: lines in the header end with CRLF instead of LF
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
--- 2KIGb7ye32MWtUuEVWkO3MP6qCDLzOvT9wF06lelBSI
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,9 @@
|
||||
expect: HMAC failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
--- 8McE3ix9R34E/vLrQv3yepsHjo/LXhfs22Ab3UyInmg
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,9 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
--- WyJp9F/9FOZh7gJdheq2WIJcwHgYc8NIVh3ddwhrcNg
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,9 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
--- WyJp9F/9FOZh7gJdheq2WIJcwHgYc8NIVh3ddwhrcNgAAA
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,9 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
---
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,9 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
---WyJp9F/9FOZh7gJdheq2WIJcwHgYc8NIVh3ddwhrcNg
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,10 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
comment: the base64 encoding of the HMAC is not canonical
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
--- WyJp9F/9FOZh7gJdheq2WIJcwHgYc8NIVh3ddwhrcNh
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,9 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
--- WyJp9F/9FOZh7gJdheq2WIJcwHgYc8NIVh3ddwhrcNg
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,9 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
--- WyJp
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,11 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
-- stanza
|
||||
|
||||
--- v5wE8ubPxI1cyQyeAwSHnljMh6DkzvX3iAdKgdYJF8A
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,12 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
-> stanza
|
||||
QUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFB
|
||||
QUE=
|
||||
--- /B04zJExClyv/5eAl7g3u3ELs0CUtMpq6ujNdFoG15s
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,11 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
-> stanza argument
|
||||
|
||||
--- zL8VKcvvLCzdRCXsc94hyIEK2TgqrOzR5nv9Yv4hscs
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,12 @@
|
||||
expect: success
|
||||
payload: 013f54400c82da08037759ada907a8b864e97de81c088a182062c4b5622fd2ab
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
-> empty
|
||||
|
||||
--- +M2eEFbXSvJ8j+gW4TtQ8pu/PpF/Jj6nQLwi2uP94tk
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,14 @@
|
||||
expect: success
|
||||
payload: 013f54400c82da08037759ada907a8b864e97de81c088a182062c4b5622fd2ab
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
-> stanza
|
||||
QUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFB
|
||||
QUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFB
|
||||
|
||||
--- D0Uu/whYjf/Cwqz6MHRR9T5em06PLAjTCMcw8aXdyEk
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,11 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
-> stanza è
|
||||
|
||||
--- hnSCjLtEBMl3qMJ3K6Tq/SkIL6VZZ1s3Yl9IOSjxgy0
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,13 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
comment: a body line is longer than 64 columns
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
-> stanza
|
||||
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
|
||||
--- UZrpZrF1A1/isUnRsxyQFmuVqELZSLktrvgn1CvIer8
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,11 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
comment: every stanza must end with a short body line, even if empty
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
-> empty
|
||||
--- OaSGgYUB+XR0qCCme0Uwp9GNJXSEgNpbknu3Q9qtL+M
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,12 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
comment: every stanza must end with a short body line
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
-> stanza
|
||||
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
--- ORM4jo0+tfqd57vT3+pUVZg/sHurDuHFHhXkG7S+RE4
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
comment: a short body line ends the stanza
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
-> stanza
|
||||
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
--- bpHzWOhjqfoXEgzIrDk7vomv/TLD+BFpxul2+j6ZZuw
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,11 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
->
|
||||
|
||||
--- IY9YoLqIaNKUM21ms4L539FbXHrG2FHmECJiECwQimM
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,12 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
-> stanza
|
||||
QUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFB
|
||||
QUF
|
||||
--- 3dcBdeuKtDbEpx/hhcA6qEAR/niQh2MAsruVPRsH4CI
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,11 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
-> stanza
|
||||
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA␍AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
--- ahynG58BNILnncvWP3dPKYYuzvcn8Xajrz3LdsOfwJI
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,14 @@
|
||||
expect: success
|
||||
payload: 013f54400c82da08037759ada907a8b864e97de81c088a182062c4b5622fd2ab
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
|
||||
age-encryption.org/v1
|
||||
-> !"#$%&' ()*+,-./ 01234567 89:;<=>? @ABCDEFG HIJKLMNO
|
||||
|
||||
-> PQRSTUVW XYZ[\]^_ `abcdefg hijklmno pqrstuvw xyz{|}~
|
||||
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
--- qcNy6mAn80JKuXPUW7ANJdOhzbOtVSsIGM12i5B4vx4
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,10 @@
|
||||
expect: payload failure
|
||||
payload: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
--- WyJp9F/9FOZh7gJdheq2WIJcwHgYc8NIVh3ddwhrcNg
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûF
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -0,0 +1,10 @@
|
||||
expect: success
|
||||
payload: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
--- WyJp9F/9FOZh7gJdheq2WIJcwHgYc8NIVh3ddwhrcNg
|
||||
îÏbÇΑ´3'NhÔòùL.OÏ>RŠA0Þ«ïC6åU
|
||||
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
@@ -0,0 +1,10 @@
|
||||
expect: payload failure
|
||||
payload: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
--- WyJp9F/9FOZh7gJdheq2WIJcwHgYc8NIVh3ddwhrcNg
|
||||
îÏbÇΑ´3'NhÔòùL·L[
|
||||
@@ -0,0 +1,10 @@
|
||||
expect: payload failure
|
||||
payload: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
--- WyJp9F/9FOZh7gJdheq2WIJcwHgYc8NIVh3ddwhrcNg
|
||||
îÏbÇΑ´3'NhÔòùL
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
@@ -0,0 +1,8 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
--- WyJp9F/9FOZh7gJdheq2WIJcwHgYc8NIVh3ddwhrcNg
|
||||
@@ -0,0 +1,10 @@
|
||||
expect: payload failure
|
||||
payload: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
--- WyJp9F/9FOZh7gJdheq2WIJcwHgYc8NIVh3ddwhrcNg
|
||||
îÏbÇΑ´3'NhÔòùL[æè.½Ó#Èw
|
||||
@@ -0,0 +1,9 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
--- WyJp9F/9FOZh7gJdheq2WIJcwHgYc8NIVh3ddwhrcNg
|
||||
îÏbÇΑ´3'NhÔ
|
||||
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -0,0 +1,9 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
|
||||
age-encryption.org/v1234
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
--- Tv+h4x3tN8O4kAWnf7DbpSkmNlxlyxSVfY7UoPFkhno
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,10 @@
|
||||
expect: success
|
||||
payload: 013f54400c82da08037759ada907a8b864e97de81c088a182062c4b5622fd2ab
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
--- WyJp9F/9FOZh7gJdheq2WIJcwHgYc8NIVh3ddwhrcNg
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,10 @@
|
||||
expect: no match
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
comment: the ChaCha20Poly1305 authentication tag on the body of the X25519 stanza is wrong
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FE4
|
||||
--- zOCHpynV0aV7p4R6c+bOapgpq9TtpFgGgYghQ2+PIX8
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,10 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
comment: the X25519 stanza has an unexpected extra argument
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc 1234
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
--- l7E0/PQP54HBZYKUu505n1muW7EniDFqMrXgMhFmeiA
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,14 @@
|
||||
expect: success
|
||||
payload: 013f54400c82da08037759ada907a8b864e97de81c088a182062c4b5622fd2ab
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
|
||||
age-encryption.org/v1
|
||||
-> grease
|
||||
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
-> grease
|
||||
|
||||
--- QIfAOEMt1fGOf2FP2m3+TwFQtfy2H3sX3YqUAQRApkM
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,10 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
comment: the X25519 share is the identity point, so the shared secretis the disallowed all-zero value
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
W3E/OCRme9TiTY97JoK31Z71arNur77WIIdB90XnN3M
|
||||
--- Pne3IPMDvBj7wRbPMcNViffpVZAx814tgMxp8AwyMhs
|
||||
¬]?7åPqÓ¦ F—¹ •Â÷õÛ®è␍zŒ(rŠóÎ|
|
||||
@@ -0,0 +1,10 @@
|
||||
expect: header failure
|
||||
file key: 41204c4f4e4745522059454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
comment: the file key must be checked to be 16 bytes before decrypting it
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
nlObGn0CSA4pxiaG3W6nLlaFFuHmqW+bFC6sJmbsJ9yFesgSok1K0AI
|
||||
--- C49Jo3+j4I6jWB2tldSs1jVAXbv0mOTAnwdT+5vOiBg
|
||||
îÏbÇΑ´3'NhÔòùLc÷(çñ␍ÐtÿÇ�P²)€x1
|
||||
@@ -0,0 +1,10 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
comment: an extra most-significant zero byte is appended to the X25519 share
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCcA
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
--- QbEwdWirchS37UUOPh7uVddRiOaWjFwRUpaQ4Q+Z1RE
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,10 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
comment: the X25519 share is a low-order point, so the shared secretis the disallowed all-zero value
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 X5yVvKNQjCSx0LFVnIPvWwREXMRYHI6G2CJO3dCfEdc
|
||||
3E0NpFans/m0WLWF7+54ZBdNj3iqQqpraGDFiaRkvBA
|
||||
--- sXw327YMT1/ULXe+ZyRMbMY0Z2jnWHGgI9j1we6yQ8A
|
||||
¬]?7åPqÓ¦ F—¹ •Â÷õÛ®è␍zŒ(rŠóÎ|
|
||||
@@ -0,0 +1,10 @@
|
||||
expect: no match
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
comment: the first argument in the X25519 stanza is lowercase
|
||||
|
||||
age-encryption.org/v1
|
||||
-> x25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
--- AYeVZK262kiO9KRKUZNEldKRzXDG1vPMXdWs2fF0iJY
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,12 @@
|
||||
expect: success
|
||||
payload: 013f54400c82da08037759ada907a8b864e97de81c088a182062c4b5622fd2ab
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 ajtqAvDEkVNr2B7zUOtq2mAQXDSBlNrVAuM/dKb5sT4
|
||||
0evrK/HQXVsQ4YaDe+659l5OQzvAzD2ytLGHQLQiqxg
|
||||
-> X25519 0qC7u6AbLxuwnM8tPFOWVtWZn/ZZe7z7gcsP5kgA0FI
|
||||
Y3OzevLm23Vx7PN9k33F9y+ercWe/bcZJLqhqA3h408
|
||||
--- 855pKblQzZ3oabDowxRDQvSj/xo47ZSh5WTjkmK0I0U
|
||||
ð¸¾5TB9™ €„–Ko•Ãm³^OYØøž<òo-¥B
|
||||
@@ -0,0 +1,9 @@
|
||||
expect: no match
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-143WN7DCXU4G8R5AXQSSYD9AEPYDNT3HXSLWSPK36CDU6E8M59SSSAGZ3KG
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 ajtqAvDEkVNr2B7zUOtq2mAQXDSBlNrVAuM/dKb5sT4
|
||||
HUKtz0R2j5Bl2ER7HhAZrURikCFpiIjNa0KjHcjbAGU
|
||||
--- rrpTlvKEKrK3EqhoOPJeP1KE8O1d2arrRez77mwekRc
|
||||
ÝßrÐo¼«Wß=␍1$–!Œ×ýo€x»ø�-ØyG^·½^ˆ
|
||||
@@ -0,0 +1,10 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
comment: the base64 encoding of the share is not canonical
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCc
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLF
|
||||
--- SGYx1A08TAxtamnfCclSbmk59kIZWY8/f+qmMXv4g9g
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,10 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
comment: the base64 encoding of the share is not canonical
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 TEiF0ypqr+bpvcqXNyCVJpL7OuwPdVwPL7KQEbFDOCd
|
||||
hjabGXwSLQ9c3S6Lw2i+S2Tu2fiwQHHslbBN6B41FLE
|
||||
--- ngoKTEDpJF0jTrD7UALMpTyjZC8ONeH6kqCvSYCvm2g
|
||||
îÏbÇΑ´3'NhÔòùL·L[þ÷¾ªRÈð¼™,ƒ1ûf
|
||||
@@ -0,0 +1,10 @@
|
||||
expect: header failure
|
||||
file key: 59454c4c4f57205355424d4152494e45
|
||||
identity: AGE-SECRET-KEY-1EGTZVFFV20835NWYV6270LXYVK2VKNX2MMDKWYKLMGR48UAWX40Q2P2LM0
|
||||
comment: a trailing zero is missing from the X25519 share
|
||||
|
||||
age-encryption.org/v1
|
||||
-> X25519 l7o4oTX9X5E3/KODa/7CQ0CrA9fKMWsm9IJjYzSlJg
|
||||
yUGP5aPob6YJ+vzRfBtDT9D1K/wmyheZE/Xl/mDSKA4
|
||||
--- Zn1/VRtHpD93HtIXSv1S++POXeKcQF7w1+hpXhMiAbk
|
||||
¬]?7åPqÓ¦ F—¹ •Â÷õÛ®è␍zŒ(rŠóÎ|
|
||||
Reference in New Issue
Block a user