List of usage examples for java.security Signature initSign
public final void initSign(PrivateKey privateKey) throws InvalidKeyException
From source file:org.wso2.carbon.appmgt.impl.token.JWTGenerator.java
/** * Helper method to sign the JWT/*w w w .ja va 2 s . co m*/ * * @param assertion * @param endUserName * @return signed assertion * @throws org.wso2.carbon.appmgt.api.AppManagementException */ private byte[] signJWT(String assertion, String endUserName) throws AppManagementException { try { //get tenant domain String tenantDomain = MultitenantUtils.getTenantDomain(endUserName); //get tenantId int tenantId = getTenantId(endUserName); Key privateKey = null; if (!(privateKeys.containsKey(tenantId))) { AppManagerUtil.loadTenantRegistry(tenantId); //get tenant's key store manager KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId); if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { //derive key store name String ksName = tenantDomain.trim().replace(".", "-"); String jksName = ksName + ".jks"; //obtain private key //TODO: maintain a hash map with tenants' private keys after first initialization privateKey = tenantKSM.getPrivateKey(jksName, tenantDomain); } else { try { privateKey = tenantKSM.getDefaultPrivateKey(); } catch (Exception e) { log.error("Error while obtaining private key for super tenant", e); } } if (privateKey != null) { privateKeys.put(tenantId, privateKey); } } else { privateKey = privateKeys.get(tenantId); } //initialize signature with private key and algorithm Signature signature = Signature.getInstance(signatureAlgorithm); signature.initSign((PrivateKey) privateKey); //update signature with data to be signed byte[] dataInBytes = assertion.getBytes(); signature.update(dataInBytes); //sign the assertion and return the signature byte[] signedInfo = signature.sign(); return signedInfo; } catch (NoSuchAlgorithmException e) { String error = "Signature algorithm not found."; //do not log throw new AppManagementException(error); } catch (InvalidKeyException e) { String error = "Invalid private key provided for the signature"; //do not log throw new AppManagementException(error); } catch (SignatureException e) { String error = "Error in signature"; //do not log throw new AppManagementException(error); } catch (AppManagementException e) { //do not log throw new AppManagementException(e.getMessage()); } }
From source file:com.taobao.android.builder.tools.sign.LocalSignedJarBuilder.java
/** * Closes the Jar archive by creating the manifest, and signing the archive. * * @throws IOException//from w ww. ja va2 s. c om * @throws SigningException */ public void close() throws IOException, SigningException { if (mManifest != null) { // write the manifest to the jar file mOutputJar.putNextEntry(new JarEntry(JarFile.MANIFEST_NAME)); mManifest.write(mOutputJar); try { // CERT.SF Signature signature = Signature.getInstance("SHA1with" + mKey.getAlgorithm()); signature.initSign(mKey); if (StringUtils.isBlank(mSignFile)) { mOutputJar.putNextEntry(new JarEntry("META-INF/CERT.SF")); } else { mOutputJar.putNextEntry(new JarEntry("META-INF/" + mSignFile + ".SF")); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); writeSignatureFile(baos); byte[] signedData = baos.toByteArray(); mOutputJar.write(signedData); if (StringUtils.isBlank(mSignFile)) { mOutputJar.putNextEntry(new JarEntry("META-INF/CERT." + mKey.getAlgorithm())); } else { mOutputJar.putNextEntry(new JarEntry("META-INF/" + mSignFile + "." + mKey.getAlgorithm())); } // CERT.* writeSignatureBlock(new CMSProcessableByteArray(signedData), mCertificate, mKey); } catch (Exception e) { throw new SigningException(e); } } mOutputJar.close(); mOutputJar = null; }
From source file:org.alfresco.extension.countersign.signature.RepositoryManagedSignatureProvider.java
/** * Sign a hash using the user's private key * //from www. j av a 2 s. c o m * @param hash * @param key * @return * @throws Exception */ public byte[] signHash(byte[] hash, String password) throws Exception { String alg = config.getProperty(RepositoryManagedSignatureProviderFactory.SIGNATURE_ALGORITHM); String prov = config.getProperty(RepositoryManagedSignatureProviderFactory.JAVA_SIGNATURE_PROVIDER); String alias = config.getProperty(RepositoryManagedSignatureProviderFactory.ALIAS); KeyStore ks = getUserKeyStore(password); PrivateKey key = (PrivateKey) ks.getKey(alias, password.toCharArray()); Signature signer = Signature.getInstance(alg, prov); signer.initSign(key); signer.update(hash); return signer.sign(); }
From source file:uk.bowdlerize.API.java
@Deprecated private String SignHeaders(String dataToSign, boolean isUser) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, NoSuchProviderException, SignatureException { PKCS8EncodedKeySpec spec;/* ww w. j a va 2 s . c om*/ if (isUser) { spec = new PKCS8EncodedKeySpec( Base64.decode(settings.getString(SETTINGS_USER_PRIVATE_KEY, "").getBytes(), 0)); } else { spec = new PKCS8EncodedKeySpec( Base64.decode(settings.getString(SETTINGS_PROBE_PRIVATE_KEY, "").getBytes(), 0)); } KeyFactory kf = KeyFactory.getInstance("RSA", "BC"); PrivateKey pk = kf.generatePrivate(spec); byte[] signed = null; //Log.e("algorithm", pk.getAlgorithm()); Signature instance = Signature.getInstance("SHA1withRSA"); instance.initSign(pk); instance.update(dataToSign.getBytes()); signed = instance.sign(); Log.e("privateKey", settings.getString(SETTINGS_USER_PRIVATE_KEY, "")); Log.e("privateKey", settings.getString(SETTINGS_PROBE_PRIVATE_KEY, "")); //Log.e("Signature",Base64.encodeToString(signed, Base64.NO_WRAP)); return Base64.encodeToString(signed, Base64.NO_WRAP); }
From source file:test.unit.be.fedict.eid.applet.service.AuthenticationDataMessageHandlerTest.java
public void testHandleMessage() throws Exception { // setup//from w ww. j a v a 2 s. c o m KeyPair keyPair = MiscTestUtils.generateKeyPair(); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusYears(1); String userId = "1234"; X509Certificate certificate = MiscTestUtils.generateCertificate(keyPair.getPublic(), "CN=Test, SERIALNUMBER=" + userId, notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null, null); byte[] salt = "salt".getBytes(); byte[] sessionId = "session-id".getBytes(); AuthenticationDataMessage message = new AuthenticationDataMessage(); message.authnCert = certificate; message.saltValue = salt; message.sessionId = sessionId; Map<String, String> httpHeaders = new HashMap<String, String>(); HttpSession testHttpSession = new HttpTestSession(); HttpServletRequest mockServletRequest = EasyMock.createMock(HttpServletRequest.class); ServletConfig mockServletConfig = EasyMock.createMock(ServletConfig.class); byte[] challenge = AuthenticationChallenge.generateChallenge(testHttpSession); AuthenticationContract authenticationContract = new AuthenticationContract(salt, null, null, sessionId, null, challenge); byte[] toBeSigned = authenticationContract.calculateToBeSigned(); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(keyPair.getPrivate()); signature.update(toBeSigned); byte[] signatureValue = signature.sign(); message.signatureValue = signatureValue; EasyMock.expect(mockServletConfig .getInitParameter(AuthenticationDataMessageHandler.CHALLENGE_MAX_MATURITY_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.AUTHN_SERVICE_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig .getInitParameter(AuthenticationDataMessageHandler.AUTHN_SERVICE_INIT_PARAM_NAME + "Class")) .andReturn(AuthenticationTestService.class.getName()); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.HOSTNAME_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INET_ADDRESS_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.AUDIT_SERVICE_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig .getInitParameter(AuthenticationDataMessageHandler.AUDIT_SERVICE_INIT_PARAM_NAME + "Class")) .andReturn(AuditTestService.class.getName()); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVER_CERTIFICATE)) .andStubReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(HelloMessageHandler.SESSION_ID_CHANNEL_BINDING_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_SECRET_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_IDENTITY_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_CERTS_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_ADDRESS_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_PHOTO_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(HelloMessageHandler.IDENTITY_INTEGRITY_SERVICE_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig .getInitParameter(HelloMessageHandler.IDENTITY_INTEGRITY_SERVICE_INIT_PARAM_NAME + "Class")) .andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVICE)) .andReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVICE + "Class")) .andReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_ORG_ID_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_APP_ID_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig .getInitParameter(AuthenticationDataMessageHandler.AUTHN_SIGNATURE_SERVICE_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig.getInitParameter( AuthenticationDataMessageHandler.AUTHN_SIGNATURE_SERVICE_INIT_PARAM_NAME + "Class")) .andReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(IdentityDataMessageHandler.INCLUDE_DATA_FILES)) .andReturn(null); EasyMock.expect(mockServletRequest.getAttribute("javax.servlet.request.ssl_session")) .andStubReturn(new String(Hex.encodeHex(sessionId))); EasyMock.expect(mockServletRequest.getRemoteAddr()).andStubReturn("1.2.3.4"); // prepare EasyMock.replay(mockServletRequest, mockServletConfig); // operate AppletServiceServlet.injectInitParams(mockServletConfig, this.testedInstance); this.testedInstance.init(mockServletConfig); this.testedInstance.handleMessage(message, httpHeaders, mockServletRequest, testHttpSession); // verify EasyMock.verify(mockServletRequest, mockServletConfig); assertTrue(AuthenticationTestService.isCalled()); assertEquals(userId, AuditTestService.getAuditUserId()); assertEquals(userId, testHttpSession.getAttribute("eid.identifier")); }
From source file:test.unit.be.fedict.eid.applet.service.AuthenticationDataMessageHandlerTest.java
public void testHandleMessageWithoutAuditService() throws Exception { // setup/*from ww w .j a v a 2 s . c o m*/ KeyPair keyPair = MiscTestUtils.generateKeyPair(); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusYears(1); String userId = "1234"; X509Certificate certificate = MiscTestUtils.generateCertificate(keyPair.getPublic(), "CN=Test, SERIALNUMBER=" + userId, notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null, null); byte[] salt = "salt".getBytes(); byte[] sessionId = "session-id".getBytes(); AuthenticationDataMessage message = new AuthenticationDataMessage(); message.authnCert = certificate; message.saltValue = salt; message.sessionId = sessionId; Map<String, String> httpHeaders = new HashMap<String, String>(); HttpSession testHttpSession = new HttpTestSession(); HttpServletRequest mockServletRequest = EasyMock.createMock(HttpServletRequest.class); ServletConfig mockServletConfig = EasyMock.createMock(ServletConfig.class); byte[] challenge = AuthenticationChallenge.generateChallenge(testHttpSession); AuthenticationContract authenticationContract = new AuthenticationContract(salt, null, null, sessionId, null, challenge); byte[] toBeSigned = authenticationContract.calculateToBeSigned(); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(keyPair.getPrivate()); signature.update(toBeSigned); byte[] signatureValue = signature.sign(); message.signatureValue = signatureValue; EasyMock.expect(mockServletConfig .getInitParameter(AuthenticationDataMessageHandler.CHALLENGE_MAX_MATURITY_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.AUTHN_SERVICE_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig .getInitParameter(AuthenticationDataMessageHandler.AUTHN_SERVICE_INIT_PARAM_NAME + "Class")) .andReturn(AuthenticationTestService.class.getName()); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.HOSTNAME_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INET_ADDRESS_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVER_CERTIFICATE)) .andStubReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(HelloMessageHandler.SESSION_ID_CHANNEL_BINDING_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.AUDIT_SERVICE_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_SECRET_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig .getInitParameter(AuthenticationDataMessageHandler.AUDIT_SERVICE_INIT_PARAM_NAME + "Class")) .andReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_IDENTITY_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_CERTS_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_ADDRESS_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_PHOTO_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(HelloMessageHandler.IDENTITY_INTEGRITY_SERVICE_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig .getInitParameter(HelloMessageHandler.IDENTITY_INTEGRITY_SERVICE_INIT_PARAM_NAME + "Class")) .andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVICE)) .andReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVICE + "Class")) .andReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_ORG_ID_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_APP_ID_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig .getInitParameter(AuthenticationDataMessageHandler.AUTHN_SIGNATURE_SERVICE_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig.getInitParameter( AuthenticationDataMessageHandler.AUTHN_SIGNATURE_SERVICE_INIT_PARAM_NAME + "Class")) .andReturn(null); EasyMock.expect(mockServletRequest.getAttribute("javax.servlet.request.ssl_session")) .andStubReturn(new String(Hex.encodeHex(sessionId))); EasyMock.expect(mockServletConfig.getInitParameter(IdentityDataMessageHandler.INCLUDE_DATA_FILES)) .andReturn(null); EasyMock.expect(mockServletRequest.getRemoteAddr()).andStubReturn("1.2.3.4"); // prepare EasyMock.replay(mockServletRequest, mockServletConfig); // operate AppletServiceServlet.injectInitParams(mockServletConfig, this.testedInstance); this.testedInstance.init(mockServletConfig); this.testedInstance.handleMessage(message, httpHeaders, mockServletRequest, testHttpSession); // verify EasyMock.verify(mockServletRequest, mockServletConfig); assertTrue(AuthenticationTestService.isCalled()); assertNull(AuditTestService.getAuditUserId()); assertEquals(userId, testHttpSession.getAttribute("eid.identifier")); }
From source file:test.unit.be.fedict.eid.applet.service.AuthenticationDataMessageHandlerTest.java
public void testHandleMessageNRCID() throws Exception { // setup/*from w w w.j a va 2 s . c om*/ KeyPair keyPair = MiscTestUtils.generateKeyPair(); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusYears(1); String userId = "1234"; X509Certificate certificate = MiscTestUtils.generateCertificate(keyPair.getPublic(), "CN=Test, SERIALNUMBER=" + userId, notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null, null); byte[] salt = "salt".getBytes(); byte[] sessionId = "session-id".getBytes(); AuthenticationDataMessage message = new AuthenticationDataMessage(); message.authnCert = certificate; message.saltValue = salt; message.sessionId = sessionId; Map<String, String> httpHeaders = new HashMap<String, String>(); HttpSession testHttpSession = new HttpTestSession(); HttpServletRequest mockServletRequest = EasyMock.createMock(HttpServletRequest.class); ServletConfig mockServletConfig = EasyMock.createMock(ServletConfig.class); byte[] challenge = AuthenticationChallenge.generateChallenge(testHttpSession); AuthenticationContract authenticationContract = new AuthenticationContract(salt, null, null, sessionId, null, challenge); byte[] toBeSigned = authenticationContract.calculateToBeSigned(); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(keyPair.getPrivate()); signature.update(toBeSigned); byte[] signatureValue = signature.sign(); message.signatureValue = signatureValue; EasyMock.expect(mockServletConfig .getInitParameter(AuthenticationDataMessageHandler.CHALLENGE_MAX_MATURITY_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.AUTHN_SERVICE_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig .getInitParameter(AuthenticationDataMessageHandler.AUTHN_SERVICE_INIT_PARAM_NAME + "Class")) .andReturn(AuthenticationTestService.class.getName()); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.HOSTNAME_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INET_ADDRESS_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.AUDIT_SERVICE_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig .getInitParameter(AuthenticationDataMessageHandler.AUDIT_SERVICE_INIT_PARAM_NAME + "Class")) .andReturn(AuditTestService.class.getName()); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVER_CERTIFICATE)) .andStubReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(HelloMessageHandler.SESSION_ID_CHANNEL_BINDING_INIT_PARAM_NAME)) .andStubReturn(null); String nrcidSecret = "112233445566778899AABBCCDDEEFF00112233445566778899"; EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_SECRET_INIT_PARAM_NAME)) .andStubReturn(nrcidSecret); String nrcidAppId = "my-app-id"; EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_APP_ID_INIT_PARAM_NAME)) .andStubReturn(nrcidAppId); String nrcidOrgId = "my-org-id"; EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_ORG_ID_INIT_PARAM_NAME)) .andStubReturn(nrcidOrgId); EasyMock.expect(mockServletRequest.getAttribute("javax.servlet.request.ssl_session")) .andStubReturn(new String(Hex.encodeHex(sessionId))); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_IDENTITY_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_CERTS_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_ADDRESS_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_PHOTO_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(HelloMessageHandler.IDENTITY_INTEGRITY_SERVICE_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig .getInitParameter(HelloMessageHandler.IDENTITY_INTEGRITY_SERVICE_INIT_PARAM_NAME + "Class")) .andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVICE)) .andReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVICE + "Class")) .andReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(IdentityDataMessageHandler.INCLUDE_DATA_FILES)) .andReturn(null); EasyMock.expect(mockServletRequest.getRemoteAddr()).andStubReturn("1.2.3.4"); EasyMock.expect(mockServletConfig .getInitParameter(AuthenticationDataMessageHandler.AUTHN_SIGNATURE_SERVICE_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig.getInitParameter( AuthenticationDataMessageHandler.AUTHN_SIGNATURE_SERVICE_INIT_PARAM_NAME + "Class")) .andReturn(null); // prepare EasyMock.replay(mockServletRequest, mockServletConfig); // operate AppletServiceServlet.injectInitParams(mockServletConfig, this.testedInstance); this.testedInstance.init(mockServletConfig); this.testedInstance.handleMessage(message, httpHeaders, mockServletRequest, testHttpSession); // verify EasyMock.verify(mockServletRequest, mockServletConfig); assertTrue(AuthenticationTestService.isCalled()); String nrcid = UserIdentifierUtil.getNonReversibleCitizenIdentifier(userId, nrcidOrgId, nrcidAppId, nrcidSecret); assertTrue(nrcid.equals(AuditTestService.getAuditUserId())); assertTrue(nrcid.equals(testHttpSession.getAttribute("eid.identifier"))); }
From source file:test.unit.be.fedict.eid.applet.service.AuthenticationDataMessageHandlerTest.java
@Test public void testHandleMessageExpiredChallenge() throws Exception { // setup//from ww w .ja v a2s. c o m KeyPair keyPair = MiscTestUtils.generateKeyPair(); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusYears(1); String userId = "1234"; X509Certificate certificate = MiscTestUtils.generateCertificate(keyPair.getPublic(), "CN=Test, SERIALNUMBER=" + userId, notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null, null); byte[] salt = "salt".getBytes(); byte[] sessionId = "session-id".getBytes(); AuthenticationDataMessage message = new AuthenticationDataMessage(); message.authnCert = certificate; message.saltValue = salt; message.sessionId = sessionId; Map<String, String> httpHeaders = new HashMap<String, String>(); HttpSession testHttpSession = new HttpTestSession(); HttpServletRequest mockServletRequest = EasyMock.createMock(HttpServletRequest.class); ServletConfig mockServletConfig = EasyMock.createMock(ServletConfig.class); byte[] challenge = AuthenticationChallenge.generateChallenge(testHttpSession); Thread.sleep(1000); // > 1 ms AuthenticationContract authenticationContract = new AuthenticationContract(salt, null, null, sessionId, null, challenge); byte[] toBeSigned = authenticationContract.calculateToBeSigned(); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(keyPair.getPrivate()); signature.update(toBeSigned); byte[] signatureValue = signature.sign(); message.signatureValue = signatureValue; EasyMock.expect(mockServletConfig .getInitParameter(AuthenticationDataMessageHandler.CHALLENGE_MAX_MATURITY_INIT_PARAM_NAME)) .andReturn("1"); // 1 ms EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.AUTHN_SERVICE_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig .getInitParameter(AuthenticationDataMessageHandler.AUTHN_SERVICE_INIT_PARAM_NAME + "Class")) .andReturn(AuthenticationTestService.class.getName()); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.HOSTNAME_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INET_ADDRESS_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVER_CERTIFICATE)) .andStubReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(HelloMessageHandler.SESSION_ID_CHANNEL_BINDING_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_IDENTITY_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_CERTS_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_ADDRESS_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_PHOTO_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(HelloMessageHandler.IDENTITY_INTEGRITY_SERVICE_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig .getInitParameter(HelloMessageHandler.IDENTITY_INTEGRITY_SERVICE_INIT_PARAM_NAME + "Class")) .andStubReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.AUDIT_SERVICE_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig .getInitParameter(AuthenticationDataMessageHandler.AUDIT_SERVICE_INIT_PARAM_NAME + "Class")) .andReturn(AuditTestService.class.getName()); EasyMock.expect(mockServletRequest.getRemoteAddr()).andStubReturn("remote-address"); EasyMock.expect(mockServletRequest.getAttribute("javax.servlet.request.ssl_session")) .andStubReturn(new String(Hex.encodeHex(sessionId))); EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_SECRET_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVICE)) .andReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVICE + "Class")) .andReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_ORG_ID_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_APP_ID_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(IdentityDataMessageHandler.INCLUDE_DATA_FILES)) .andReturn(null); EasyMock.expect(mockServletConfig .getInitParameter(AuthenticationDataMessageHandler.AUTHN_SIGNATURE_SERVICE_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig.getInitParameter( AuthenticationDataMessageHandler.AUTHN_SIGNATURE_SERVICE_INIT_PARAM_NAME + "Class")) .andReturn(null); // prepare EasyMock.replay(mockServletRequest, mockServletConfig); // operate AppletServiceServlet.injectInitParams(mockServletConfig, this.testedInstance); this.testedInstance.init(mockServletConfig); try { this.testedInstance.handleMessage(message, httpHeaders, mockServletRequest, testHttpSession); fail(); } catch (ServletException e) { // verify EasyMock.verify(mockServletRequest, mockServletConfig); assertNull(AuditTestService.getAuditUserId()); assertNull(testHttpSession.getAttribute("eid.identifier")); assertEquals(certificate, AuditTestService.getAuditClientCertificate()); assertEquals("remote-address", AuditTestService.getAuditRemoteAddress()); } }
From source file:test.unit.be.fedict.eid.applet.service.AuthenticationDataMessageHandlerTest.java
@Test public void testInvalidAuthenticationSignature() throws Exception { // setup//from w w w .j a va 2 s. c o m KeyPair keyPair = MiscTestUtils.generateKeyPair(); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusYears(1); String userId = "1234"; X509Certificate certificate = MiscTestUtils.generateCertificate(keyPair.getPublic(), "CN=Test, SERIALNUMBER=" + userId, notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null, null); byte[] salt = "salt".getBytes(); byte[] sessionId = "session-id".getBytes(); AuthenticationDataMessage message = new AuthenticationDataMessage(); message.authnCert = certificate; message.saltValue = salt; message.sessionId = sessionId; Map<String, String> httpHeaders = new HashMap<String, String>(); HttpSession testHttpSession = new HttpTestSession(); HttpServletRequest mockServletRequest = EasyMock.createMock(HttpServletRequest.class); ServletConfig mockServletConfig = EasyMock.createMock(ServletConfig.class); AuthenticationChallenge.generateChallenge(testHttpSession); AuthenticationContract authenticationContract = new AuthenticationContract(salt, null, null, sessionId, null, "foobar-challenge".getBytes()); byte[] toBeSigned = authenticationContract.calculateToBeSigned(); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(keyPair.getPrivate()); signature.update(toBeSigned); byte[] signatureValue = signature.sign(); message.signatureValue = signatureValue; EasyMock.expect(mockServletConfig .getInitParameter(AuthenticationDataMessageHandler.CHALLENGE_MAX_MATURITY_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.AUTHN_SERVICE_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig .getInitParameter(AuthenticationDataMessageHandler.AUTHN_SERVICE_INIT_PARAM_NAME + "Class")) .andReturn(AuthenticationTestService.class.getName()); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.HOSTNAME_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INET_ADDRESS_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVER_CERTIFICATE)) .andStubReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(HelloMessageHandler.SESSION_ID_CHANNEL_BINDING_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.AUDIT_SERVICE_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig .getInitParameter(AuthenticationDataMessageHandler.AUDIT_SERVICE_INIT_PARAM_NAME + "Class")) .andReturn(AuditTestService.class.getName()); EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_SECRET_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_IDENTITY_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_CERTS_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_ADDRESS_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_PHOTO_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(HelloMessageHandler.IDENTITY_INTEGRITY_SERVICE_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig .getInitParameter(HelloMessageHandler.IDENTITY_INTEGRITY_SERVICE_INIT_PARAM_NAME + "Class")) .andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVICE)) .andReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVICE + "Class")) .andReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_ORG_ID_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_APP_ID_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(IdentityDataMessageHandler.INCLUDE_DATA_FILES)) .andReturn(null); EasyMock.expect(mockServletConfig .getInitParameter(AuthenticationDataMessageHandler.AUTHN_SIGNATURE_SERVICE_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig.getInitParameter( AuthenticationDataMessageHandler.AUTHN_SIGNATURE_SERVICE_INIT_PARAM_NAME + "Class")) .andReturn(null); EasyMock.expect(mockServletRequest.getAttribute("javax.servlet.request.ssl_session")) .andStubReturn(new String(Hex.encodeHex(sessionId))); String remoteAddress = "1.2.3.4"; EasyMock.expect(mockServletRequest.getRemoteAddr()).andReturn(remoteAddress); // prepare EasyMock.replay(mockServletRequest, mockServletConfig); // operate AppletServiceServlet.injectInitParams(mockServletConfig, this.testedInstance); this.testedInstance.init(mockServletConfig); try { this.testedInstance.handleMessage(message, httpHeaders, mockServletRequest, testHttpSession); fail(); } catch (SecurityException e) { // expected } // verify EasyMock.verify(mockServletRequest, mockServletConfig); assertFalse(AuthenticationTestService.isCalled()); assertNull(AuditTestService.getAuditUserId()); assertEquals(remoteAddress, AuditTestService.getAuditRemoteAddress()); assertEquals(certificate, AuditTestService.getAuditClientCertificate()); assertNull(testHttpSession.getAttribute("eid.identifier")); }
From source file:cl.nic.dte.util.XMLUtil.java
public static AUTORIZACIONDocument generateAuthorization(AUTORIZACIONDocument template, PrivateKey pKey) throws NoSuchAlgorithmException, SignatureException, TransformerException, InvalidKeyException, IOException {// w w w . j av a 2 s. co m // Generation of keys KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(1024); KeyPair kp = kpg.generateKeyPair(); CAFType caf = template.getAUTORIZACION().getCAF(); CAFType.DA.RSAPK rsapk = caf.getDA().addNewRSAPK(); rsapk.setM(((RSAPublicKey) kp.getPublic()).getModulus().toByteArray()); rsapk.setE(((RSAPublicKey) kp.getPublic()).getPublicExponent().toByteArray()); ResourceBundle labels = ResourceBundle.getBundle("cl.nic.dte.resources.VerifyResults"); Signature sig = null; if (pKey.getAlgorithm().equals("RSA")) { sig = Signature.getInstance("SHA1withRSA"); caf.addNewFRMA().setAlgoritmo("SHA1withRSA"); } else if (pKey.getAlgorithm().equals("DSA")) { sig = Signature.getInstance("SHA1withDSA"); caf.addNewFRMA().setAlgoritmo("SHA1withDSA"); } else { throw new NoSuchAlgorithmException( labels.getString("ALGORITHM_NOT_SUPPORTED").replaceAll("%1", pKey.getAlgorithm())); } template.getAUTORIZACION() .setRSASK("-----BEGIN RSA PRIVATE KEY-----\n" + new String(Base64.encodeBase64(kp.getPrivate().getEncoded(), true)) + "-----END RSA PRIVATE KEY-----\n"); template.getAUTORIZACION() .setRSAPUBK("-----BEGIN RSA PUBLIC KEY-----\n" + new String(Base64.encodeBase64(kp.getPublic().getEncoded(), true)) + "-----END RSA PUBLIC KEY-----\n"); sig.initSign(pKey); sig.update(XMLUtil.getCleaned(caf.getDA())); caf.getFRMA().setByteArrayValue(Base64.encodeBase64(sig.sign())); return template; }