• 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

96.47
/jsign-crypto/src/main/java/net/jsign/jca/AzureKeyVaultSigningService.java
1
/*
2
 * Copyright 2021 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.ArrayList;
29
import java.util.Base64;
30
import java.util.HashMap;
31
import java.util.List;
32
import java.util.Map;
33

34
import org.bouncycastle.asn1.DERNull;
35
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
36
import org.bouncycastle.asn1.x509.DigestInfo;
37

38
import net.jsign.DigestAlgorithm;
39

40
/**
41
 * Signing service using the Azure KeyVault API.
42
 *
43
 * @since 4.0
44
 * @see <a href="https://docs.microsoft.com/en-us/rest/api/keyvault/">Azure Key Vault REST API reference</a>
45
 */
46
public class AzureKeyVaultSigningService implements SigningService {
47

48
    /** Cache of certificates indexed by alias */
49
    private final Map<String, Map<String, ?>> certificates = new HashMap<>();
1 ✔
50

51
    private final RESTClient client;
52

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

71
    /**
72
     * Creates a new Azure Key Vault signing service.
73
     *
74
     * @param vault the name of the key vault, either the short name (e.g. <tt>myvault</tt>),
75
     *              or the full URL (e.g. <tt>https://myvault.vault.azure.net</tt>).
76
     * @param token the Azure API access token
77
     */
78
    public AzureKeyVaultSigningService(String vault, String token) {
79
        this(vault, new AzureCredentials(token));
1 ✔
80
    }
1 ✔
81

82
    /**
83
     * Creates a new Azure Key Vault signing service.
84
     *
85
     * @param vault       the name of the key vault, either the short name (e.g. <tt>myvault</tt>),
86
     *                    or the full URL (e.g. <tt>https://myvault.vault.azure.net</tt>).
87
     * @param credentials the Azure credentials used to fetch the API access token
88
     * @since 8.0
89
     */
90
    public AzureKeyVaultSigningService(String vault, AzureCredentials credentials) {
1 ✔
91
        if (!vault.startsWith("http")) {
1 ✔
92
            vault = "https://" + vault + ".vault.azure.net";
1 ✔
93
        }
94
        this.client = new RESTClient(vault)
1 ✔
95
                .authentication(conn -> {
1 ✔
96
                    try {
97
                        String token = credentials.getAccessToken("https://vault.azure.net");
1 ✔
98
                        conn.setRequestProperty("Authorization", "Bearer " + token);
1 ✔
99
                    } catch (IOException e) {
1 ✔
100
                        throw new RuntimeException("Unable to get the Azure API access token", e);
1 ✔
101
                    }
1 ✔
102
                })
1 ✔
103
                .errorHandler(response -> {
1 ✔
104
                    Map error = (Map) response.get("error");
1 ✔
105
                    return error.get("code") + ": " + error.get("message");
1 ✔
106
                });
107
    }
1 ✔
108

109
    @Override
110
    public String getName() {
111
        return "AzureKeyVault";
1 ✔
112
    }
113

114
    /**
115
     * Returns the certificate details
116
     *
117
     * @param alias the alias of the certificate
118
     */
119
    private Map<String, ?> getCertificateInfo(String alias) throws IOException {
120
        if (!certificates.containsKey(alias)) {
1 ✔
121
            Map<String, ?> response = client.get("/certificates/" + alias + "?api-version=7.2");
1 ✔
122
            certificates.put(alias, response);
1 ✔
123
        }
124

125
        return certificates.get(alias);
1 ✔
126
    }
127

128
    @Override
129
    public List<String> aliases() throws KeyStoreException {
130
        List<String> aliases = new ArrayList<>();
1 ✔
131

132
        try {
133
            Map<String, ?> response = client.get("/certificates?api-version=7.2");
1 ✔
134
            Object[] certificates = (Object[]) response.get("value");
1 ✔
135
            for (Object certificate : certificates) {
1 ✔
136
                String id = (String) ((Map) certificate).get("id");
1 ✔
137
                aliases.add(id.substring(id.lastIndexOf('/') + 1));
1 ✔
138
            }
139
        } catch (IOException e) {
1 ✔
140
            // return an empty list when called from the jarsigner JDK tool, because jarsigner fetches the aliases
141
            // even if unnecessary for signing and this requires extra permissions on the Azure account (see #219)
142
            if (!isCalledByJarSigner(e.getStackTrace())) {
1 ✔
143
                throw new KeyStoreException("Unable to retrieve Azure Key Vault certificate aliases", e);
1 ✔
144
            }
145
        }
1 ✔
146

147
        return aliases;
1 ✔
148
    }
149

150
    /**
151
     * Checks the stacktrace and tells if the calling class is the jarsigner tool.
152
     */
153
    private boolean isCalledByJarSigner(StackTraceElement[] trace) {
154
        for (StackTraceElement element : trace) {
1 ✔
155
            if (element.getClassName().contains("jarsigner")) {
1 ✔
156
                return true;
1 ✔
157
            }
158
        }
159
        return false;
1 ✔
160
    }
161

162
    @Override
163
    public Certificate[] getCertificateChain(String alias) throws KeyStoreException {
164
        try {
165
            Map<String, ?> response = getCertificateInfo(alias);
1 ✔
166
            String pem = (String) response.get("cer");
1 ✔
167

168
            Certificate certificate = CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(Base64.getDecoder().decode(pem)));
1 ✔
169
            return new Certificate[]{certificate};
1 ✔
170
        } catch (IOException | CertificateException e) {
1 ✔
171
            if (e.getMessage() != null && e.getMessage().contains("was not found in this key vault")) {
1 ✔
172
                return null;
×
173
            } else {
174
                throw new KeyStoreException("Unable to retrieve Azure Key Vault certificate '" + alias + "'", e);
1 ✔
175
            }
176
        }
177
    }
178

179
    @Override
180
    public SigningServicePrivateKey getPrivateKey(String alias, char[] password) throws UnrecoverableKeyException {
181
        try {
182
            Map<String, ?> response = getCertificateInfo(alias);
1 ✔
183
            String kid = (String) response.get("kid");
1 ✔
184
            Map policy = (Map) response.get("policy");
1 ✔
185
            Map keyprops = (Map) policy.get("key_props");
1 ✔
186
            String algorithm = ((String) keyprops.get("kty")).replace("-HSM", "");
1 ✔
187

188
            return new SigningServicePrivateKey(kid, algorithm, this);
1 ✔
189
        } catch (IOException e) {
1 ✔
190
            throw (UnrecoverableKeyException) new UnrecoverableKeyException("Unable to fetch Azure Key Vault private key for the certificate '" + alias + "'").initCause(e);
1 ✔
191
        }
192
    }
193

194
    @Override
195
    public byte[] sign(SigningServicePrivateKey privateKey, String algorithm, byte[] data) throws GeneralSecurityException {
196
        String alg = algorithmMapping.get(algorithm);
1 ✔
197
        if (alg == null) {
1 ✔
198
            throw new InvalidAlgorithmParameterException("Unsupported signing algorithm: " + algorithm);
1 ✔
199
        }
200

201
        DigestAlgorithm digestAlgorithm = DigestAlgorithm.of(algorithm.substring(0, algorithm.toLowerCase().indexOf("with")));
1 ✔
202
        data = digestAlgorithm.getMessageDigest().digest(data);
1 ✔
203

204
        if (alg.equals("RSNULL")) {
1 ✔
205
            AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(digestAlgorithm.oid, DERNull.INSTANCE);
1 ✔
206
            DigestInfo digestInfo = new DigestInfo(algorithmIdentifier, data);
1 ✔
207
            try {
208
                data = digestInfo.getEncoded("DER");
1 ✔
209
            } catch (IOException e) {
×
210
                throw new GeneralSecurityException(e);
×
211
            }
1 ✔
212
        }
213

214
        Map<String, String> request = new HashMap<>();
1 ✔
215
        request.put("alg", alg);
1 ✔
216
        request.put("value", Base64.getEncoder().encodeToString(data));
1 ✔
217

218
        try {
219
            Map<String, ?> response = client.post(privateKey.getId() + "/sign?api-version=7.2", JsonWriter.format(request));
1 ✔
220
            String value = (String) response.get("value");
1 ✔
221

222
            return Base64.getUrlDecoder().decode(value);
1 ✔
223
        } catch (IOException e) {
1 ✔
224
            throw new GeneralSecurityException(e);
1 ✔
225
        }
226
    }
227
}
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