1
2
3
4
5
6
7 package org.mule.module.pgp;
8
9 import org.mule.api.lifecycle.InitialisationException;
10 import org.mule.api.security.Authentication;
11 import org.mule.api.security.SecurityException;
12 import org.mule.api.security.UnauthorisedException;
13 import org.mule.config.i18n.CoreMessages;
14 import org.mule.module.pgp.i18n.PGPMessages;
15 import org.mule.security.AbstractSecurityProvider;
16
17 import org.bouncycastle.jce.provider.BouncyCastleProvider;
18 import org.bouncycastle.openpgp.PGPPublicKey;
19
20 public class PGPSecurityProvider extends AbstractSecurityProvider
21 {
22 private PGPKeyRing keyManager;
23
24 public PGPSecurityProvider()
25 {
26 super("pgp");
27 }
28
29 public Authentication authenticate(Authentication authentication) throws SecurityException
30 {
31 PGPAuthentication auth = (PGPAuthentication) authentication;
32
33 String userId = (String) auth.getPrincipal();
34
35 if (userId == null)
36 {
37 throw new UnauthorisedException(CoreMessages.objectIsNull("UserId"));
38 }
39
40 PGPPublicKey publicKey = keyManager.getPublicKey(userId);
41
42 if (publicKey == null)
43 {
44 throw new UnauthorisedException(PGPMessages.noPublicKeyForUser(userId));
45 }
46
47 Message msg = (Message) auth.getCredentials();
48
49 if (msg instanceof SignedMessage)
50 {
51 try
52 {
53 if (!((SignedMessage) msg).verify())
54 {
55 throw new UnauthorisedException(PGPMessages.invalidSignature());
56 }
57 }
58 catch (Exception e)
59 {
60 throw new UnauthorisedException(PGPMessages.errorVerifySignature(), e);
61 }
62 }
63
64 auth.setAuthenticated(true);
65 auth.setDetails(publicKey);
66
67 return auth;
68 }
69
70 @Override
71 public boolean supports(Class aClass)
72 {
73 return PGPAuthentication.class.isAssignableFrom(aClass);
74 }
75
76 @Override
77 protected void doInitialise() throws InitialisationException
78 {
79 try
80 {
81 java.security.Security.addProvider(new BouncyCastleProvider());
82 setSecurityContextFactory(new PGPSecurityContextFactory());
83 }
84 catch (Exception e)
85 {
86 throw new InitialisationException(CoreMessages.failedToCreate("PGPProvider"), e, this);
87 }
88 }
89
90 public PGPKeyRing getKeyManager()
91 {
92 return keyManager;
93 }
94
95 public void setKeyManager(PGPKeyRing keyManager)
96 {
97 this.keyManager = keyManager;
98 }
99 }