scoop:scoop.crypto:0.1.0
src/jws/compact.scoop
Selected production source · src/jws/compact.scoop
1
package scoop.crypto.jws3
import scoop.crypto.*4
import scoop.crypto.native.*5
import scoop.text.split7
/**8
* The explicitly selected compact JWS algorithm. Header validation requires the token's alg to9
* match this selection.10
*/11
public enum JwsAlgorithm {12
/**13
* HMAC-SHA-256 with a symmetric key.14
*/15
HS256,16
/**17
* RSA PKCS#1 v1.5 with SHA-256.18
*/19
RS256,20
/**21
* RSA-PSS with SHA-256.22
*/23
PS256,24
/**25
* P-256 ECDSA with SHA-256 and JWS raw signature encoding.26
*/27
ES256,28
/**29
* Ed25519 signing for compact JWS.30
*/31
EdDSA }32
/**33
* Selects symmetric MAC or asymmetric private-key signing without transferring key ownership.34
*/35
public enum JwsSigningKey {36
/**37
* A borrowed symmetric key for HS256.38
*/39
Mac(SecretKey),40
/**41
* A borrowed private key matching the selected asymmetric scheme.42
*/43
Signature(PrivateKey) }44
/**45
* Selects symmetric MAC or asymmetric public-key verification without transferring ownership.46
*/47
public enum JwsVerificationKey {48
/**49
* A borrowed symmetric key for HS256 verification.50
*/51
Mac(SecretKey),52
/**53
* A borrowed public key matching the selected asymmetric scheme.54
*/55
Signature(PublicKey) }56
/**57
* The protected header, payload bytes, and optional key identifier after cryptographic58
* verification. Payload claims such as expiry or audience are not interpreted.59
*/60
public struct VerifiedJws(val protectedHeader: String, val payload: Array<Byte>, val keyId: String?)62
internal fun algorithmName(algorithm: JwsAlgorithm): String = when (algorithm) {63
case HS256 -> "HS256"64
case RS256 -> "RS256"65
case PS256 -> "PS256"66
case ES256 -> "ES256"67
case EdDSA -> "EdDSA"68
}70
private fun signatureAlgorithm(algorithm: JwsAlgorithm): SignatureAlgorithm = when (algorithm) {71
case RS256 -> SignatureAlgorithm.RsaPkcs1Sha25672
case PS256 -> SignatureAlgorithm.RsaPssSha25673
case ES256 -> SignatureAlgorithm.EcdsaP256Sha256Der74
case EdDSA -> SignatureAlgorithm.Ed2551975
case HS256 -> throw IllegalArgumentException(Some("HS256 requires a MAC key"))76
}78
private fun requireMac(algorithm: JwsAlgorithm, key: SecretKey) {79
if (algorithm != JwsAlgorithm.HS256) throw IllegalArgumentException(Some("signature algorithm requires an asymmetric key"))80
if (key.size < 32L) throw IllegalArgumentException(Some("HS256 key must contain at least 32 bytes"))81
}83
/**84
* Validates the protected header and produces the three base64url compact-JWS segments. HS25685
* needs at least 32 key bytes; ES256 uses the JWS fixed-width signature encoding.86
*/87
public fun signCompact(protectedHeader: String, payload: List<Byte>, algorithm: JwsAlgorithm, key: JwsSigningKey): String {88
parseHeader(protectedHeader, algorithm)89
val input = urlEncoding.encode(protectedHeader.toByteArray()) + "." + urlEncoding.encode(payload)90
val bytes = input.toByteArray()91
val signature = when (key) {92
case Mac(val secret) -> {93
requireMac(algorithm, secret)94
hmac(DigestAlgorithm.Sha256, secret, bytes)95
}96
case Signature(val privateKey) -> {97
val der = sign(signatureAlgorithm(algorithm), privateKey, bytes)98
if (algorithm == JwsAlgorithm.ES256) convertEcdsa(der, true) else der99
}100
}101
return input + "." + urlEncoding.encode(signature)102
}104
// Verifies the signature and returns the header and payload; a mismatch returns None.105
/**106
* Validates compact syntax and the explicitly selected algorithm, then verifies the signature. A107
* signature mismatch returns None; malformed headers or encodings throw JwsException. Application108
* payload claims remain the caller's responsibility.109
*/110
public fun verifyCompactOrNone(token: String, algorithm: JwsAlgorithm, key: JwsVerificationKey): VerifiedJws? {111
val parts = token.split('.')112
if (parts.size != 3L) throw JwsException("compact JWS must contain three segments")113
val header = headerText(decodePart(parts[0L]))114
val parsed = parseHeader(header, algorithm)115
val payload = decodePart(parts[1L])116
val signature = decodePart(parts[2L])117
val input = (parts[0L] + "." + parts[1L]).toByteArray()118
val valid = when (key) {119
case Mac(val secret) -> {120
requireMac(algorithm, secret)121
verifyHmac(DigestAlgorithm.Sha256, secret, input, signature)122
}123
case Signature(val publicKey) -> {124
val selected = signatureAlgorithm(algorithm)125
val der = if (algorithm == JwsAlgorithm.ES256) convertEcdsa(signature, false) else signature126
verify(selected, publicKey, input, der)127
}128
}129
return if (valid) Some(VerifiedJws(header, payload, parsed.keyId)) else None130
}132
private fun convertEcdsa(signature: Array<Byte>, toRaw: Boolean): Array<Byte> {133
if (!toRaw && signature.size != 64L) throw JwsException("ES256 signature must contain 64 bytes")134
@Unsafe { return signature.withDataPointer { data, count ->135
@Unsafe { return@withDataPointer cryptoBytes(ecdsaConvert(data, count, if (toRaw) 1 else 0), "convert ES256 signature") }136
} }137
}