List of usage examples for org.bouncycastle.jce PKCS10CertificationRequest getPublicKey
public PublicKey getPublicKey() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException
From source file:org.glite.security.delegation.impl.GliteDelegation.java
License:Apache License
/** * @param inDelegationID/*from w w w .j a v a 2 s. c om*/ * @param proxy * @throws DelegationException */ public void putProxy(String inDelegationID, String proxy) throws DelegationException { logger.info("Processing putProxy."); String delegationID = inDelegationID; // Init Security Context InitSecurityContext.init(); // Get security context SecurityContext sc = SecurityContext.getCurrentContext(); if (sc == null) { logger.debug("Failed to get SecurityContext."); throw new DelegationException("Failed to get client security information."); } // Check if a bad configuration was detected on launch (and fail if // true) if (m_bad_config) { logger.error("Service is misconfigured. Stopping execution."); throw new DelegationException("Service is misconfigured."); } // Check for a null proxy if (proxy == null) { logger.error("Failed to putProxy as proxy was null."); throw new DelegationException("No proxy was given."); } // Load given proxy X509Certificate[] proxyCertChain; try { proxyCertChain = s_reader.readCertChain(new BufferedInputStream(new StringBufferInputStream(proxy))) .toArray(new X509Certificate[] {}); } catch (IOException e2) { logger.error("Failed to load proxy certificate chain: " + e2.getMessage()); throw new DelegationException("Failed to load proxy certificate chain: " + e2.getMessage()); } if (proxyCertChain == null || proxyCertChain.length == 0) { logger.error("Failed to load proxy certificate chain - chain was null or size 0."); throw new DelegationException("Failed to load proxy certificate chain."); } logger.debug("Given proxy certificate loaded successfully."); // check if the chain is within it's validity period. for (int i = 0; i < proxyCertChain.length; i++) { // Check if the proxy is currently valid try { proxyCertChain[i].checkValidity(); } catch (CertificateExpiredException e) { throw new DelegationException( "Failed proxy validation - it expired on: " + proxyCertChain[0].getNotAfter()); } catch (CertificateNotYetValidException e) { throw new DelegationException( "Failed proxy validation - it will be valid from: " + proxyCertChain[0].getNotBefore()); } } // Get the given proxy information String proxySubjectDN = DNHandler.getSubject(proxyCertChain[0]).getRFCDN(); String proxyIssuerDN = DNHandler.getIssuer(proxyCertChain[0]).getRFCDN(); if (logger.isDebugEnabled()) { logger.debug("Proxy Subject DN: " + proxySubjectDN); logger.debug("Proxy Issuer DN: " + proxyIssuerDN); logger.debug("Proxy Public key:" + proxyCertChain[0].getPublicKey()); logger.debug("chain length is: " + proxyCertChain.length); logger.debug("last cert is:" + proxyCertChain[proxyCertChain.length - 1]); for (int n = 0; n < proxyCertChain.length; n++) { logger.debug("cert [" + n + "] is from " + DNHandler.getSubject(proxyCertChain[n]).getRFCDN()); } } if (proxySubjectDN == null || proxyIssuerDN == null) { logger.error("Failed to get DN (subject or issuer) out of proxy. It came null"); throw new DelegationException("Failed to get DN (subject or issuer) out of proxy."); } String clientDN = null; // Get client information from security context try { clientDN = CertUtil.getUserDN(sc.getClientCertChain()).getRFCDN(); } catch (IOException e) { throw new DelegationException("No user certificate found in the proxy chain: " + e.getMessage()); } if (clientDN == null) { logger.error("Failed to get client DN. It came null"); throw new DelegationException("Failed to get client DN."); } logger.debug("Client DN: " + clientDN); // Get the client VOMS attributes (for the DLG ID) String[] clientVOMSAttributes = GrDPX509Util.getVOMSAttributes(sc); // Get a delegation ID for the given proxy (or take the specified one if // given) // TODO: Should the dlg id here be generated from the client or the proxy info? // Also, should the client and proxy VOMS attributes be checked for a match? if (delegationID == null || delegationID.length() == 0) { delegationID = GrDPX509Util.genDlgID(clientDN, clientVOMSAttributes); } logger.debug("Delegation ID is '" + delegationID + "'"); // Check that the client is the issuer of the given proxy // TODO: more strict check if (!proxyIssuerDN.endsWith(clientDN)) { String message = "Client '" + clientDN + "' is not issuer of proxy '" + proxyIssuerDN + "'."; logger.error(message); throw new DelegationException(message); } String cacheID = delegationID; try { cacheID = delegationID + '+' + GrDPX509Util.generateSessionID(proxyCertChain[0].getPublicKey()); } catch (GeneralSecurityException e) { logger.error("Error while generating the session ID." + e); throw new DelegationException("Failed to generate the session ID."); } logger.debug("Cache ID (delegation ID + session ID): " + cacheID); // Get the cache entry for this delegation ID GrDPStorageCacheElement cacheElem = null; try { cacheElem = m_storage.findGrDPStorageCacheElement(cacheID, clientDN); } catch (GrDPStorageException e) { logger.error("Failed to get certificate request information from storage.", e); throw new DelegationException("Internal failure."); } // Check if the delegation request existed if (cacheElem == null) { logger.info("Could not find cache ID '" + cacheID + "' for DN '" + clientDN + "' in cache."); throw new DelegationException("Could not find a proper delegation request"); } logger.debug("Got from cache element for cache ID '" + cacheID + "' and DN '" + clientDN + "'"); // the public key of the cached certificate request has to // match the public key of the proxy certificate, otherwise // this is an answer to a different request PEMReader pemReader = new PEMReader(new StringReader(cacheElem.getCertificateRequest())); PKCS10CertificationRequest req; try { req = (PKCS10CertificationRequest) pemReader.readObject(); } catch (IOException e1) { logger.error("Could not load the original certificate request from cache."); throw new DelegationException( "Could not load the original certificate request from cache: " + e1.getMessage()); } if (req == null) { logger.error("Could not load the original certificate request from cache."); throw new DelegationException("Could not load the original certificate request from cache."); } try { if (!req.getPublicKey().equals(proxyCertChain[0].getPublicKey())) { logger.error("The proxy and the original request's public key do not match."); logger.error("Proxy public key: " + proxyCertChain[0].getPublicKey()); logger.error("Request public key: " + req.getPublicKey()); throw new DelegationException("The proxy and the original request's public key do not match."); } } catch (GeneralSecurityException ge) { logger.error("Error while decoding the certificate request: " + ge); throw new DelegationException("Error while decoding the certificate request."); } // Add the private key to the proxy certificate chain and check it was ok String completeProxy = getProxyWithPrivateKey(proxyCertChain, cacheElem.getPrivateKey()); if (completeProxy == null) { logger.error("Failed to add private key to the proxy certificate chain."); throw new DelegationException("Could not properly process given proxy."); } // Save the proxy in proxy storage (copying the rest from the info taken // from the cache) try { GrDPStorageElement elem = m_storage.findGrDPStorageElement(delegationID, clientDN); if (elem != null) { elem.setCertificate(completeProxy); elem.setTerminationTime(proxyCertChain[0].getNotAfter()); m_storage.updateGrDPStorageElement(elem); } else { elem = new GrDPStorageElement(); elem.setDelegationID(delegationID); elem.setDN(clientDN); elem.setVomsAttributes(clientVOMSAttributes); elem.setCertificate(completeProxy); elem.setTerminationTime(proxyCertChain[0].getNotAfter()); m_storage.insertGrDPStorageElement(elem); } } catch (GrDPStorageException e) { logger.error("Failed to put certificate request in storage.", e); throw new DelegationException("Internal failure: " + e.getMessage()); } logger.debug("Delegation finished successfully."); // Remove the credential from storage cache try { m_storage.deleteGrDPStorageCacheElement(cacheID, clientDN); } catch (GrDPStorageException e) { logger.warn("Failed to remove credential from storage cache."); } }
From source file:org.glite.security.util.proxy.ProxyCertificateGenerator.java
License:Apache License
/** * Create a new proxy cert generator based on certification request and a certificate chain. Used for example when * creating a proxy certificate on the client side from certificate request coming from a service. * // w ww . ja v a2 s.co m * @param parentCertChain The parent cert chain of the proxy. * @param certReq The certification request to generate the certificate from. * @throws InvalidKeyException Thrown if the public key in the request is invalid. * @throws NoSuchAlgorithmException Thrown if the request uses unsupported algorithm. * @throws NoSuchProviderException Thrown if the bouncycastle provider was not found. */ public ProxyCertificateGenerator(X509Certificate[] parentCertChain, PKCS10CertificationRequest certReq) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException { this(parentCertChain); // m_certReq = certReq; m_publicKey = certReq.getPublicKey(); m_newDN = certReq.getCertificationRequestInfo().getSubject(); /* * // test for DN violation, the new DN must be composed of the parentDN // and and additional CN component. DN * baseDN = DNHandler.getSubject(m_parentCert); DN reqSubject = DNHandler.getDN(m_newDN); try{ * ProxyCertUtil.checkProxyDN(baseDN, reqSubject); } catch(IllegalArgumentException e){ throw new * IllegalArgumentException("Got an invalid proxy request subject, '" + reqSubject + * "' is not a valid proxy subject for '" + baseDN + "', error was: " + e.getMessage()); } */ // in case the parent was unknown type, deduce the type from the cert // req. in case it's not legacy and not set later, use default in generate(). if (m_type == ProxyCertificateInfo.UNKNOWN_PROXY_TYPE) { if (ProxyCertificateInfo.isLegacyDN(m_newDN)) { m_type = ProxyCertificateInfo.LEGACY_PROXY; } } // if the proxy is not legacy proxy, try to figure out the serial number from the DN of the request. if (m_type != ProxyCertificateInfo.LEGACY_PROXY) { BigInteger sn = ProxyCertUtil.getSN(m_newDN); if (sn != null) { m_serialNumber = sn; } } m_certGen = new X509V3CertificateGenerator(); }
From source file:org.globus.gsi.bc.BouncyCastleCertProcessingFactory.java
License:Apache License
/** * Creates a proxy certificate from the certificate request. (Signs a certificate request creating a new * certificate)// ww w .j a va2 s .c o m * * @see #createProxyCertificate(X509Certificate, PrivateKey, PublicKey, int, int, X509ExtensionSet, * String) createProxyCertificate * @param certRequestInputStream * the input stream to read the certificate request from. * @param cert * the issuer certificate * @param privateKey * the private key to sign the new certificate with. * @param lifetime * lifetime of the new certificate in seconds. If 0 (or less then) the new certificate will * have the same lifetime as the issuing certificate. * @param delegationMode * the type of proxy credential to create * @param extSet * a set of X.509 extensions to be included in the new proxy certificate. Can be null. If * delegation mode is {@link org.globus.gsi.GSIConstants.CertificateType#GSI_3_RESTRICTED_PROXY * GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY} or {@link org.globus.gsi.GSIConstants.CertificateType#GSI_4_RESTRICTED_PROXY * GSIConstants.CertificateType.GSI_4_RESTRICTED_PROXY} then * {@link org.globus.gsi.proxy.ext.ProxyCertInfoExtension ProxyCertInfoExtension} must be * present in the extension set. * @param cnValue * the value of the CN component of the subject of the new certificate. If null, the defaults * will be used depending on the proxy certificate type created. * @return <code>X509Certificate</code> the new proxy certificate * @exception IOException * if error reading the certificate request * @exception GeneralSecurityException * if a security error occurs. * @deprecated */ public X509Certificate createCertificate(InputStream certRequestInputStream, X509Certificate cert, PrivateKey privateKey, int lifetime, int delegationMode, X509ExtensionSet extSet, String cnValue) throws IOException, GeneralSecurityException { ASN1InputStream derin = new ASN1InputStream(certRequestInputStream); ASN1Primitive reqInfo = derin.readObject(); PKCS10CertificationRequest certReq = new PKCS10CertificationRequest((ASN1Sequence) reqInfo); boolean rs = certReq.verify(); if (!rs) { String err = i18n.getMessage("certReqVerification"); throw new GeneralSecurityException(err); } return createProxyCertificate(cert, privateKey, certReq.getPublicKey(), lifetime, delegationMode, extSet, cnValue); }
From source file:org.globus.gsi.bc.BouncyCastleCertProcessingFactory.java
License:Apache License
/** * Creates a proxy certificate from the certificate request. (Signs a certificate request creating a new * certificate)/*from w w w . ja v a 2 s.c om*/ * * @see #createProxyCertificate(X509Certificate, PrivateKey, PublicKey, int, int, X509ExtensionSet, * String) createProxyCertificate * @param certRequestInputStream * the input stream to read the certificate request from. * @param cert * the issuer certificate * @param privateKey * the private key to sign the new certificate with. * @param lifetime * lifetime of the new certificate in seconds. If 0 (or less then) the new certificate will * have the same lifetime as the issuing certificate. * @param certType * the type of proxy credential to create * @param extSet * a set of X.509 extensions to be included in the new proxy certificate. Can be null. If * delegation mode is {@link org.globus.gsi.GSIConstants.CertificateType#GSI_3_RESTRICTED_PROXY * GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY} or {@link org.globus.gsi.GSIConstants.CertificateType#GSI_4_RESTRICTED_PROXY * GSIConstants.CertificateType.GSI_4_RESTRICTED_PROXY} then * {@link org.globus.gsi.proxy.ext.ProxyCertInfoExtension ProxyCertInfoExtension} must be * present in the extension set. * @param cnValue * the value of the CN component of the subject of the new certificate. If null, the defaults * will be used depending on the proxy certificate type created. * @return <code>X509Certificate</code> the new proxy certificate * @exception IOException * if error reading the certificate request * @exception GeneralSecurityException * if a security error occurs. */ public X509Certificate createCertificate(InputStream certRequestInputStream, X509Certificate cert, PrivateKey privateKey, int lifetime, GSIConstants.CertificateType certType, X509ExtensionSet extSet, String cnValue) throws IOException, GeneralSecurityException { ASN1InputStream derin = new ASN1InputStream(certRequestInputStream); ASN1Primitive reqInfo = derin.readObject(); PKCS10CertificationRequest certReq = new PKCS10CertificationRequest((ASN1Sequence) reqInfo); boolean rs = certReq.verify(); if (!rs) { String err = i18n.getMessage("certReqVerification"); throw new GeneralSecurityException(err); } return createProxyCertificate(cert, privateKey, certReq.getPublicKey(), lifetime, certType, extSet, cnValue); }
From source file:org.qipki.ca.domain.ca.CAMixin.java
License:Open Source License
@Override public X509Certificate sign(X509Profile x509profile, PKCS10CertificationRequest pkcs10) { LOGGER.debug(/*w w w . j av a 2s . c om*/ "Handling a PKCS#10 Certificate Signing Request using X509Profile " + x509profile.name().get()); try { ensureX509ProfileIsAllowed(x509profile); List<X509ExtensionHolder> extensions = x509ExtReader.extractRequestedExtensions(pkcs10); ensureNoIllegalRequestedExtensions(extensions); // Adding extensions commons to all profiles SubjectKeyIdentifier subjectKeyID = x509ExtBuilder.buildSubjectKeyIdentifier(pkcs10.getPublicKey()); extensions.add(new X509ExtensionHolder(X509Extensions.SubjectKeyIdentifier, false, subjectKeyID)); AuthorityKeyIdentifier authKeyID = x509ExtBuilder .buildAuthorityKeyIdentifier(certificate().getPublicKey()); extensions.add(new X509ExtensionHolder(X509Extensions.AuthorityKeyIdentifier, false, authKeyID)); // Applying X509Profile on issued X509Certificate if (x509profile.basicConstraints().get().subjectIsCA().get()) { BasicConstraints bc = x509ExtBuilder .buildCABasicConstraints(x509profile.basicConstraints().get().pathLengthConstraint().get()); extensions.add(new X509ExtensionHolder(X509Extensions.BasicConstraints, x509profile.basicConstraints().get().critical().get(), bc)); } else { BasicConstraints bc = x509ExtBuilder.buildNonCABasicConstraints(); extensions.add(new X509ExtensionHolder(X509Extensions.BasicConstraints, x509profile.basicConstraints().get().critical().get(), bc)); } KeyUsage keyUsages = x509ExtBuilder.buildKeyUsages(x509profile.keyUsages().get().keyUsages().get()); extensions.add(new X509ExtensionHolder(X509Extensions.KeyUsage, x509profile.keyUsages().get().critical().get(), keyUsages)); ExtendedKeyUsage extendedKeyUsage = x509ExtBuilder .buildExtendedKeyUsage(x509profile.extendedKeyUsages().get().extendedKeyUsages().get()); extensions.add(new X509ExtensionHolder(X509Extensions.ExtendedKeyUsage, x509profile.extendedKeyUsages().get().critical().get(), extendedKeyUsage)); NetscapeCertType netscapeCertType = x509ExtBuilder .buildNetscapeCertTypes(x509profile.netscapeCertTypes().get().netscapeCertTypes().get()); extensions.add(new X509ExtensionHolder(MiscObjectIdentifiers.netscapeCertType, x509profile.netscapeCertTypes().get().critical().get(), netscapeCertType)); String[] crlDistPoints = gatherCRLDistributionPoints(); if (crlDistPoints.length > 0) { CRLDistPoint crlDistPointsExt = x509ExtBuilder .buildCRLDistributionPoints(certificate().getSubjectX500Principal(), crlDistPoints); extensions.add( new X509ExtensionHolder(X509Extensions.CRLDistributionPoints, false, crlDistPointsExt)); } DistinguishedName issuerDN = new DistinguishedName(certificate().getSubjectX500Principal()); DistinguishedName subjectDN = new DistinguishedName(pkcs10.getCertificationRequestInfo().getSubject()); X509Certificate certificate = x509Generator.generateX509Certificate(privateKey(), issuerDN, BigInteger.probablePrime(120, new SecureRandom()), subjectDN, pkcs10.getPublicKey(), Duration.standardDays(x509profile.validityDays().get()), extensions); return certificate; } catch (GeneralSecurityException ex) { LOGGER.error(ex.getMessage(), ex); throw new QiPkiFailure("Unable to enroll PKCS#10", ex); } }
From source file:org.signserver.module.xmlsigner.AnySignerTest.java
License:Open Source License
@Test public void test01GenerateKey() throws Exception { final char[] authCode = "foo123".toCharArray(); final String newKeyAlias = "newkey0001"; final String actualNewAlias = workerSession.generateSignerKey(WORKERID, "RSA", "2048", newKeyAlias, authCode);/*from ww w. ja v a 2 s . c o m*/ assertEquals("alias", newKeyAlias, actualNewAlias); final Collection<KeyTestResult> results = workerSession.testKey(WORKERID, newKeyAlias, authCode); final KeyTestResult result = results.iterator().next(); assertEquals("alias in result", newKeyAlias, result.getAlias()); assertTrue("test result", result.isSuccess()); final KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(new FileInputStream(keystoreFile), authCode); final PublicKey pubKey = keyStore.getCertificate(newKeyAlias).getPublicKey(); final byte[] pubKeyBytes = pubKey.getEncoded(); final String expectedKeyHash = createKeyHash(pubKeyBytes); final String actualKeyHash = result.getPublicKeyHash(); assertEquals("key hash", expectedKeyHash, actualKeyHash); // Set new key as NEXTCERTSIGNKEY workerSession.setWorkerProperty(WORKERID, "NEXTCERTSIGNKEY", newKeyAlias); workerSession.reloadConfiguration(WORKERID); // Generate CSR final PKCS10CertReqInfo certReqInfo = new PKCS10CertReqInfo("SHA1WithRSA", "CN=test01GenerateKey,C=SE", null); Base64SignerCertReqData data = (Base64SignerCertReqData) workerSession.getCertificateRequest(WORKERID, certReqInfo, false, false); byte[] reqBytes = data.getBase64CertReq(); final PKCS10CertificationRequest req = new PKCS10CertificationRequest(Base64.decode(reqBytes)); final PublicKey actualPubKey = req.getPublicKey(); assertEquals("key in request", pubKey, actualPubKey); // Test that the DN is in the correct order String actualDN = req.getCertificationRequestInfo().getSubject().toString(); assertTrue("dn: " + actualDN, actualDN.startsWith("CN=test01GenerateKey") && actualDN.endsWith("C=SE")); }
From source file:org.signserver.module.xmlsigner.AnySignerTest.java
License:Open Source License
/** * Test key generation of a ECDSA curve. * @throws Exception in case of error//w ww .ja va2s . com */ @Test public void test02GenerateKeyECDSA() throws Exception { final char[] authCode = "foo123".toCharArray(); final String newKeyAlias = "newkey0002"; final String actualNewAlias = workerSession.generateSignerKey(WORKERID, "ECDSA", "secp256r1", newKeyAlias, authCode); assertEquals("alias", newKeyAlias, actualNewAlias); final Collection<KeyTestResult> results = workerSession.testKey(WORKERID, newKeyAlias, authCode); final KeyTestResult result = results.iterator().next(); assertEquals("alias in result", newKeyAlias, result.getAlias()); assertTrue("test result", result.isSuccess()); final KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(new FileInputStream(keystoreFile), authCode); final PublicKey pubKey = keyStore.getCertificate(newKeyAlias).getPublicKey(); final byte[] pubKeyBytes = pubKey.getEncoded(); final String expectedKeyHash = createKeyHash(pubKeyBytes); final String actualKeyHash = result.getPublicKeyHash(); assertEquals("keyAlg", "EC", pubKey.getAlgorithm()); assertEquals("key hash", expectedKeyHash, actualKeyHash); // Set new key as NEXTCERTSIGNKEY workerSession.setWorkerProperty(WORKERID, "NEXTCERTSIGNKEY", newKeyAlias); workerSession.reloadConfiguration(WORKERID); // Generate CSR final PKCS10CertReqInfo certReqInfo = new PKCS10CertReqInfo("SHA1WithECDSA", "CN=test02GenerateKey", null); Base64SignerCertReqData data = (Base64SignerCertReqData) workerSession.getCertificateRequest(WORKERID, certReqInfo, false, false); byte[] reqBytes = data.getBase64CertReq(); final PKCS10CertificationRequest req = new PKCS10CertificationRequest(Base64.decode(reqBytes)); final PublicKey actualPubKey = req.getPublicKey(); assertEquals("key in request", pubKey, actualPubKey); }
From source file:org.signserver.module.xmlsigner.AnySignerTest.java
License:Open Source License
@Test public void test03GenerateRequestNamedCurve() throws Exception { final boolean explicitEcc = false; // Generate CSR final PKCS10CertReqInfo certReqInfo = new PKCS10CertReqInfo("SHA1WithECDSA", "CN=test02GenerateKey", null); Base64SignerCertReqData data = (Base64SignerCertReqData) workerSession.getCertificateRequest(WORKERID, certReqInfo, explicitEcc, false); byte[] reqBytes = data.getBase64CertReq(); final PKCS10CertificationRequest req = new PKCS10CertificationRequest(Base64.decode(reqBytes)); final PublicKey actualPubKey = req.getPublicKey(); final PublicKey afterConvert = ECKeyUtil.publicToExplicitParameters(actualPubKey, "BC"); // The following assertion assumes that publicToExplicitParameters // returns a new/different PublicKey instance if it was not already // converted and if it already was explicit the same instance was // returned/*w w w . j ava 2 s . c o m*/ // Not the same object assertNotSame("Not converted to explicit", actualPubKey.hashCode(), afterConvert.hashCode()); }
From source file:org.signserver.module.xmlsigner.AnySignerTest.java
License:Open Source License
@Test public void test04GenerateRequestExplicitParams() throws Exception { final boolean explicitEcc = true; // Generate CSR final PKCS10CertReqInfo certReqInfo = new PKCS10CertReqInfo("SHA1WithECDSA", "CN=test02GenerateKey", null); Base64SignerCertReqData data = (Base64SignerCertReqData) workerSession.getCertificateRequest(WORKERID, certReqInfo, explicitEcc, false); byte[] reqBytes = data.getBase64CertReq(); final PKCS10CertificationRequest req = new PKCS10CertificationRequest(Base64.decode(reqBytes)); final PublicKey actualPubKey = req.getPublicKey(); final PublicKey afterConvert = ECKeyUtil.publicToExplicitParameters(actualPubKey, "BC"); // The following assertion assumes that publicToExplicitParameters // returns a new/different PublicKey instance if it was not already // converted and if it already was explicit the same instance was // returned// ww w . j a v a 2s . c o m // The same object assertTrue("Not converted to explicit", actualPubKey.hashCode() == afterConvert.hashCode()); }
From source file:org.signserver.server.cryptotokens.SoftCryptoTokenTest.java
License:Open Source License
@Test public void test01BasicTests() throws Exception { StaticWorkerStatus stat = (StaticWorkerStatus) workerSession.getStatus(88); assertTrue(stat.getTokenStatus() == WorkerStatus.STATUS_OFFLINE); PKCS10CertReqInfo crInfo = new PKCS10CertReqInfo("SHA1WithRSA", "CN=TEST1", null); ICertReqData reqData = workerSession.getCertificateRequest(88, crInfo, false); assertNotNull(reqData);//from w ww .j av a 2 s . co m assertTrue(reqData instanceof Base64SignerCertReqData); PKCS10CertificationRequest pkcs10 = new PKCS10CertificationRequest( Base64.decode(((Base64SignerCertReqData) reqData).getBase64CertReq())); assertTrue(pkcs10.getPublicKey() != null); KeyPair dummyCAKeys = KeyTools.genKeys("2048", "RSA"); X509Certificate cert = CertTools.genSelfCert(pkcs10.getCertificationRequestInfo().getSubject().toString(), 10, null, dummyCAKeys.getPrivate(), pkcs10.getPublicKey(), "SHA1WithRSA", false); workerSession.uploadSignerCertificate(88, cert.getEncoded(), GlobalConfiguration.SCOPE_GLOBAL); workerSession.reloadConfiguration(88); stat = (StaticWorkerStatus) workerSession.getStatus(88); assertTrue(stat.getActiveSignerConfig().getProperty("KEYDATA") != null); assertTrue(stat.getTokenStatus() == WorkerStatus.STATUS_ACTIVE); int reqid = 12; ArrayList<byte[]> signrequests = new ArrayList<byte[]>(); byte[] signreq1 = "Hello World".getBytes(); byte[] signreq2 = "Hello World2".getBytes(); signrequests.add(signreq1); signrequests.add(signreq2); MRTDSignResponse res = (MRTDSignResponse) workerSession.process(88, new MRTDSignRequest(reqid, signrequests), new RequestContext()); assertTrue(res != null); assertTrue(reqid == res.getRequestID()); Certificate signercert = res.getSignerCertificate(); assertNotNull(signercert); Cipher c = Cipher.getInstance("RSA", "BC"); c.init(Cipher.DECRYPT_MODE, signercert); byte[] signres1 = c.doFinal((byte[]) ((ArrayList<?>) res.getProcessedData()).get(0)); if (!arrayEquals(signreq1, signres1)) { assertTrue("First MRTD doesn't match with request", false); } byte[] signres2 = c.doFinal((byte[]) ((ArrayList<?>) res.getProcessedData()).get(1)); if (!arrayEquals(signreq2, signres2)) { assertTrue("Second MRTD doesn't match with request", false); } assertTrue(signercert.getPublicKey().equals(pkcs10.getPublicKey())); reqData = workerSession.getCertificateRequest(88, crInfo, false); assertNotNull(reqData); assertTrue(reqData instanceof Base64SignerCertReqData); PKCS10CertificationRequest pkcs10_2 = new PKCS10CertificationRequest( Base64.decode(((Base64SignerCertReqData) reqData).getBase64CertReq())); assertTrue(pkcs10_2.getPublicKey() != null); assertFalse(pkcs10_2.getPublicKey().equals(pkcs10.getPublicKey())); workerSession.deactivateSigner(88); stat = (StaticWorkerStatus) workerSession.getStatus(88); assertTrue(stat.getTokenStatus() == WorkerStatus.STATUS_OFFLINE); try { res = (MRTDSignResponse) workerSession.process(88, new MRTDSignRequest(reqid, signrequests), new RequestContext()); assertTrue(false); } catch (CryptoTokenOfflineException e) { } workerSession.activateSigner(88, "anypwd"); stat = (StaticWorkerStatus) workerSession.getStatus(88); assertTrue(stat.getTokenStatus() == WorkerStatus.STATUS_ACTIVE); res = (MRTDSignResponse) workerSession.process(88, new MRTDSignRequest(reqid, signrequests), new RequestContext()); }