1 22 package org.jboss.test.security.interceptors; 23 24 import java.io.Serializable ; 25 import java.security.GeneralSecurityException ; 26 import java.security.InvalidAlgorithmParameterException ; 27 import java.util.Iterator ; 28 import java.util.Set ; 29 import javax.crypto.Cipher; 30 import javax.crypto.SealedObject; 31 import javax.crypto.SecretKey; 32 import javax.crypto.spec.IvParameterSpec; 33 import javax.security.auth.Subject ; 34 35 import org.jboss.logging.Logger; 36 37 import org.jboss.invocation.Invocation; 38 import org.jboss.proxy.Interceptor; 39 import org.jboss.security.SecurityAssociation; 40 import org.jboss.security.srp.SRPParameters; 41 42 47 public class ClientEncryptionInterceptor 48 extends Interceptor 49 { 50 51 private Cipher encryptCipher; 52 private Cipher decryptCipher; 53 private Logger log = Logger.getLogger(ClientEncryptionInterceptor.class); 54 55 56 public ClientEncryptionInterceptor() 57 { 58 } 59 60 public Object invoke(Invocation mi) throws Throwable 61 { 62 if( encryptCipher == null ) 63 { 64 Subject subject = SecurityAssociation.getSubject(); 65 initCipher(subject); 66 } 67 68 log.debug("invoke mi="+mi.getMethod()); 69 Object [] args = mi.getArguments(); 71 int length = args != null ? args.length : 0; 72 for(int a = 0; a < length; a ++) 73 { 74 if( (args[a] instanceof Serializable ) == false ) 75 continue; 76 Serializable arg = (Serializable ) args[a]; 77 SealedObject sarg = new SealedObject(arg, encryptCipher); 78 args[a] = sarg; 79 log.debug(" Sealed arg("+a+"): "+arg); 80 } 81 82 Interceptor next = getNext(); 83 Object value = next.invoke(mi); 84 if( value instanceof SealedObject ) 85 { 86 SealedObject svalue = (SealedObject) value; 87 value = svalue.getObject(decryptCipher); 88 } 89 return value; 90 } 91 92 private void initCipher(Subject subject) throws GeneralSecurityException 93 { 94 Set credentials = subject.getPrivateCredentials(SecretKey.class); 95 Iterator iter = credentials.iterator(); 96 SecretKey key = null; 97 while( iter.hasNext() ) 98 { 99 key = (SecretKey) iter.next(); 100 } 101 if( key == null ) 102 { 103 System.out.println("Subject: "+subject); 104 throw new GeneralSecurityException ("Failed to find SecretKey in Subject.PrivateCredentials"); 105 } 106 107 credentials = subject.getPrivateCredentials(SRPParameters.class); 108 iter = credentials.iterator(); 109 SRPParameters params = null; 110 while( iter.hasNext() ) 111 { 112 params = (SRPParameters) iter.next(); 113 } 114 if( params == null ) 115 throw new GeneralSecurityException ("Failed to find SRPParameters in Subject.PrivateCredentials"); 116 117 encryptCipher = Cipher.getInstance(key.getAlgorithm()); 118 encryptCipher.init(Cipher.ENCRYPT_MODE, key); 119 decryptCipher = Cipher.getInstance(key.getAlgorithm()); 120 decryptCipher.init(Cipher.DECRYPT_MODE, key); 121 } 122 } 123 | Popular Tags |