List of usage examples for java.security KeyPair getPublic
public PublicKey getPublic()
From source file:com.netscape.cms.servlet.csadmin.ConfigurationUtils.java
public static void storeKeyPair(IConfigStore config, String tag, KeyPair pair) throws TokenException, EBaseException { logger.debug("ConfigurationUtils: storeKeyPair(" + tag + ")"); PublicKey publicKey = pair.getPublic(); if (publicKey instanceof RSAPublicKey) { RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; byte modulus[] = rsaPublicKey.getModulus().toByteArray(); config.putString(PCERT_PREFIX + tag + ".pubkey.modulus", CryptoUtil.byte2string(modulus)); byte exponent[] = rsaPublicKey.getPublicExponent().toByteArray(); config.putString(PCERT_PREFIX + tag + ".pubkey.exponent", CryptoUtil.byte2string(exponent)); } else { // ECC logger.debug("ConfigurationUtils: Public key class: " + publicKey.getClass().getName()); byte encoded[] = publicKey.getEncoded(); config.putString(PCERT_PREFIX + tag + ".pubkey.encoded", CryptoUtil.byte2string(encoded)); }/*from w w w . j a va2 s .c om*/ PrivateKey privateKey = (PrivateKey) pair.getPrivate(); byte id[] = privateKey.getUniqueID(); String kid = CryptoUtil.encodeKeyID(id); config.putString(PCERT_PREFIX + tag + ".privkey.id", kid); String keyAlgo = config.getString(PCERT_PREFIX + tag + ".signingalgorithm"); setSigningAlgorithm(tag, keyAlgo, config); }
From source file:org.ejbca.core.protocol.cmp.EndEntityCertAuthModuleTest.java
private AuthenticationToken createTokenWithCert(String adminName, AuthenticationSubject subject, KeyPair keys, int _caid, int eepid, int cpid) { // A small check if we have added a "fail" credential to the subject. // If we have we will return null, so we can test authentication failure. Set<?> usercredentials = subject.getCredentials(); if ((usercredentials != null) && (usercredentials.size() > 0)) { Object o = usercredentials.iterator().next(); if (o instanceof String) { String str = (String) o; if (StringUtils.equals("fail", str)) { return null; }/*w w w . ja va 2 s .c om*/ } } X509Certificate certificate = null; // If there was no certificate input, create a self signed String dn = "CN=" + adminName; // If we have created a subject with an X500Principal we will use this DN to create the dummy certificate. { Set<Principal> principals = subject.getPrincipals(); if ((principals != null) && (principals.size() > 0)) { Principal p = principals.iterator().next(); if (p instanceof X500Principal) { X500Principal xp = (X500Principal) p; dn = xp.getName(); } } } try { createUser(adminName, dn, "foo123", true, _caid, eepid, cpid); } catch (AuthorizationDeniedException e1) { throw new IllegalStateException(e1.getLocalizedMessage(), e1); } catch (UserDoesntFullfillEndEntityProfile e1) { throw new IllegalStateException(e1.getLocalizedMessage(), e1); } catch (WaitingForApprovalException e1) { throw new IllegalStateException(e1.getLocalizedMessage(), e1); } catch (EjbcaException e1) { throw new IllegalStateException(e1.getLocalizedMessage(), e1); } catch (Exception e1) { throw new IllegalStateException(e1.getLocalizedMessage(), e1); } try { certificate = (X509Certificate) signSession.createCertificate(ADMIN, adminName, "foo123", new PublicKeyWrapper(keys.getPublic())); } catch (ObjectNotFoundException e) { throw new IllegalStateException(e.getLocalizedMessage(), e); } catch (CADoesntExistsException e) { throw new IllegalStateException(e.getLocalizedMessage(), e); } catch (EjbcaException e) { throw new IllegalStateException(e.getLocalizedMessage(), e); } catch (AuthorizationDeniedException e) { throw new IllegalStateException(e.getLocalizedMessage(), e); } catch (CesecoreException e) { throw new IllegalStateException(e.getLocalizedMessage(), e); } assertNotNull("Failed to create a test user certificate", certificate); // We cannot use the X509CertificateAuthenticationToken here, since it can only be used internally in a JVM. AuthenticationToken result = new TestX509CertificateAuthenticationToken(certificate); assertNotNull("Failed to create authentication token.", result); return result; }
From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
protected void generatePkcs10Request() throws Exception { // Change token to P12 UserMatch usermatch = new UserMatch(); usermatch.setMatchwith(UserMatch.MATCH_WITH_USERNAME); usermatch.setMatchtype(UserMatch.MATCH_TYPE_EQUALS); usermatch.setMatchvalue(CA1_WSTESTUSER1); List<UserDataVOWS> userdatas = ejbcaraws.findUser(usermatch); assertTrue(userdatas != null);/* ww w. ja va 2s .c o m*/ assertTrue(userdatas.size() == 1); userdatas.get(0).setTokenType(UserDataVOWS.TOKEN_TYPE_USERGENERATED); userdatas.get(0).setStatus(UserDataVOWS.STATUS_NEW); userdatas.get(0).setPassword(PASSWORD); userdatas.get(0).setClearPwd(true); ejbcaraws.editUser(userdatas.get(0)); KeyPair keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA); PKCS10CertificationRequest pkcs10 = CertTools.genPKCS10CertificationRequest("SHA1WithRSA", CertTools.stringToBcX500Name("CN=NOUSED"), keys.getPublic(), new DERSet(), keys.getPrivate(), null); CertificateResponse certenv = ejbcaraws.pkcs10Request(CA1_WSTESTUSER1, PASSWORD, new String(Base64.encode(pkcs10.getEncoded())), null, CertificateHelper.RESPONSETYPE_CERTIFICATE); assertNotNull(certenv); assertTrue(certenv.getResponseType().equals(CertificateHelper.RESPONSETYPE_CERTIFICATE)); X509Certificate cert = (X509Certificate) CertificateHelper.getCertificate(certenv.getData()); assertNotNull(cert); assertTrue(cert.getSubjectDN().toString().equals(getDN(CA1_WSTESTUSER1))); ejbcaraws.editUser(userdatas.get(0)); certenv = ejbcaraws.pkcs10Request(CA1_WSTESTUSER1, PASSWORD, new String(Base64.encode(pkcs10.getEncoded())), null, CertificateHelper.RESPONSETYPE_PKCS7); assertTrue(certenv.getResponseType().equals(CertificateHelper.RESPONSETYPE_PKCS7)); CMSSignedData cmsSignedData = new CMSSignedData(CertificateHelper.getPKCS7(certenv.getData())); assertTrue(cmsSignedData != null); Store certStore = cmsSignedData.getCertificates(); assertTrue(certStore.getMatches(null).size() == 1); }
From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
private CertReqMsg createCrmfRequest(final String issuerDN, final String userDN, final KeyPair keys, final String extensionOid) throws IOException { CertTemplateBuilder myCertTemplate = new CertTemplateBuilder(); myCertTemplate.setIssuer(new X500Name(issuerDN)); myCertTemplate.setSubject(new X500Name(userDN)); byte[] bytes = keys.getPublic().getEncoded(); ByteArrayInputStream bIn = new ByteArrayInputStream(bytes); ASN1InputStream dIn = new ASN1InputStream(bIn); try {// w w w .java 2 s. c om SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject()); myCertTemplate.setPublicKey(keyInfo); } finally { dIn.close(); } // If we did not pass any extensions as parameter, we will create some of our own, standard ones ExtensionsGenerator extgen = new ExtensionsGenerator(); extgen.addExtension(new ASN1ObjectIdentifier(extensionOid), false, new DEROctetString("foo123".getBytes())); myCertTemplate.setExtensions(extgen.generate()); CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null); CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, null, null); return myCertReqMsg; }
From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
protected void genTokenCertificates(boolean onlyOnce) throws Exception { GlobalConfiguration gc = (GlobalConfiguration) globalConfigurationSession .getCachedConfiguration(GlobalConfiguration.GLOBAL_CONFIGURATION_ID); boolean originalProfileSetting = gc.getEnableEndEntityProfileLimitations(); gc.setEnableEndEntityProfileLimitations(false); globalConfigurationSession.saveConfiguration(intAdmin, gc); if (certificateProfileSession.getCertificateProfileId(WSTESTPROFILE) != 0) { certificateProfileSession.removeCertificateProfile(intAdmin, WSTESTPROFILE); }// w w w . ja v a 2 s . co m { final CertificateProfile profile = new CertificateProfile( CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); profile.setAllowValidityOverride(true); certificateProfileSession.addCertificateProfile(intAdmin, WSTESTPROFILE, profile); } // first a simple test UserDataVOWS tokenUser1 = new UserDataVOWS(); tokenUser1.setUsername("WSTESTTOKENUSER1"); tokenUser1.setPassword(PASSWORD); tokenUser1.setClearPwd(true); tokenUser1.setSubjectDN("CN=WSTESTTOKENUSER1"); tokenUser1.setCaName(getAdminCAName()); tokenUser1.setEmail(null); tokenUser1.setSubjectAltName(null); tokenUser1.setStatus(UserDataVOWS.STATUS_NEW); tokenUser1.setTokenType(UserDataVOWS.TOKEN_TYPE_USERGENERATED); tokenUser1.setEndEntityProfileName("EMPTY"); tokenUser1.setCertificateProfileName("ENDUSER"); KeyPair basickeys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA); PKCS10CertificationRequest basicpkcs10 = CertTools.genPKCS10CertificationRequest("SHA256WithRSA", CertTools.stringToBcX500Name("CN=NOUSED"), basickeys.getPublic(), new DERSet(), basickeys.getPrivate(), null); ArrayList<TokenCertificateRequestWS> requests = new ArrayList<TokenCertificateRequestWS>(); TokenCertificateRequestWS tokenCertReqWS = new TokenCertificateRequestWS(); tokenCertReqWS.setCAName(getAdminCAName()); tokenCertReqWS.setCertificateProfileName(WSTESTPROFILE); tokenCertReqWS.setValidityIdDays("1"); tokenCertReqWS.setPkcs10Data(basicpkcs10.getEncoded()); tokenCertReqWS.setType(HardTokenConstants.REQUESTTYPE_PKCS10_REQUEST); requests.add(tokenCertReqWS); tokenCertReqWS = new TokenCertificateRequestWS(); tokenCertReqWS.setCAName(getAdminCAName()); tokenCertReqWS.setCertificateProfileName("ENDUSER"); tokenCertReqWS.setKeyalg("RSA"); tokenCertReqWS.setKeyspec("1024"); tokenCertReqWS.setType(HardTokenConstants.REQUESTTYPE_KEYSTORE_REQUEST); requests.add(tokenCertReqWS); HardTokenDataWS hardTokenDataWS = setupHardTokenDataWS("12345678"); List<TokenCertificateResponseWS> responses = ejbcaraws.genTokenCertificates(tokenUser1, requests, hardTokenDataWS, true, false); assertTrue(responses.size() == 2); Iterator<TokenCertificateResponseWS> iter = responses.iterator(); TokenCertificateResponseWS next = iter.next(); assertTrue(next.getType() == HardTokenConstants.RESPONSETYPE_CERTIFICATE_RESPONSE); Certificate cert = next.getCertificate(); X509Certificate realcert = (X509Certificate) CertificateHelper.getCertificate(cert.getCertificateData()); assertNotNull(realcert); assertTrue(realcert.getNotAfter().toString(), realcert.getNotAfter().before(new Date(System.currentTimeMillis() + 2 * 24 * 3600 * 1000))); next = iter.next(); assertTrue(next.getType() == HardTokenConstants.RESPONSETYPE_KEYSTORE_RESPONSE); KeyStore keyStore = next.getKeyStore(); java.security.KeyStore realKeyStore = KeyStoreHelper.getKeyStore(keyStore.getKeystoreData(), HardTokenConstants.TOKENTYPE_PKCS12, PASSWORD); assertTrue(realKeyStore.containsAlias("WSTESTTOKENUSER1")); assertTrue(((X509Certificate) realKeyStore.getCertificate("WSTESTTOKENUSER1")).getNotAfter() .after(new Date(System.currentTimeMillis() + 48 * 24 * 3600 * 1000))); if (!onlyOnce) { try { responses = ejbcaraws.genTokenCertificates(tokenUser1, requests, hardTokenDataWS, false, false); assertTrue(false); } catch (HardTokenExistsException_Exception e) { } } certificateProfileSession.removeCertificateProfile(intAdmin, WSTESTPROFILE); gc.setEnableEndEntityProfileLimitations(originalProfileSetting); globalConfigurationSession.saveConfiguration(intAdmin, gc); }
From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
protected void errorOnGeneratePkcs10() throws Exception { // Add a user for this test purpose. UserDataVOWS user1 = new UserDataVOWS(); user1.setUsername("WSTESTUSER30"); user1.setPassword("foo1234"); user1.setClearPwd(true);// w w w . j a va 2 s. c o m user1.setSubjectDN("CN=WSTESTUSER30"); user1.setEmail(null); user1.setSubjectAltName(null); user1.setStatus(UserDataVOWS.STATUS_NEW); user1.setTokenType(UserDataVOWS.TOKEN_TYPE_USERGENERATED); user1.setEndEntityProfileName("EMPTY"); user1.setCertificateProfileName("ENDUSER"); user1.setCaName(getAdminCAName()); ejbcaraws.editUser(user1); KeyPair keys = null; PKCS10CertificationRequest pkcs10 = null; ErrorCode errorCode = null; // ///// Check Error.LOGIN_ERROR /////// keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA); pkcs10 = CertTools.genPKCS10CertificationRequest("SHA256WithRSA", CertTools.stringToBcX500Name("CN=WSTESTUSER30"), keys.getPublic(), new DERSet(), keys.getPrivate(), null); try { ejbcaraws.pkcs10Request("WSTESTUSER30", PASSWORD, new String(Base64.encode(pkcs10.getEncoded())), null, CertificateHelper.RESPONSETYPE_CERTIFICATE); } catch (EjbcaException_Exception e) { errorCode = e.getFaultInfo().getErrorCode(); } assertNotNull("error code should not be null", errorCode); assertEquals(errorCode.getInternalErrorCode(), org.cesecore.ErrorCode.LOGIN_ERROR.getInternalErrorCode()); errorCode = null; // ///// Check Error.USER_WRONG_STATUS /////// user1.setStatus(EndEntityConstants.STATUS_REVOKED); ejbcaraws.editUser(user1); keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA); pkcs10 = CertTools.genPKCS10CertificationRequest("SHA256WithRSA", CertTools.stringToBcX500Name("CN=WSTESTUSER30"), keys.getPublic(), new DERSet(), keys.getPrivate(), null); try { ejbcaraws.pkcs10Request("WSTESTUSER30", "foo1234", new String(Base64.encode(pkcs10.getEncoded())), null, CertificateHelper.RESPONSETYPE_CERTIFICATE); } catch (EjbcaException_Exception e) { errorCode = e.getFaultInfo().getErrorCode(); } assertNotNull("error code should not be null", errorCode); assertEquals(errorCode.getInternalErrorCode(), org.cesecore.ErrorCode.USER_WRONG_STATUS.getInternalErrorCode()); }
From source file:net.nicholaswilliams.java.licensing.encryption.TestRSAKeyPairGenerator.java
@Test public void testSaveKeysToProviders01() throws ClassNotFoundException, IllegalAccessException, InstantiationException { String pn = "com.nicholaswilliams.mock"; RSAKeyPairGeneratorInterface.GeneratedClassDescriptor privateKPDescriptor = new RSAKeyPairGeneratorInterface.GeneratedClassDescriptor(); privateKPDescriptor.setPackageName(pn); privateKPDescriptor.setClassName("TestPrivateKeyProvider01"); RSAKeyPairGeneratorInterface.GeneratedClassDescriptor publicKPDescriptor = new RSAKeyPairGeneratorInterface.GeneratedClassDescriptor(); publicKPDescriptor.setPackageName(pn); publicKPDescriptor.setClassName("TestPublicKeyProvider01"); KeyPair keyPair = this.generator.generateKeyPair(); this.generator.saveKeyPairToProviders(keyPair, privateKPDescriptor, publicKPDescriptor, "testPassword01".toCharArray()); /////////////////////// assertNotNull("The private key code should not be null.", privateKPDescriptor.getJavaFileContents()); assertTrue("The private key code should have length.", privateKPDescriptor.getJavaFileContents().length() > 0); Class<?> privateKPClass = this .compileClass(pn + ".TestPrivateKeyProvider01", privateKPDescriptor.getJavaFileContents()) .getClassLoader(null).loadClass(pn + ".TestPrivateKeyProvider01"); PrivateKeyDataProvider privateKeyDataProvider = (PrivateKeyDataProvider) privateKPClass.newInstance(); assertNotNull("The private key data provider should not be null.", privateKeyDataProvider); byte[] privateKeyData = privateKeyDataProvider.getEncryptedPrivateKeyData(); assertNotNull("The private key data should not be null.", privateKeyData); assertTrue("The private key data should have length.", privateKeyData.length > 0); PrivateKey privateKey = KeyFileUtilities.readEncryptedPrivateKey(privateKeyData, "testPassword01".toCharArray()); assertNotNull("The private key should not be null.", privateKey); assertEquals("The private key is not correct.", keyPair.getPrivate(), privateKey); /////////////////////// assertNotNull("The public key code should not be null.", publicKPDescriptor.getJavaFileContents()); assertTrue("The public key code should have length.", publicKPDescriptor.getJavaFileContents().length() > 0); Class<?> publicKPClass = this .compileClass(pn + ".TestPublicKeyProvider01", publicKPDescriptor.getJavaFileContents()) .getClassLoader(null).loadClass(pn + ".TestPublicKeyProvider01"); PublicKeyDataProvider publicKeyDataProvider = (PublicKeyDataProvider) publicKPClass.newInstance(); assertNotNull("The public key data provider should not be null.", publicKeyDataProvider); byte[] publicKeyData = publicKeyDataProvider.getEncryptedPublicKeyData(); assertNotNull("The public key data should not be null.", publicKeyData); assertTrue("The public key data should have length.", publicKeyData.length > 0); PublicKey publicKey = KeyFileUtilities.readEncryptedPublicKey(publicKeyData, "testPassword01".toCharArray()); assertNotNull("The public key should not be null.", publicKey); assertEquals("The public key is not correct.", keyPair.getPublic(), publicKey); }
From source file:org.alfresco.extension.countersign.signature.RepositoryManagedSignatureProvider.java
/** * Generate an X509 cert for use as the keystore cert chain * //from w w w. j a v a2 s. c om * @param keyPair * @return */ private X509Certificate generateCertificate(KeyPair keyPair, NodeRef person) { X509Certificate cert = null; int validDuration = Integer .parseInt(config.getProperty(RepositoryManagedSignatureProviderFactory.VALID_DURATION)); // get user's first and last name Map<QName, Serializable> props = serviceRegistry.getNodeService().getProperties(person); String firstName = String.valueOf(props.get(ContentModel.PROP_FIRSTNAME)); String lastName = String.valueOf(props.get(ContentModel.PROP_LASTNAME)); // backdate the start date by a day Calendar start = Calendar.getInstance(); start.add(Calendar.DATE, -1); java.util.Date startDate = start.getTime(); // what is the end date for this cert's validity? Calendar end = Calendar.getInstance(); end.add(Calendar.DATE, validDuration); java.util.Date endDate = end.getTime(); try { // This code works with newer versions of the BouncyCastle libraries, but not // the (severely outdated) version that ships with Alfresco /*X509v1CertificateBuilder certBuilder = new JcaX509v1CertificateBuilder( new X500Principal("CN=" + firstName + " " + lastName), BigInteger.ONE, startDate, cal.getTime(), new X500Principal("CN=" + firstName + " " + lastName), keyPair.getPublic()); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); AsymmetricKeyParameter keyParam = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded()); ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(keyParam); X509CertificateHolder certHolder = certBuilder.build(sigGen); // now lets convert this thing back to a regular old java cert CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream certIs = new ByteArrayInputStream(certHolder.getEncoded()); cert = (X509Certificate) cf.generateCertificate(certIs); certIs.close();*/ X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); X500Principal subjectName = new X500Principal("CN=" + firstName + " " + lastName); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setNotBefore(startDate); certGen.setNotAfter(endDate); certGen.setSubjectDN(subjectName); certGen.setPublicKey(keyPair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); // if we are actually generating a trusted cert, the action is a little different boolean generateTrusted = Boolean.parseBoolean( config.getProperty(RepositoryManagedSignatureProviderFactory.ENABLE_TRUSTED_CERTS)); if (generateTrusted) { KeyStore trustedKs = getTrustedKeyStore(); PrivateKey caKey = getCaKey(trustedKs); X509Certificate caCert = getCaCert(trustedKs); // set the issuer of the generated cert to the subject of the ca cert X500Principal caSubject = caCert.getSubjectX500Principal(); certGen.setIssuerDN(caSubject); //add the required extensions for the new cert certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.getPublic())); cert = certGen.generate(caKey, "BC"); //verify the cert cert.verify(caCert.getPublicKey()); } else { certGen.setIssuerDN(subjectName); cert = certGen.generate(keyPair.getPrivate(), "BC"); } } catch (CertificateException ce) { logger.error("CertificateException creating or validating X509 certificate for user: " + ce); throw new AlfrescoRuntimeException(ce.getMessage()); } catch (Exception ex) { logger.error("Unknown exception creating or validating X509 certificate for user : " + ex); ex.printStackTrace(); } return cert; }
From source file:net.nicholaswilliams.java.licensing.encryption.TestRSAKeyPairGenerator.java
@Test public void testSaveKeysToProviders03() throws ClassNotFoundException, IllegalAccessException, InstantiationException { String pn = "com.nicholaswilliams.last"; RSAKeyPairGeneratorInterface.GeneratedClassDescriptor privateKPDescriptor = new RSAKeyPairGeneratorInterface.GeneratedClassDescriptor(); privateKPDescriptor.setPackageName(pn); privateKPDescriptor.setClassName("TestPrivateKeyProvider03"); RSAKeyPairGeneratorInterface.GeneratedClassDescriptor publicKPDescriptor = new RSAKeyPairGeneratorInterface.GeneratedClassDescriptor(); publicKPDescriptor.setPackageName(pn); publicKPDescriptor.setClassName("TestPublicKeyProvider03"); KeyPair keyPair = this.generator.generateKeyPair(); this.generator.saveKeyPairToProviders(keyPair, privateKPDescriptor, publicKPDescriptor, "finalPasswordOne03".toCharArray(), "finalPasswordTwo03".toCharArray()); /////////////////////// assertNotNull("The private key code should not be null.", privateKPDescriptor.getJavaFileContents()); assertTrue("The private key code should have length.", privateKPDescriptor.getJavaFileContents().length() > 0); Class<?> privateKPClass = this .compileClass(pn + ".TestPrivateKeyProvider03", privateKPDescriptor.getJavaFileContents()) .getClassLoader(null).loadClass(pn + ".TestPrivateKeyProvider03"); PrivateKeyDataProvider privateKeyDataProvider = (PrivateKeyDataProvider) privateKPClass.newInstance(); assertNotNull("The private key data provider should not be null.", privateKeyDataProvider); byte[] privateKeyData = privateKeyDataProvider.getEncryptedPrivateKeyData(); assertNotNull("The private key data should not be null.", privateKeyData); assertTrue("The private key data should have length.", privateKeyData.length > 0); PrivateKey privateKey = KeyFileUtilities.readEncryptedPrivateKey(privateKeyData, "finalPasswordOne03".toCharArray()); assertNotNull("The private key should not be null.", privateKey); assertEquals("The private key is not correct.", keyPair.getPrivate(), privateKey); /////////////////////// assertNotNull("The public key code should not be null.", publicKPDescriptor.getJavaFileContents()); assertTrue("The public key code should have length.", publicKPDescriptor.getJavaFileContents().length() > 0); Class<?> publicKPClass = this .compileClass(pn + ".TestPublicKeyProvider03", publicKPDescriptor.getJavaFileContents()) .getClassLoader(null).loadClass(pn + ".TestPublicKeyProvider03"); PublicKeyDataProvider publicKeyDataProvider = (PublicKeyDataProvider) publicKPClass.newInstance(); assertNotNull("The public key data provider should not be null.", publicKeyDataProvider); byte[] publicKeyData = publicKeyDataProvider.getEncryptedPublicKeyData(); assertNotNull("The public key data should not be null.", publicKeyData); assertTrue("The public key data should have length.", publicKeyData.length > 0); PublicKey publicKey = KeyFileUtilities.readEncryptedPublicKey(publicKeyData, "finalPasswordTwo03".toCharArray()); assertNotNull("The public key should not be null.", publicKey); assertEquals("The public key is not correct.", keyPair.getPublic(), publicKey); }
From source file:org.apache.hadoop.gateway.services.security.impl.X509CertificateUtil.java
/** * Create a self-signed X.509 Certificate * @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB" * @param pair the KeyPair/*w w w. j a va2 s .c om*/ * @param days how many days from now the Certificate is valid for * @param algorithm the signing algorithm, eg "SHA1withRSA" */ public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm) throws GeneralSecurityException, IOException { PrivateKey privkey = pair.getPrivate(); Object x509CertImplObject = null; try { Date from = new Date(); Date to = new Date(from.getTime() + days * 86400000l); Class<?> certInfoClass = Class.forName(getX509CertInfoModuleName()); Constructor<?> certInfoConstr = certInfoClass.getConstructor(); Object certInfoObject = certInfoConstr.newInstance(); // CertificateValidity interval = new CertificateValidity(from, to); Class<?> certValidityClass = Class.forName(getX509CertifValidityModuleName()); Constructor<?> certValidityConstr = certValidityClass .getConstructor(new Class[] { Date.class, Date.class }); Object certValidityObject = certValidityConstr.newInstance(from, to); BigInteger sn = new BigInteger(64, new SecureRandom()); // X500Name owner = new X500Name(dn); Class<?> x500NameClass = Class.forName(getX509X500NameModuleName()); Constructor<?> x500NameConstr = x500NameClass.getConstructor(new Class[] { String.class }); Object x500NameObject = x500NameConstr.newInstance(dn); Method methodSET = certInfoObject.getClass().getMethod("set", String.class, Object.class); // info.set(X509CertInfo.VALIDITY, interval); methodSET.invoke(certInfoObject, getSetField(certInfoObject, "VALIDITY"), certValidityObject); // info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn)); Class<?> certificateSerialNumberClass = Class.forName(getCertificateSerialNumberModuleName()); Constructor<?> certificateSerialNumberConstr = certificateSerialNumberClass .getConstructor(new Class[] { BigInteger.class }); Object certificateSerialNumberObject = certificateSerialNumberConstr.newInstance(sn); methodSET.invoke(certInfoObject, getSetField(certInfoObject, "SERIAL_NUMBER"), certificateSerialNumberObject); // info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner)); try { Class<?> certificateSubjectNameClass = Class.forName(getCertificateSubjectNameModuleName()); Constructor<?> certificateSubjectNameConstr = certificateSubjectNameClass .getConstructor(new Class[] { x500NameClass }); Object certificateSubjectNameObject = certificateSubjectNameConstr.newInstance(x500NameObject); methodSET.invoke(certInfoObject, getSetField(certInfoObject, "SUBJECT"), certificateSubjectNameObject); } catch (InvocationTargetException ite) { methodSET.invoke(certInfoObject, getSetField(certInfoObject, "SUBJECT"), x500NameObject); } // info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner)); try { Class<?> certificateIssuerNameClass = Class.forName(getCertificateIssuerNameModuleName()); Constructor<?> certificateIssuerNameConstr = certificateIssuerNameClass .getConstructor(new Class[] { x500NameClass }); Object certificateIssuerNameObject = certificateIssuerNameConstr.newInstance(x500NameObject); methodSET.invoke(certInfoObject, getSetField(certInfoObject, "ISSUER"), certificateIssuerNameObject); } catch (InvocationTargetException ite) { methodSET.invoke(certInfoObject, getSetField(certInfoObject, "ISSUER"), x500NameObject); } // info.set(X509CertInfo.KEY, new CertificateX509Key(pair.getPublic())); Class<?> certificateX509KeyClass = Class.forName(getCertificateX509KeyModuleName()); Constructor<?> certificateX509KeyConstr = certificateX509KeyClass .getConstructor(new Class[] { PublicKey.class }); Object certificateX509KeyObject = certificateX509KeyConstr.newInstance(pair.getPublic()); methodSET.invoke(certInfoObject, getSetField(certInfoObject, "KEY"), certificateX509KeyObject); // info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3)); Class<?> certificateVersionClass = Class.forName(getCertificateVersionModuleName()); Constructor<?> certificateVersionConstr = certificateVersionClass .getConstructor(new Class[] { int.class }); Constructor<?> certificateVersionConstr0 = certificateVersionClass.getConstructor(); Object certInfoObject0 = certificateVersionConstr0.newInstance(); Field v3IntField = certInfoObject0.getClass().getDeclaredField("V3"); v3IntField.setAccessible(true); int fValue = (int) v3IntField.getInt(certInfoObject0); Object certificateVersionObject = certificateVersionConstr.newInstance(fValue); methodSET.invoke(certInfoObject, getSetField(certInfoObject, "VERSION"), certificateVersionObject); // AlgorithmId algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid); Class<?> algorithmIdClass = Class.forName(getAlgorithmIdModuleName()); Field md5WithRSAField = algorithmIdClass.getDeclaredField("md5WithRSAEncryption_oid"); md5WithRSAField.setAccessible(true); Class<?> objectIdentifierClass = Class.forName(getObjectIdentifierModuleName()); Object md5WithRSAValue = md5WithRSAField.get(algorithmIdClass); Constructor<?> algorithmIdConstr = algorithmIdClass .getConstructor(new Class[] { objectIdentifierClass }); Object algorithmIdObject = algorithmIdConstr.newInstance(md5WithRSAValue); // info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo)); Class<?> certificateAlgorithmIdClass = Class.forName(getCertificateAlgorithmIdModuleName()); Constructor<?> certificateAlgorithmIdConstr = certificateAlgorithmIdClass .getConstructor(new Class[] { algorithmIdClass }); Object certificateAlgorithmIdObject = certificateAlgorithmIdConstr.newInstance(algorithmIdObject); methodSET.invoke(certInfoObject, getSetField(certInfoObject, "ALGORITHM_ID"), certificateAlgorithmIdObject); // Sign the cert to identify the algorithm that's used. // X509CertImpl cert = new X509CertImpl(info); Class<?> x509CertImplClass = Class.forName(getX509CertImplModuleName()); Constructor<?> x509CertImplConstr = x509CertImplClass.getConstructor(new Class[] { certInfoClass }); x509CertImplObject = x509CertImplConstr.newInstance(certInfoObject); // cert.sign(privkey, algorithm); Method methoSIGN = x509CertImplObject.getClass().getMethod("sign", PrivateKey.class, String.class); methoSIGN.invoke(x509CertImplObject, privkey, algorithm); // Update the algorith, and resign. // algo = (AlgorithmId)cert.get(X509CertImpl.SIG_ALG); Method methoGET = x509CertImplObject.getClass().getMethod("get", String.class); String sig_alg = getSetField(x509CertImplObject, "SIG_ALG"); String certAlgoIdNameValue = getSetField(certificateAlgorithmIdObject, "NAME"); String certAlgoIdAlgoValue = getSetField(certificateAlgorithmIdObject, "ALGORITHM"); // info.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algo); methodSET.invoke(certInfoObject, certAlgoIdNameValue + "." + certAlgoIdAlgoValue, methoGET.invoke(x509CertImplObject, sig_alg)); // cert = new X509CertImpl(info); x509CertImplObject = x509CertImplConstr.newInstance(certInfoObject); // cert.sign(privkey, algorithm); methoSIGN.invoke(x509CertImplObject, privkey, algorithm); } catch (Exception e) { LOG.failedToGenerateCertificate(e); } return (X509Certificate) x509CertImplObject; }