1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.bitrepository.protocol.security;
23
24 import java.security.cert.X509Certificate;
25
26 import org.bitrepository.protocol.security.exception.MessageAuthenticationException;
27 import org.bitrepository.protocol.security.exception.PermissionStoreException;
28 import org.bitrepository.protocol.security.exception.SecurityException;
29 import org.bouncycastle.cms.CMSException;
30 import org.bouncycastle.cms.CMSProcessableByteArray;
31 import org.bouncycastle.cms.CMSSignedData;
32 import org.bouncycastle.cms.SignerInformation;
33 import org.bouncycastle.cms.SignerInformationVerifier;
34 import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder;
35 import org.bouncycastle.operator.OperatorCreationException;
36
37
38
39
40 public class BasicMessageAuthenticator implements MessageAuthenticator {
41
42
43
44
45 private final PermissionStore permissionStore;
46
47
48
49
50 public BasicMessageAuthenticator(PermissionStore permissionStore) {
51 this.permissionStore = permissionStore;
52 }
53
54
55
56
57
58
59
60 @Override
61 public void authenticateMessage(byte[] messageData, byte[] signatureData) throws MessageAuthenticationException {
62 try {
63 CMSSignedData s = new CMSSignedData(new CMSProcessableByteArray(messageData), signatureData);
64 SignerInformation signer = (SignerInformation) s.getSignerInfos().getSigners().iterator().next();
65 X509Certificate signingCert = permissionStore.getCertificate(signer.getSID());
66 SignerInformationVerifier verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider(
67 SecurityModuleConstants.BC).build(signingCert);
68
69 if(!signer.verify(verifier)) {
70 throw new MessageAuthenticationException("Signature does not match the message. Indicated " +
71 "certificate did not sign message. Certificate issuer: "
72 + signingCert.getIssuerX500Principal().getName() + ", serial: "
73 + signingCert.getSerialNumber());
74 }
75 } catch (PermissionStoreException e) {
76 throw new MessageAuthenticationException(e.getMessage(), e);
77 } catch (CMSException e) {
78 throw new SecurityException(e.getMessage(), e);
79 } catch (OperatorCreationException e) {
80 throw new SecurityException(e.getMessage(), e);
81 }
82 }
83 }