|
| 1 | +package io.github.intoto.dsse.helpers; |
| 2 | + |
| 3 | +import dev.sigstore.KeylessSigner; |
| 4 | +import dev.sigstore.KeylessSignerException; |
| 5 | +import dev.sigstore.bundle.Bundle; |
| 6 | +import io.github.intoto.dsse.models.Signer; |
| 7 | + |
| 8 | +import java.io.IOException; |
| 9 | +import java.nio.charset.StandardCharsets; |
| 10 | +import java.security.*; |
| 11 | +import java.security.cert.CertificateException; |
| 12 | +import java.security.cert.X509Certificate; |
| 13 | +import java.security.spec.InvalidKeySpecException; |
| 14 | +import java.util.Optional; |
| 15 | + |
| 16 | +public class SimpleSigstoreSigner implements Signer { |
| 17 | + private String keyId; |
| 18 | + Optional<Bundle.DSSESignature> dsseSignature; |
| 19 | + Bundle result; |
| 20 | + |
| 21 | + public byte[] sign(byte[] payload) throws InvalidAlgorithmParameterException, CertificateException, IOException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, KeylessSignerException { |
| 22 | + KeylessSigner functionary = new KeylessSigner.Builder().sigstorePublicDefaults().build(); |
| 23 | + this.result = functionary.sign(payload); |
| 24 | + |
| 25 | + // set keyId |
| 26 | + X509Certificate certificate = (X509Certificate) (this.result.getCertPath().getCertificates().getFirst()); |
| 27 | + String oid = "1.3.6.1.4.1.57264.1.8"; |
| 28 | + byte[] extensionValue = certificate.getExtensionValue(oid); |
| 29 | + String issuer = new String(extensionValue, StandardCharsets.UTF_8); |
| 30 | + this.keyId = issuer.substring(4); |
| 31 | + Object subAltArr = certificate.getSubjectAlternativeNames().toArray()[0]; |
| 32 | + String subAltName = subAltArr.toString(); |
| 33 | + subAltName = subAltName.substring(4, subAltName.length() - 1); |
| 34 | + this.keyId = keyId.concat(" " + subAltName); |
| 35 | + |
| 36 | + this.dsseSignature = result.getDSSESignature(); |
| 37 | + return dsseSignature.get().getSignature(); |
| 38 | + } |
| 39 | + |
| 40 | + @Override |
| 41 | + public String getKeyId() { |
| 42 | + if (this.keyId.isEmpty()) { |
| 43 | + throw new RuntimeException("Sign the artifact to initialize keyId"); |
| 44 | + } |
| 45 | + return this.keyId; |
| 46 | + } |
| 47 | + |
| 48 | + public byte[] getPayload() { |
| 49 | + if (this.dsseSignature.isEmpty()) { |
| 50 | + throw new RuntimeException("Cannot retrieve and unsigned payload"); |
| 51 | + } |
| 52 | + return this.dsseSignature.get().getPayload().getBytes(StandardCharsets.UTF_8); |
| 53 | + } |
| 54 | + |
| 55 | + public Bundle getResult() { |
| 56 | + return this.result; |
| 57 | + } |
| 58 | +} |
0 commit comments