• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

ebourg / jsign / #429

12 Oct 2026 08:24AM UTC coverage: 80.879% (+0.3%) from 80.604%
#429

push

ebourg
Release version 7.6

5080 of 6281 relevant lines covered (80.88%)

0.81 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

94.25
/jsign-crypto/src/main/java/net/jsign/jca/AzureTrustedSigningService.java
1
/*
2
 * Copyright 2024 Emmanuel Bourg
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *     http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16

17
package net.jsign.jca;
18

19
import java.io.ByteArrayInputStream;
20
import java.io.IOException;
21
import java.security.GeneralSecurityException;
22
import java.security.InvalidAlgorithmParameterException;
23
import java.security.KeyStoreException;
24
import java.security.UnrecoverableKeyException;
25
import java.security.cert.Certificate;
26
import java.security.cert.CertificateException;
27
import java.security.cert.CertificateFactory;
28
import java.util.Base64;
29
import java.util.Collection;
30
import java.util.Collections;
31
import java.util.HashMap;
32
import java.util.List;
33
import java.util.Map;
34

35
import net.jsign.DigestAlgorithm;
36

37
/**
38
 * Signing service using the Azure Trusted Signing API.
39
 *
40
 * @since 7.0
41
 */
42
public class AzureTrustedSigningService implements SigningService {
43

44
    /** Cache of certificate chains indexed by alias */
45
    private final Map<String, Certificate[]> certificates = new HashMap<>();
1 ✔
46

47
    private final RESTClient client;
48

49
    /** Timeout in seconds for the signing operation */
50
    private long timeout = 60;
1 ✔
51

52
    /**
53
     * Mapping between Java and Azure signing algorithms.
54
     * @see <a href="https://docs.microsoft.com/en-us/rest/api/keyvault/sign/sign#jsonwebkeysignaturealgorithm">Key Vault API - JsonWebKeySignatureAlgorithm</a>
55
     */
56
    private final Map<String, String> algorithmMapping = new HashMap<>();
1 ✔
57
    {
58
        algorithmMapping.put("SHA256withRSA", "RS256");
1 ✔
59
        algorithmMapping.put("SHA384withRSA", "RS384");
1 ✔
60
        algorithmMapping.put("SHA512withRSA", "RS512");
1 ✔
61
        algorithmMapping.put("SHA256withECDSA", "ES256");
1 ✔
62
        algorithmMapping.put("SHA384withECDSA", "ES384");
1 ✔
63
        algorithmMapping.put("SHA512withECDSA", "ES512");
1 ✔
64
        algorithmMapping.put("SHA256withRSA/PSS", "PS256");
1 ✔
65
        algorithmMapping.put("SHA384withRSA/PSS", "PS384");
1 ✔
66
        algorithmMapping.put("SHA512withRSA/PSS", "PS512");
1 ✔
67
    }
68

69
    /**
70
     * Creates a new Azure Artifact Signing service.
71
     *
72
     * @param endpoint the API endpoint (e.g. <tt>weu.codesigning.azure.net</tt>)
73
     * @param token    the Azure API access token
74
     */
75
    public AzureTrustedSigningService(String endpoint, String token) {
76
        this(endpoint, new AzureCredentials(token));
1 ✔
77
    }
1 ✔
78

79
    /**
80
     * Creates a new Azure Artifact Signing service.
81
     *
82
     * @param endpoint    the API endpoint (e.g. <tt>weu.codesigning.azure.net</tt>)
83
     * @param credentials the Azure credentials used to fetch the API access token
84
     * @since 8.0
85
     */
86
    public AzureTrustedSigningService(String endpoint, AzureCredentials credentials) {
1 ✔
87
        if (!endpoint.startsWith("http")) {
1 ✔
88
            endpoint = "https://" + endpoint;
×
89
        }
90
        endpoint = endpoint.replaceFirst("/+$", "");
1 ✔
91
        client = new RESTClient(endpoint)
1 ✔
92
                .authentication(conn -> {
1 ✔
93
                    try {
94
                        String token = credentials.getAccessToken("https://codesigning.azure.net");
1 ✔
95
                        conn.setRequestProperty("Authorization", "Bearer " + token);
1 ✔
96
                    } catch (IOException e) {
1 ✔
97
                        throw new RuntimeException("Unable to get the Azure API access token", e);
1 ✔
98
                    }
1 ✔
99
                })
1 ✔
100
                .errorHandler(response -> {
1 ✔
101
                    if (response.containsKey("errorDetail")) {
1 ✔
102
                        Map error = (Map) response.get("errorDetail");
1 ✔
103
                        return error.get("code") + " - " + error.get("message");
1 ✔
104
                    } else {
105
                        String errors = JsonWriter.format(response.get("errors"));
×
106
                        return response.get("status") + " - " + response.get("title") + ": " + errors;
×
107
                    }
108
                });
109
    }
1 ✔
110

111
    void setTimeout(int timeout) {
112
        this.timeout = timeout;
1 ✔
113
    }
1 ✔
114

115
    @Override
116
    public String getName() {
117
        return "TrustedSigning";
1 ✔
118
    }
119

120
    @Override
121
    public List<String> aliases() throws KeyStoreException {
122
        return Collections.emptyList();
1 ✔
123
    }
124

125
    @Override
126
    public Certificate[] getCertificateChain(String alias) throws KeyStoreException {
127
        if (!certificates.containsKey(alias)) {
1 ✔
128
            try {
129
                String account = alias.substring(0, alias.indexOf('/'));
1 ✔
130
                String profile = alias.substring(alias.indexOf('/') + 1);
1 ✔
131
                SignStatus status = sign(account, profile, "RS256", new byte[32]);
1 ✔
132
                certificates.put(alias, status.getCertificateChain().toArray(new Certificate[0]));
1 ✔
133
            } catch (Exception e) {
1 ✔
134
                throw new KeyStoreException("Unable to retrieve the certificate chain '" + alias + "'", e);
1 ✔
135
            }
1 ✔
136
        }
137

138
        return certificates.get(alias);
1 ✔
139
    }
140

141
    @Override
142
    public SigningServicePrivateKey getPrivateKey(String alias, char[] password) throws UnrecoverableKeyException {
143
        return new SigningServicePrivateKey(alias, "RSA", this);
1 ✔
144
    }
145

146
    @Override
147
    public byte[] sign(SigningServicePrivateKey privateKey, String algorithm, byte[] data) throws GeneralSecurityException {
148
        String alg = algorithmMapping.get(algorithm);
1 ✔
149
        if (alg == null) {
1 ✔
150
            throw new InvalidAlgorithmParameterException("Unsupported signing algorithm: " + algorithm);
1 ✔
151
        }
152

153
        DigestAlgorithm digestAlgorithm = DigestAlgorithm.of(algorithm.substring(0, algorithm.toLowerCase().indexOf("with")));
1 ✔
154
        data = digestAlgorithm.getMessageDigest().digest(data);
1 ✔
155

156
        String alias = privateKey.getId();
1 ✔
157
        String account = alias.substring(0, alias.indexOf('/'));
1 ✔
158
        String profile = alias.substring(alias.indexOf('/') + 1);
1 ✔
159
        try {
160
            SignStatus status = sign(account, profile, alg, data);
1 ✔
161
            return status.signature;
1 ✔
162
        } catch (IOException e) {
1 ✔
163
            throw new GeneralSecurityException(e);
1 ✔
164
        }
165
    }
166

167
    private SignStatus sign(String account, String profile, String algorithm, byte[] data) throws IOException {
168
        Map<String, Object> request = new HashMap<>();
1 ✔
169
        request.put("signatureAlgorithm", algorithm);
1 ✔
170
        request.put("digest", Base64.getEncoder().encodeToString(data));
1 ✔
171

172
        Map<String, ?> response = client.post("/codesigningaccounts/" + account + "/certificateprofiles/" + profile + "/sign?api-version=2022-06-15-preview", JsonWriter.format(request));
1 ✔
173

174
        String operationId = (String) response.get("operationId");
1 ✔
175

176
        // poll until the operation is completed
177
        long startTime = System.currentTimeMillis();
1 ✔
178
        int i = 0;
1 ✔
179
        while (System.currentTimeMillis() - startTime < timeout * 1000) {
1 ✔
180
            try {
181
                Thread.sleep(Math.min(1000, 50 + 10 * i++));
1 ✔
182
            } catch (InterruptedException e) {
×
183
                break;
×
184
            }
1 ✔
185
            response = client.get("/codesigningaccounts/" + account + "/certificateprofiles/" + profile + "/sign/" + operationId + "?api-version=2022-06-15-preview");
1 ✔
186
            String status = (String) response.get("status");
1 ✔
187
            if ("InProgress".equals(status)) {
1 ✔
188
                continue;
1 ✔
189
            }
190
            if ("Succeeded".equals(status)) {
1 ✔
191
                break;
1 ✔
192
            }
193

194
            throw new IOException("Signing operation " + operationId + " failed: " + status);
1 ✔
195
        }
196

197
        if (!"Succeeded".equals(response.get("status"))) {
1 ✔
198
            throw new IOException("Signing operation " + operationId + " timed out");
1 ✔
199
        }
200

201
        SignStatus status = new SignStatus();
1 ✔
202
        status.signature = Base64.getDecoder().decode((String) response.get("signature"));
1 ✔
203
        status.signingCertificate = new String(Base64.getDecoder().decode((String) response.get("signingCertificate")));
1 ✔
204

205
        return status;
1 ✔
206
    }
207

208
    private static class SignStatus {
209
        public byte[] signature;
210
        public String signingCertificate;
211

212
        public Collection<? extends Certificate> getCertificateChain() throws CertificateException {
213
            byte[] cerbin = Base64.getMimeDecoder().decode(signingCertificate);
1 ✔
214

215
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
1 ✔
216
            return certificateFactory.generateCertificates(new ByteArrayInputStream(cerbin));
1 ✔
217
        }
218
    }
219
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc