List of usage examples for java.security Signature update
public final void update(ByteBuffer data) throws SignatureException
From source file:org.ejbca.core.protocol.cmp.AuthenticationModulesTest.java
@Test public void test12EECrmfNotCheckAdmin() throws NoSuchAlgorithmException, EjbcaException, IOException, Exception { this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE); this.cmpConfiguration.setAuthenticationParameters(ALIAS, "TestCA"); this.cmpConfiguration.setOmitVerificationsInECC(ALIAS, true); this.cmpConfiguration.setRAMode(ALIAS, true); this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration); KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage msg = genCertReq(issuerDN, USER_DN, keys, this.cacert, this.nonce, this.transid, false, null, null, null, null, pAlg, new DEROctetString(this.nonce)); assertNotNull("Generating CrmfRequest failed.", msg); String adminName = "cmpTestAdmin"; KeyPair admkeys = KeyTools.genKeys("1024", "RSA"); AuthenticationToken adminToken = createAdminToken(admkeys, adminName, "CN=" + adminName + ",C=SE", this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); Certificate admCert = getCertFromCredentials(adminToken); CMPCertificate[] extraCert = getCMPCert(admCert); msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, admkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(msg);//from w w w .j a va2 s . c o m //******************************************** final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC"); sig.initVerify(admCert.getPublicKey()); sig.update(CmpMessageHelper.getProtectedBytes(msg)); boolean verified = sig.verify(msg.getProtection().getBytes()); assertTrue("Signing the message failed.", verified); //******************************************** final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(msg); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, ALIAS); checkCmpResponseGeneral(resp, issuerDN, USER_DN, this.cacert, msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(resp)); try { PKIMessage respObject = PKIMessage.getInstance(inputStream.readObject()); assertNotNull(respObject); PKIBody body = respObject.getBody(); assertEquals(23, body.getType()); ErrorMsgContent err = (ErrorMsgContent) body.getContent(); String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString(); String expectedErrmsg = "Omitting some verifications can only be accepted in RA mode and when the CMP request has already been authenticated, for example, through the use of NestedMessageContent"; assertEquals(expectedErrmsg, errMsg); } finally { inputStream.close(); } removeAuthenticationToken(adminToken, admCert, adminName); }
From source file:org.ejbca.core.protocol.cmp.AuthenticationModulesTest.java
@Test public void test05EECrmfReq() throws NoSuchAlgorithmException, EjbcaException, IOException, Exception { this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE); this.cmpConfiguration.setAuthenticationParameters(ALIAS, "TestCA"); this.cmpConfiguration.setRAMode(ALIAS, true); this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration); final X500Name testUserDN = new X500Name("CN=cmptestuser5,C=SE"); final String testUsername = "cmptestuser5"; String fingerprint = null;//from w ww .j a v a 2s .c o m String fingerprint2 = null; AuthenticationToken admToken = null; Certificate admCert = null; try { KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage msg = genCertReq(issuerDN, testUserDN, keys, this.cacert, this.nonce, this.transid, false, null, null, null, null, pAlg, new DEROctetString(this.nonce)); assertNotNull("Generating CrmfRequest failed.", msg); KeyPair admkeys = KeyTools.genKeys("512", "RSA"); admToken = createAdminToken(admkeys, testUsername, testUserDN.toString(), this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); admCert = getCertFromCredentials(admToken); fingerprint = CertTools.getFingerprintAsString(admCert); CMPCertificate[] extraCert = getCMPCert(admCert); msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, admkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(msg); //******************************************'''''' final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC"); sig.initVerify(admCert.getPublicKey()); sig.update(CmpMessageHelper.getProtectedBytes(msg)); boolean verified = sig.verify(msg.getProtection().getBytes()); assertTrue("Signing the message failed.", verified); //*************************************************** final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(msg); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, ALIAS); checkCmpResponseGeneral(resp, issuerDN, testUserDN, this.cacert, msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); CertReqMessages ir = (CertReqMessages) msg.getBody().getContent(); Certificate cert2 = checkCmpCertRepMessage(testUserDN, this.cacert, resp, ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue()); assertNotNull("CrmfRequest did not return a certificate", cert2); fingerprint2 = CertTools.getFingerprintAsString(cert2); } finally { removeAuthenticationToken(admToken, admCert, testUsername); // also removes testUsername this.internalCertStoreSession.removeCertificate(fingerprint); this.internalCertStoreSession.removeCertificate(fingerprint2); } }
From source file:org.ejbca.core.protocol.cmp.AuthenticationModulesTest.java
/** * Tests that EndEntityAuthentication module can be successfully used in client mode when the end entity's password is not stored in clear text. * //from w ww .j a v a 2s .c o m * @throws Exception */ @Test public void test21CrmfRequestClientModeEECNotClearPassword() throws Exception { this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE); this.cmpConfiguration.setAuthenticationParameters(ALIAS, "-"); this.cmpConfiguration.setRAMode(ALIAS, false); this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration); final X500Name testUserDN = new X500Name("CN=cmptestuser21,C=SE"); final String testUsername = "cmptestuser21"; String fingerprint = null; String fingerprint2 = null; try { KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); createUser(testUsername, testUserDN.toString(), "foo123", false, this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); Certificate cert = this.signSession.createCertificate(ADMIN, testUsername, "foo123", new PublicKeyWrapper(keys.getPublic())); fingerprint = CertTools.getFingerprintAsString(cert); //Edit the status of the user to NEW createUser(testUsername, testUserDN.toString(), "foo123", false, this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); PKIMessage msg = genCertReq(issuerDN, testUserDN, keys, this.cacert, this.nonce, this.transid, false, null, null, null, null, pAlg, null); assertNotNull("Generating CrmfRequest failed.", msg); CMPCertificate[] extraCert = getCMPCert(cert); msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, keys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(msg); //******************************************'''''' final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC"); sig.initVerify(cert.getPublicKey()); sig.update(CmpMessageHelper.getProtectedBytes(msg)); boolean verified = sig.verify(msg.getProtection().getBytes()); assertTrue("Signing the message failed.", verified); //*************************************************** final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(msg); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, ALIAS); CertReqMessages ir = (CertReqMessages) msg.getBody().getContent(); Certificate cert2 = checkCmpCertRepMessage(testUserDN, this.cacert, resp, ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue()); assertNotNull("CrmfRequest did not return a certificate", cert2); fingerprint2 = CertTools.getFingerprintAsString(cert2); } finally { try { this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, testUsername, ReasonFlags.unused); } catch (Exception e) {// do nothing } this.internalCertStoreSession.removeCertificate(fingerprint); this.internalCertStoreSession.removeCertificate(fingerprint2); } }
From source file:org.atricore.idbus.capabilities.sso.support.core.signature.JSR105SamlR2SignerImpl.java
public String signQueryString(String queryString) throws SamlR2SignatureException { try {//w ww . ja va 2s . c o m if (queryString == null || queryString.length() == 0) { logger.error("SAML 2.0 Qery string null"); throw new SamlR2SignatureException("SAML 2.0 Qery string null"); } if (logger.isDebugEnabled()) logger.debug("Received SAML 2.0 Query string [" + queryString + "] for signing"); PrivateKey privateKey = (PrivateKey) this.getKeyResolver().getPrivateKey(); String keyAlgorithm = privateKey.getAlgorithm(); Signature signature = null; String algURI = null; if (keyAlgorithm.equals("RSA")) { signature = Signature.getInstance(SHA1_WITH_RSA); algURI = SignatureMethod.RSA_SHA1; } else if (keyAlgorithm.equals("DSA")) { signature = Signature.getInstance(SHA1_WITH_DSA); algURI = SignatureMethod.DSA_SHA1; } else { throw new SamlR2SignatureException( "SAML 2.0 Signature does not support provided key's algorithm " + keyAlgorithm); } if (queryString.charAt(queryString.length() - 1) != '&') { queryString = queryString + "&"; } queryString += "SigAlg=" + URLEncoder.encode(algURI, "UTF-8"); if (logger.isTraceEnabled()) logger.trace("Signing SAML 2.0 Query string [" + queryString + "]"); signature.initSign(privateKey); signature.update(queryString.getBytes()); byte[] sigBytes = null; sigBytes = signature.sign(); if (sigBytes == null || sigBytes.length == 0) { logger.error("Cannot generate signed query string, Signature created 'null' value."); throw new SamlR2SignatureException( "Cannot generate signed query string, Signature created 'null' value."); } Base64 encoder = new Base64(); String encodedSig = new String(encoder.encode(sigBytes), "UTF-8"); queryString += "&Signature=" + URLEncoder.encode(encodedSig, "UTF-8"); if (logger.isTraceEnabled()) logger.trace("Signed SAML 2.0 Query string [" + queryString + "]"); return queryString; } catch (Exception e) { throw new SamlR2SignatureException("Error generating SAML 2.0 Query string signature " + e.getMessage(), e); } }
From source file:org.ejbca.core.protocol.cmp.AuthenticationModulesTest.java
/** Test CMP initial request against EJBCA CMP in client mode (operationmode=normal) using End Entity certificate signature authentication, * i.e. the request is signed by a certificate of the same end entity making the request, and this signature is used for authenticating the end entity. * Test:/*w w w . j av a 2s . com*/ * - Request signed by a fake certificate, i.e. one that is not in the database (FAIL) * - Request signed by a certificate that beloongs to another user (FAIL) * - Request signed by a proper certificate but where user status is not NEW (FAIL) * - Request signed by a proper, but revoked certificate (FAIL) * - A working request signed by a proper, unrevoked certificate and user status is NEW (SUCCESS) * * @throws Exception on some errors */ @Test public void test18CrmfReqClientModeEESignature() throws Exception { this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE); this.cmpConfiguration.setAuthenticationParameters(ALIAS, "-"); this.cmpConfiguration.setRAMode(ALIAS, false); this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration); final X500Name testUserDN = new X500Name("CN=cmptestuser16,C=SE"); final String testUsername = "cmptestuser16"; final String otherUserDN = "CN=cmptestotheruser16,C=SE"; final String otherUsername = "cmptestotheruser16"; String fingerprint = null; String fingerprint2 = null; String fingerprint3 = null; try { KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); KeyPair fakeKeys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); createUser(testUsername, testUserDN.toString(), "foo123", true, this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); // A real certificate that can be used to sign the message Certificate cert = this.signSession.createCertificate(ADMIN, testUsername, "foo123", new PublicKeyWrapper(keys.getPublic())); fingerprint = CertTools.getFingerprintAsString(cert); // A fake certificate that should not be valid Certificate fakeCert = CertTools.genSelfCert(testUserDN.toString(), 30, null, fakeKeys.getPrivate(), fakeKeys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, false); // Step 1 sign with fake certificate, should not be valid as end entity authentication { AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage msg = genCertReq(issuerDN, testUserDN, keys, this.cacert, this.nonce, this.transid, false, null, null, null, null, pAlg, null); assertNotNull("Generating CrmfRequest failed.", msg); CMPCertificate[] extraCert = getCMPCert(fakeCert); msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, fakeKeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(msg); //******************************************'''''' final Signature sig = Signature .getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC"); sig.initVerify(fakeCert.getPublicKey()); sig.update(CmpMessageHelper.getProtectedBytes(msg)); boolean verified = sig.verify(msg.getProtection().getBytes()); assertTrue("Signing the message failed.", verified); //*************************************************** final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(msg); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, ALIAS); // This should have failed checkCmpResponseGeneral(resp, issuerDN, testUserDN, this.cacert, msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(resp)); PKIMessage respObject = PKIMessage.getInstance(inputStream.readObject()); try { assertNotNull(respObject); PKIBody body = respObject.getBody(); assertEquals(23, body.getType()); ErrorMsgContent err = (ErrorMsgContent) body.getContent(); String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString(); String expectedErrMsg = "The certificate attached to the PKIMessage in the extraCert field could not be found in the database."; assertEquals(expectedErrMsg, errMsg); } finally { inputStream.close(); } } // Step 2, sign the request with a certificate that does not belong to the user { KeyPair otherKeys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); createUser(otherUsername, otherUserDN, "foo123", true, this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); // A real certificate that can be used to sign the message Certificate othercert = this.signSession.createCertificate(ADMIN, otherUsername, "foo123", new PublicKeyWrapper(otherKeys.getPublic())); fingerprint2 = CertTools.getFingerprintAsString(cert); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage msg = genCertReq(issuerDN, testUserDN, keys, this.cacert, this.nonce, this.transid, false, null, null, null, null, pAlg, null); assertNotNull("Generating CrmfRequest failed.", msg); CMPCertificate[] extraCert = getCMPCert(othercert); msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, otherKeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(msg); //******************************************'''''' final Signature sig = Signature .getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC"); sig.initVerify(othercert.getPublicKey()); sig.update(CmpMessageHelper.getProtectedBytes(msg)); boolean verified = sig.verify(msg.getProtection().getBytes()); assertTrue("Signing the message failed.", verified); //*************************************************** final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(msg); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, ALIAS); // This should have failed checkCmpResponseGeneral(resp, issuerDN, testUserDN, this.cacert, msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(resp)); try { PKIMessage respObject = PKIMessage.getInstance(inputStream.readObject()); assertNotNull(respObject); PKIBody body = respObject.getBody(); assertEquals(23, body.getType()); ErrorMsgContent err = (ErrorMsgContent) body.getContent(); String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString(); String expectedErrMsg = "The End Entity certificate attached to the PKIMessage in the extraCert field does not belong to user '" + testUsername + "'"; assertEquals(expectedErrMsg, errMsg); } finally { inputStream.close(); } } // Step 3 sign with the real certificate, but user status is not NEW AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage msg = genCertReq(issuerDN, testUserDN, keys, this.cacert, this.nonce, this.transid, false, null, null, null, null, pAlg, null); assertNotNull("Generating CrmfRequest failed.", msg); CMPCertificate[] extraCert = getCMPCert(cert); msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, keys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(msg); //******************************************'''''' final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC"); sig.initVerify(cert.getPublicKey()); sig.update(CmpMessageHelper.getProtectedBytes(msg)); boolean verified = sig.verify(msg.getProtection().getBytes()); assertTrue("Signing the message failed.", verified); //*************************************************** final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(msg); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, ALIAS); checkCmpResponseGeneral(resp, issuerDN, testUserDN, this.cacert, msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); // This should have failed ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(resp)); try { PKIMessage respObject = PKIMessage.getInstance(inputStream.readObject()); assertNotNull(respObject); PKIBody body = respObject.getBody(); assertEquals(23, body.getType()); ErrorMsgContent err = (ErrorMsgContent) body.getContent(); String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString(); String expectedErrMsg = "Got request with status GENERATED (40), NEW, FAILED or INPROCESS required: cmptestuser16."; assertEquals(expectedErrMsg, errMsg); // Step 4 now set status to NEW, and a clear text password, then it should finally work createUser(testUsername, testUserDN.toString(), "randompasswordhere", true, this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); // Send request and receive response final byte[] resp2 = sendCmpHttp(ba, 200, ALIAS); CertReqMessages ir = (CertReqMessages) msg.getBody().getContent(); Certificate cert2 = checkCmpCertRepMessage(testUserDN, this.cacert, resp2, ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue()); assertNotNull("CrmfRequest did not return a certificate", cert2); fingerprint3 = CertTools.getFingerprintAsString(cert2); // Step 5, revoke the certificate and try again { this.certificateStoreSession.setRevokeStatus(ADMIN, cert, RevokedCertInfo.REVOCATION_REASON_CESSATIONOFOPERATION, null); final byte[] resp3 = sendCmpHttp(ba, 200, ALIAS); // This should have failed checkCmpResponseGeneral(resp, issuerDN, testUserDN, this.cacert, msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); ASN1InputStream inputStream3 = new ASN1InputStream(new ByteArrayInputStream(resp3)); try { PKIMessage respObject3 = PKIMessage.getInstance(inputStream3.readObject()); assertNotNull(respObject); PKIBody body3 = respObject3.getBody(); assertEquals(23, body3.getType()); err = (ErrorMsgContent) body3.getContent(); String errMsg3 = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString(); String expectedErrMsg3 = "The certificate attached to the PKIMessage in the extraCert field is not active."; assertEquals(expectedErrMsg3, errMsg3); } finally { inputStream3.close(); } } } finally { inputStream.close(); } } finally { try { this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, testUsername, ReasonFlags.unused); } catch (Exception e) {// do nothing } try { this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, otherUsername, ReasonFlags.unused); } catch (Exception e) {// do nothing } this.internalCertStoreSession.removeCertificate(fingerprint); this.internalCertStoreSession.removeCertificate(fingerprint2); this.internalCertStoreSession.removeCertificate(fingerprint3); } }
From source file:com.alvexcore.share.jscript.JSShareExtensionRegistry.java
@SuppressWarnings("serial") public String removeSignature(String data) { if (data == null) return null; int idx = data.indexOf("\n"); if (idx <= 20) return null; String s = data.substring(0, idx); if (!s.startsWith("SIGNATURE:")) return null; s = s.substring(10);/*from w ww.j av a2 s. c o m*/ Signature sig; try { sig = Signature.getInstance("SHA1withRSA"); sig.initVerify(new PublicKey() { @Override public String getAlgorithm() { return "RSA"; } @Override public String getFormat() { return "X.509"; } @Override public byte[] getEncoded() { return new byte[] { 48, -126, 1, 34, 48, 13, 6, 9, 42, -122, 72, -122, -9, 13, 1, 1, 1, 5, 0, 3, -126, 1, 15, 0, 48, -126, 1, 10, 2, -126, 1, 1, 0, -115, 117, -12, -114, -121, -128, 76, 99, -114, -37, 107, -44, 108, 36, 38, 99, 13, -93, -73, -62, 44, 10, 120, -22, -31, -25, -109, 45, 24, -47, 59, -87, -39, -29, -35, -96, 13, -117, 31, -98, 107, 80, -104, -72, 5, -32, 79, -115, 59, -87, 109, -121, 104, 36, -14, 123, -113, 87, -50, 40, -52, -59, -52, -7, -13, -34, 17, -29, -39, 63, -62, -44, 51, 68, -98, -115, -13, 10, -7, -101, 81, -72, 81, 91, -94, 91, -94, 6, 65, 84, 35, -121, 14, -103, 38, 6, 59, 115, -110, 4, -63, -89, -22, 27, 126, -96, -32, 97, 105, -108, 14, -23, -62, -89, -41, 30, -126, -114, 121, 17, 125, 18, 124, -114, 0, -13, 85, -11, 92, 87, -16, 3, 30, 23, -126, -33, 122, 126, -72, -95, 29, 73, -24, -34, -27, -41, 109, -77, -108, -34, 91, -36, -3, 112, 13, 30, 111, 9, -105, 7, 8, -70, 95, -128, -82, -13, -4, 127, -58, 68, -114, 89, 69, 101, -106, -123, -36, -90, -110, -44, 45, 25, 107, 52, 6, 69, -35, 89, 7, -59, 96, 4, 97, 29, 24, -50, -59, -40, 104, 70, 68, -28, 77, 94, -57, -38, 91, -99, 37, -89, 105, -126, 52, 80, 111, 107, -69, 22, 39, -70, -5, 87, -33, -77, -79, -64, 76, -12, -58, -37, 56, 102, 17, 59, 11, -73, -68, -96, -108, -47, 13, -113, -77, 60, 88, -128, 19, -42, 12, 49, 89, 7, -11, -11, -87, 37, 2, 3, 1, 0, 1 }; } }); String d = data.substring(idx + 1); sig.update(d.getBytes()); if (sig.verify(Base64.decodeBase64(s))) return d; else return null; } catch (Exception e) { return null; } }
From source file:org.openbravo.erpCommon.obps.ActivationKey.java
private boolean decrypt(byte[] bytes, PublicKey pk, ByteArrayOutputStream bos, String strOBPublicKey) throws Exception { PublicKey obPk = getPublicKey(strOBPublicKey); // get OB public key to check signature Signature signer = Signature.getInstance("MD5withRSA"); signer.initVerify(obPk);/*ww w . j a v a 2s .c o m*/ Cipher cipher = Cipher.getInstance("RSA"); ByteArrayInputStream bis = new ByteArrayInputStream( org.apache.commons.codec.binary.Base64.decodeBase64(bytes)); // Encryptation only accepts 128B size, it must be chuncked final byte[] buf = new byte[128]; final byte[] signature = new byte[128]; // read the signature if (!(bis.read(signature) > 0)) { return false; } // decrypt while ((bis.read(buf)) > 0) { cipher.init(Cipher.DECRYPT_MODE, pk); bos.write(cipher.doFinal(buf)); } // verify signature signer.update(bos.toByteArray()); boolean signed = signer.verify(signature); log.debug("signature length:" + buf.length); log.debug("singature:" + (new BigInteger(signature).toString(16).toUpperCase())); log.debug("signed:" + signed); if (!signed) { isActive = false; errorMessage = "@NotSigned@"; setLogger(); return false; } return true; }
From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java
@Override public void restoreCAKeyStore(AuthenticationToken authenticationToken, String caname, byte[] p12file, String keystorepass, String privkeypass, String privateSignatureKeyAlias, String privateEncryptionKeyAlias) { if (log.isTraceEnabled()) { log.trace(">restoreCAKeyStore"); }/*ww w .ja v a 2 s . c o m*/ try { // check authorization if (!accessSession.isAuthorizedNoLogging(authenticationToken, StandardRules.ROLE_ROOT.resource())) { final String detailsMsg = intres.getLocalizedMessage("caadmin.notauthorizedtorestorecatoken", caname); auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), null, null, null, detailsMsg); } CA thisCa = caSession.getCAForEdit(authenticationToken, caname); final CAToken thisCAToken = thisCa.getCAToken(); CryptoToken cryptoToken = cryptoTokenSession.getCryptoToken(thisCAToken.getCryptoTokenId()); if (cryptoToken != null) { throw new Exception("CA already has an existing CryptoToken reference: " + cryptoToken.getId()); } // load keystore from input KeyStore keystore = KeyStore.getInstance("PKCS12", "BC"); keystore.load(new ByteArrayInputStream(p12file), keystorepass.toCharArray()); // Extract signature keys if (privateSignatureKeyAlias == null || !keystore.isKeyEntry(privateSignatureKeyAlias)) { throw new Exception("Alias \"" + privateSignatureKeyAlias + "\" not found."); } Certificate[] signatureCertChain = KeyTools.getCertChain(keystore, privateSignatureKeyAlias); if (signatureCertChain.length < 1) { String msg = "Cannot load certificate chain with alias " + privateSignatureKeyAlias; log.error(msg); throw new Exception(msg); } Certificate caSignatureCertificate = (Certificate) signatureCertChain[0]; PublicKey p12PublicSignatureKey = caSignatureCertificate.getPublicKey(); PrivateKey p12PrivateSignatureKey = null; p12PrivateSignatureKey = (PrivateKey) keystore.getKey(privateSignatureKeyAlias, privkeypass.toCharArray()); // Extract encryption keys PrivateKey p12PrivateEncryptionKey = null; PublicKey p12PublicEncryptionKey = null; Certificate caEncryptionCertificate = null; if (privateEncryptionKeyAlias != null) { if (!keystore.isKeyEntry(privateEncryptionKeyAlias)) { throw new Exception("Alias \"" + privateEncryptionKeyAlias + "\" not found."); } Certificate[] encryptionCertChain = KeyTools.getCertChain(keystore, privateEncryptionKeyAlias); if (encryptionCertChain.length < 1) { String msg = "Cannot load certificate chain with alias " + privateEncryptionKeyAlias; log.error(msg); throw new Exception(msg); } caEncryptionCertificate = (Certificate) encryptionCertChain[0]; p12PrivateEncryptionKey = (PrivateKey) keystore.getKey(privateEncryptionKeyAlias, privkeypass.toCharArray()); p12PublicEncryptionKey = caEncryptionCertificate.getPublicKey(); } else { throw new Exception("Missing encryption key"); } // Sign something to see that we are restoring the right private signature key String testSigAlg = (String) AlgorithmTools .getSignatureAlgorithms(thisCa.getCACertificate().getPublicKey()).iterator().next(); if (testSigAlg == null) { testSigAlg = "SHA1WithRSA"; } // Sign with imported private key byte[] input = "Test data...".getBytes(); Signature signature = Signature.getInstance(testSigAlg, "BC"); signature.initSign(p12PrivateSignatureKey); signature.update(input); byte[] signed = signature.sign(); // Verify with public key from CA certificate signature = Signature.getInstance(testSigAlg, "BC"); signature.initVerify(thisCa.getCACertificate().getPublicKey()); signature.update(input); if (!signature.verify(signed)) { throw new Exception("Could not use private key for verification. Wrong p12-file for this CA?"); } // Import the keys and save to database CAToken catoken = importKeysToCAToken(authenticationToken, keystorepass, thisCAToken.getProperties(), p12PrivateSignatureKey, p12PublicSignatureKey, p12PrivateEncryptionKey, p12PublicEncryptionKey, signatureCertChain, thisCa.getCAId()); thisCa.setCAToken(catoken); // Finally save the CA caSession.editCA(authenticationToken, thisCa, true); // Log final String detailsMsg = intres.getLocalizedMessage("caadmin.restoredcakeystore", Integer.valueOf(thisCa.getCAId())); auditSession.log(EjbcaEventTypes.CA_RESTORETOKEN, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), String.valueOf(thisCa.getCAId()), null, null, detailsMsg); } catch (Exception e) { final String detailsMsg = intres.getLocalizedMessage("caadmin.errorrestorecakeystore", caname, "PKCS12", e.getMessage()); auditSession.log(EjbcaEventTypes.CA_RESTORETOKEN, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), null, null, null, detailsMsg); throw new EJBException(e); } if (log.isTraceEnabled()) { log.trace("<restoreCAKeyStore"); } }