private X509Certificate createAll(int index) throws GeneralSecurityException, IOException { logger.info("Generating CA key pair"); KeyPair ca = CertUtil.generateKeyPair(CA_CERT_ALGORITHM, CA_CERT_BITS); OpenSSLKey caKey = new BouncyCastleOpenSSLKey(ca.getPrivate()); logger.info("Self-signing CA certificate"); X509Certificate caCert = genCert(ca.getPrivate(), ca.getPublic(), CA_CERT_DN, CA_CERT_DN, null); logger.info("Generating user key pair"); KeyPair user = CertUtil.generateKeyPair(CA_CERT_ALGORITHM, CA_CERT_BITS); OpenSSLKey userKey = new BouncyCastleOpenSSLKey(user.getPrivate()); logger.info("Signing user certificate"); X509Certificate userCert = genCert( ca.getPrivate(), user.getPublic(), USER_CERT_DN, CA_CERT_DN, createExtensions(ca.getPublic(), user.getPublic())); logger.info("Generating proxy certificate"); GlobusCredential proxy = makeProxy(user, userCert); try { logger.info("Writing keys, certificates, and proxy"); writeKey(caKey, makeFile(CA_KEY_NAME_PREFIX, index)); writeCert(caCert, makeFile(CA_CRT_NAME_PREFIX, index)); writeKey(userKey, makeFile(USER_KEY_NAME_PREFIX, index)); writeCert(userCert, makeFile(USER_CRT_NAME_PREFIX, index)); writeProxy(proxy, makeFile(PROXY_NAME_PREFIX, index)); copySigningPolicy(index); } catch (GeneralSecurityException e) { deleteAll(index); throw e; } return cert; }
/** 生成密钥对 */ public static Map<String, String> generateKeyPair() throws Exception { /** RSA算法要求有一个可信任的随机数源 */ SecureRandom sr = new SecureRandom(); /** 为RSA算法创建一个KeyPairGenerator对象 */ KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); /** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */ kpg.initialize(KEYSIZE, sr); /** 生成密匙对 */ KeyPair kp = kpg.generateKeyPair(); /** 得到公钥 */ Key publicKey = kp.getPublic(); byte[] publicKeyBytes = publicKey.getEncoded(); String pub = new String(Base64.encodeBase64(publicKeyBytes), ConfigureEncryptAndDecrypt.CHAR_ENCODING); /** 得到私钥 */ Key privateKey = kp.getPrivate(); byte[] privateKeyBytes = privateKey.getEncoded(); String pri = new String(Base64.encodeBase64(privateKeyBytes), ConfigureEncryptAndDecrypt.CHAR_ENCODING); Map<String, String> map = new HashMap<String, String>(); map.put("publicKey", pub); map.put("privateKey", pri); RSAPublicKey rsp = (RSAPublicKey) kp.getPublic(); BigInteger bint = rsp.getModulus(); byte[] b = bint.toByteArray(); byte[] deBase64Value = Base64.encodeBase64(b); String retValue = new String(deBase64Value); map.put("modulus", retValue); return map; }
public static PKCS10CertificationRequest genPKCS10(KeyPair kp) throws Exception { String sigName = "SHA1withRSA"; X500NameBuilder x500NameBld = new X500NameBuilder(BCStyle.INSTANCE); x500NameBld.addRDN(BCStyle.C, "AU"); x500NameBld.addRDN(BCStyle.ST, "Victoria"); x500NameBld.addRDN(BCStyle.L, "Melbourne"); x500NameBld.addRDN(BCStyle.O, "The Legion of the Bouncy Castle"); X500Name subject = x500NameBld.build(); PKCS10CertificationRequestBuilder requestBuilder = new JcaPKCS10CertificationRequestBuilder(subject, kp.getPublic()); ExtensionsGenerator extGen = new ExtensionsGenerator(); extGen.addExtension( Extension.subjectAlternativeName, false, new GeneralNames( new GeneralName(GeneralName.rfc822Name, "*****@*****.**"))); requestBuilder.addAttribute( PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate()); PKCS10CertificationRequest p10 = requestBuilder.build( new JcaContentSignerBuilder(sigName).setProvider("BC").build(kp.getPrivate())); if (!p10.isSignatureValid( new JcaContentVerifierProviderBuilder().setProvider("BC").build(kp.getPublic()))) { System.out.println(sigName + ": Failed verify check."); } else { System.out.println(sigName + ": PKCS#10 request verified."); } return p10; }
/** * Encrypted the public key with a password and returns the encypted key with the outputstream * * @param password The password used for encryption * @param output The encrypted key * @throws IOException This exception will be thrown when there is a problem with the stream * @throws KOAException This exception will be thrown when there is a problem with the decription */ public void getPublicKeyEncrypt(String password, OutputStream output) throws KOAException { if (keyPair.getPublic() != null) { getKeyEncrypt(password, output, keyPair.getPublic()); } else { throw new KOAException(ErrorConstants.SECURITY_KEYPAIR_ENCRYPT_PUBLIC); } }
public void test(TestHarness harness) { harness.checkPoint("TestOfDHKeyGeneration"); GnuDHKeyPairGenerator kpg = new GnuDHKeyPairGenerator(); HashMap map = new HashMap(); map.put(GnuDHKeyPairGenerator.PRIME_SIZE, new Integer(530)); try { kpg.setup(map); harness.fail("L should be <= 1024 and of the form 512 + 64n"); } catch (IllegalArgumentException x) { harness.check(true, "L should be <= 1024 and of the form 512 + 64n"); } map.put(GnuDHKeyPairGenerator.PRIME_SIZE, new Integer(512)); map.put(GnuDHKeyPairGenerator.EXPONENT_SIZE, new Integer(160)); kpg.setup(map); KeyPair kp = kpg.generate(); BigInteger p1 = ((GnuDHPublicKey) kp.getPublic()).getParams().getP(); BigInteger p2 = ((GnuDHPrivateKey) kp.getPrivate()).getParams().getP(); harness.check(p1.equals(p2), "p1.equals(p2)"); BigInteger q1 = ((GnuDHPublicKey) kp.getPublic()).getQ(); BigInteger q2 = ((GnuDHPrivateKey) kp.getPrivate()).getQ(); harness.check(q1.equals(q2), "q1.equals(q2)"); BigInteger g1 = ((GnuDHPublicKey) kp.getPublic()).getParams().getG(); BigInteger g2 = ((GnuDHPrivateKey) kp.getPrivate()).getParams().getG(); harness.check(g1.equals(g2), "g1.equals(g2)"); harness.check(Prime.isProbablePrime(p1), "p is probable prime"); }
public static X509Certificate makeCertificate( KeyPair subKP, String _subDN, KeyPair issKP, String _issDN, boolean _ca) throws GeneralSecurityException, IOException, OperatorCreationException { PublicKey subPub = subKP.getPublic(); PrivateKey issPriv = issKP.getPrivate(); PublicKey issPub = issKP.getPublic(); X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder( new X500Name(_issDN), allocateSerialNumber(), new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)), new X500Name(_subDN), subPub); JcaContentSignerBuilder contentSignerBuilder = makeContentSignerBuilder(issPub); v3CertGen.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyId(subPub)); v3CertGen.addExtension(Extension.authorityKeyIdentifier, false, createAuthorityKeyId(issPub)); v3CertGen.addExtension(Extension.basicConstraints, false, new BasicConstraints(_ca)); X509Certificate _cert = new JcaX509CertificateConverter() .setProvider("SC") .getCertificate(v3CertGen.build(contentSignerBuilder.build(issPriv))); _cert.checkValidity(new Date()); _cert.verify(issPub); return _cert; }
private static X509Certificate makeCertificate( KeyPair subKP, String _subDN, KeyPair issKP, String _issDN) throws GeneralSecurityException, IOException { PublicKey subPub = subKP.getPublic(); PrivateKey issPriv = issKP.getPrivate(); PublicKey issPub = issKP.getPublic(); X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); v3CertGen.reset(); v3CertGen.setSerialNumber(BigInteger.valueOf(1)); v3CertGen.setIssuerDN(new X509Name(_issDN)); v3CertGen.setNotBefore(new Date(System.currentTimeMillis())); v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100))); v3CertGen.setSubjectDN(new X509Name(_subDN)); v3CertGen.setPublicKey(subPub); v3CertGen.setSignatureAlgorithm("SHA1WithRSA"); X509Certificate _cert = v3CertGen.generate(issPriv, "SunRsaSign"); _cert.checkValidity(new Date()); _cert.verify(issPub); return _cert; }
@PostConstruct public void create() throws Exception { Realm cd = new Realm(REALM_CD_NAME); Realm storedRealm = partitionManager.getPartition(Realm.class, cd.getName()); if (storedRealm == null) { cd.setEnforceSSL(true); KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); cd.setPrivateKey(keyPair.getPrivate().getEncoded()); cd.setPublickKey(keyPair.getPublic().getEncoded()); cd.setNumberFailedLoginAttempts(3); partitionManager.add(cd); IdentityManager cdIdentityManager = partitionManager.createIdentityManager(cd); Role Administrator = new Role("Administrator"); Role Customer = new Role("Customer"); Role Consumer = new Role("Consumer"); Role Vendor = new Role("Vendor"); Role Contacts = new Role("Contacts"); cdIdentityManager.add(Administrator); cdIdentityManager.add(Customer); cdIdentityManager.add(Consumer); cdIdentityManager.add(Vendor); cdIdentityManager.add(Contacts); User user = new User("admin"); cdIdentityManager.add(user); Password password = new Password("admin"); cdIdentityManager.updateCredential(user, password); RelationshipManager relationshipManager = partitionManager.createRelationshipManager(); relationshipManager.add(new Grant(user, Administrator)); Realm cdcustomer = new Realm(REALM_CDCustomer_NAME); Realm customerRealm = partitionManager.getPartition(Realm.class, cdcustomer.getName()); if (customerRealm == null) { cdcustomer.setEnforceSSL(true); KeyPair keyPaircustomer = KeyPairGenerator.getInstance("RSA").generateKeyPair(); cdcustomer.setPrivateKey(keyPaircustomer.getPrivate().getEncoded()); cdcustomer.setPublickKey(keyPaircustomer.getPublic().getEncoded()); cdcustomer.setNumberFailedLoginAttempts(3); partitionManager.add(cdcustomer); IdentityManager cdIdentityManagercst = partitionManager.createIdentityManager(cdcustomer); User customer = new User("customer"); cdIdentityManagercst.add(customer); Password demo = new Password("demo"); cdIdentityManagercst.updateCredential(customer, demo); relationshipManager.add(new Grant(customer, Customer)); User consumer = new User("consumer"); cdIdentityManagercst.add(consumer); cdIdentityManagercst.updateCredential(consumer, demo); relationshipManager.add(new Grant(consumer, Consumer)); } } }
private static X509CertificateHolder makeV3Certificate( KeyPair subKP, String _subDN, KeyPair issKP, String _issDN) throws GeneralSecurityException, IOException, OperatorCreationException, CertException { PublicKey subPub = subKP.getPublic(); PrivateKey issPriv = issKP.getPrivate(); PublicKey issPub = issKP.getPublic(); X509v3CertificateBuilder v1CertGen = new JcaX509v3CertificateBuilder( new X500Name(_issDN), BigInteger.valueOf(System.currentTimeMillis()), new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)), new X500Name(_subDN), subPub); ContentSigner signer = new JcaContentSignerBuilder("SHA1WithRSA").setProvider(BC).build(issPriv); X509CertificateHolder certHolder = v1CertGen.build(signer); ContentVerifierProvider verifier = new JcaContentVerifierProviderBuilder().setProvider(BC).build(issPub); assertTrue(certHolder.isSignatureValid(verifier)); return certHolder; }
public static X509Certificate makeV1Certificate( KeyPair subKP, String _subDN, KeyPair issKP, String _issDN) throws GeneralSecurityException, IOException, OperatorCreationException { PublicKey subPub = subKP.getPublic(); PrivateKey issPriv = issKP.getPrivate(); PublicKey issPub = issKP.getPublic(); X509v1CertificateBuilder v1CertGen = new JcaX509v1CertificateBuilder( new X500Name(_issDN), allocateSerialNumber(), new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)), new X500Name(_subDN), subPub); JcaContentSignerBuilder contentSignerBuilder = makeContentSignerBuilder(issPub); X509Certificate _cert = new JcaX509CertificateConverter() .setProvider("SC") .getCertificate(v1CertGen.build(contentSignerBuilder.build(issPriv))); _cert.checkValidity(new Date()); _cert.verify(issPub); return _cert; }
public static void main(String[] args) throws Exception { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); Misc func = new Misc(); // initialize the key generator (KG) and generate the public/private key pair SecureRandom random = new SecureRandom(); KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "BC"); generator.initialize(1024, random); KeyPair pair = generator.generateKeyPair(); /* initialize KG for digital signature and generate public/private keys for digital signatures It is generally not recommended to use the same public/private key pair for both encryption and digital signatures */ KeyPairGenerator generatorTwo = KeyPairGenerator.getInstance("RSA"); generatorTwo.initialize(1024); KeyPair sigKeyPair = generatorTwo.generateKeyPair(); byte[] sigPubKey = sigKeyPair.getPublic().getEncoded(); byte[] sigPrivKey = sigKeyPair.getPrivate().getEncoded(); byte[] pubKey = pair.getPublic().getEncoded(); byte[] privKey = pair.getPrivate().getEncoded(); // output the generated keys func.outputText(func.byteToHex(sigPubKey), "alice-dspk.txt"); func.outputText(func.byteToHex(sigPrivKey), "alice-dspvk.txt"); func.outputText(func.byteToHex(pubKey), "bob-pkepk.txt"); func.outputText(func.byteToHex(privKey), "bob-pkepvk.txt"); // clear sensitive data func.clear(sigPubKey); func.clear(sigPrivKey); func.clear(pubKey); func.clear(privKey); }
@BeforeClass public void buildCredentials() throws NoSuchAlgorithmException, NoSuchProviderException { KeyPair rsaKeyPair = KeySupport.generateKeyPair(JCAConstants.KEY_ALGO_RSA, 2048, null); rsaCred1 = CredentialSupport.getSimpleCredential(rsaKeyPair.getPublic(), null); rsaCred1.getKeyNames().add(rsaCred1KeyName); KeyPair dsaKeyPair = KeySupport.generateKeyPair(JCAConstants.KEY_ALGO_DSA, 1024, null); dsaCred1 = CredentialSupport.getSimpleCredential(dsaKeyPair.getPublic(), null); dsaCred1.getKeyNames().add(dsaCred1KeyName); }
/** * Compares two keypairs (either one can be null) * * @param keypair1 * @param keypair2 * @return if keypair1 matches keypair2 */ public static boolean compare(KeyPair keypair1, KeyPair keypair2) { if (keypair1 == null) { return keypair2 == null; } else if (keypair2 == null) { return keypair1 == null; } return keypair1.getPrivate().equals(keypair2.getPrivate()) && keypair1.getPublic().equals(keypair2.getPublic()); }
public void testURI() throws Exception { // colinw // RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(512, BigInteger.ONE, RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec( 512, new BigInteger("3"), new URI[] {new URI("test://jsdsi.sf.net")}); KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGO_RSA); kpg.initialize(spec); KeyPair kp = kpg.generateKeyPair(); assertTrue(kp.getPublic() instanceof Principal); assertNotNull(((Principal) kp.getPublic()).getURIs()); }
@Test public void testX509Helpers() throws Exception { KeyPair keyPair = SAMLUtils.generateRandomKeyPair(); String privateKeyString = SAMLUtils.savePrivateKey(keyPair.getPrivate()); String publicKeyString = SAMLUtils.savePublicKey(keyPair.getPublic()); PrivateKey privateKey = SAMLUtils.loadPrivateKey(privateKeyString); PublicKey publicKey = SAMLUtils.loadPublicKey(publicKeyString); assertTrue(privateKey.equals(keyPair.getPrivate())); assertTrue(publicKey.equals(keyPair.getPublic())); }
/** This method generates public and private keys. */ public static void generateKey() throws Exception { KeyPairGenerator gen = KeyPairGenerator.getInstance(RSA); gen.initialize(512, new SecureRandom()); KeyPair keyPair = gen.generateKeyPair(); pubKey = keyPair.getPublic(); priKey = keyPair.getPrivate(); }
/** * Create a self-signed X.509 Certificate. From * http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html. * * @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB" * @param pair the KeyPair * @param days how many days from now the Certificate is valid for * @param algorithm the signing algorithm, eg "SHA1withRSA" * @return the self-signed certificate * @throws CertificateException thrown if a security error or an IO error ocurred. */ public static X509Certificate generateCertificate( String dn, KeyPair pair, int days, String algorithm) throws CertificateException { try { Security.addProvider(new BouncyCastleProvider()); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded()); ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam); X500Name name = new X500Name(dn); Date from = new Date(); Date to = new Date(from.getTime() + days * 86400000L); BigInteger sn = new BigInteger(64, new SecureRandom()); X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(name, sn, from, to, name, subPubKeyInfo); X509CertificateHolder certificateHolder = v1CertGen.build(sigGen); return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder); } catch (CertificateException ce) { throw ce; } catch (Exception e) { throw new CertificateException(e); } }
@Test public void testGenerateRSA() { /* * Init Provider */ ProviderManagement providerManagement = new ProviderManagement(); providerManagement.initProvider("BC"); /* * Generate Key RSA 1024-bit * return KeyPair */ int lengthKeyRSA = 1024; String cryptoProvider = "BC"; KeyManagementRSA keyManagementRSA = new KeyManagementRSA(); KeyPair keyPair = keyManagementRSA.generateRSA(lengthKeyRSA, cryptoProvider); /* * Get Modulus & Exponent Public Key */ RSAPublicKey rsaPubKey = (RSAPublicKey) keyPair.getPublic(); /* * Test Result */ assertEquals(lengthKeyRSA, rsaPubKey.getModulus().bitLength()); }
private static X509Certificate getSelfCertificate( String myname, long validity, String sigAlg, KeyPair keyPair, String provider) throws OperatorCreationException, CertificateException { final long currentTime = new Date().getTime(); final Date firstDate = new Date(currentTime - 24 * 60 * 60 * 1000); final Date lastDate = new Date(currentTime + validity * 1000); // Add all mandatory attributes if (LOG.isDebugEnabled()) { LOG.debug("keystore signing algorithm " + sigAlg); } final PublicKey publicKey = keyPair.getPublic(); if (publicKey == null) { throw new IllegalArgumentException("Public key is null"); } X509v3CertificateBuilder cg = new JcaX509v3CertificateBuilder( new X500Principal(myname), BigInteger.valueOf(firstDate.getTime()), firstDate, lastDate, new X500Principal(myname), publicKey); final JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder(sigAlg); contentSignerBuilder.setProvider(provider); final ContentSigner contentSigner = contentSignerBuilder.build(keyPair.getPrivate()); return new JcaX509CertificateConverter().getCertificate(cg.build(contentSigner)); }
public void testSelfSignedCert() throws Exception { KeyPair keyPair = createKeyPair(1024, "secret"); // Certificate String email = "*****@*****.**"; String domain = "tigase.org"; String ou = "XMPP Service"; String o = "Tigase.org"; String l = "Cambourne"; String st = "Cambridgeshire"; String c = "UK"; // System.out.println("Creating self-signed certificate for issuer: " + domain); X509Certificate cert = createSelfSignedCertificate(email, domain, ou, o, l, st, c, keyPair); cert.checkValidity(); assertTrue("Checked certificate validty for today - valid", true); try { cert.checkValidity(new Date(System.currentTimeMillis() - (1000 * 3600 * 24))); fail("Checked certificate validty for yesterday - valid"); } catch (CertificateNotYetValidException e) { assertTrue("Checked certificate validty for yesterday - not valid", true); } cert.verify(keyPair.getPublic()); assertTrue("Verified certificate with public key - done", true); }
@Test public void testKeygenToFileOutputStream() throws NoSuchAlgorithmException, NoSuchProviderException, IOException { final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); final SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN"); keyGen.initialize(1024, random); KeyPair pair = keyGen.generateKeyPair(); final PrivateKey priv = pair.getPrivate(); final PublicKey pub = pair.getPublic(); // Write the private key to a file FileOutputStream privOS = new FileOutputStream("RSAPrivateKey.key"); Assert.assertNotNull(privOS); privOS.write(priv.getEncoded()); privOS.close(); // Write the private key to a file FileOutputStream publicOS = new FileOutputStream("RSAPublicKey.key"); Assert.assertNotNull(publicOS); publicOS.write(pub.getEncoded()); publicOS.close(); }
public static ECPublicKey PrivateKeytoECPublicKey(byte[] privateKey) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeySpecException { KeyPairGenerator kpg = null; kpg = KeyPairGenerator.getInstance("EC"); ECGenParameterSpec gps = new ECGenParameterSpec("secp256k1"); // NIST P-256 kpg.initialize(gps); KeyPair apair = kpg.generateKeyPair(); ECPublicKey apub = (ECPublicKey) apair.getPublic(); ECParameterSpec aspec = apub.getParams(); byte[] publicKeyb = Address.privateKeyToPublicKey(Utils.toHex(privateKey), false); byte[] publicKeybx = new byte[32]; byte[] publicKeyby = new byte[32]; System.arraycopy(publicKeyb, 1, publicKeybx, 0, 32); System.arraycopy(publicKeyb, 33, publicKeyby, 0, 32); BigInteger x = new BigInteger(1, publicKeybx); BigInteger y = new BigInteger(1, publicKeyby); java.security.spec.ECPoint cpoint = new java.security.spec.ECPoint(x, y); ECPublicKeySpec cpubs = new ECPublicKeySpec(cpoint, aspec); ECPublicKey cpub = null; KeyFactory kfa = null; kfa = KeyFactory.getInstance("EC"); return cpub = (ECPublicKey) kfa.generatePublic(cpubs); }
static X509ResourceCertificate getRootResourceCertificate() { X509ResourceCertificateBuilder builder = new X509ResourceCertificateBuilder(); builder.withSubjectDN(ROOT_CERTIFICATE_NAME); builder.withIssuerDN(ROOT_CERTIFICATE_NAME); builder.withSerial(ROOT_SERIAL_NUMBER); builder.withValidityPeriod(VALIDITY_PERIOD); builder.withPublicKey(ROOT_KEY_PAIR.getPublic()); builder.withCa(true); builder.withKeyUsage(KeyUsage.keyCertSign); builder.withAuthorityKeyIdentifier(true); builder.withSubjectKeyIdentifier(true); builder.withResources(ROOT_RESOURCE_SET); builder.withAuthorityKeyIdentifier(false); builder.withSigningKeyPair(ROOT_KEY_PAIR); X509CertificateInformationAccessDescriptor[] descriptors = { new X509CertificateInformationAccessDescriptor( X509CertificateInformationAccessDescriptor.ID_AD_CA_REPOSITORY, ROOT_SIA_REPO_HTTP_LOCATION), new X509CertificateInformationAccessDescriptor( X509CertificateInformationAccessDescriptor.ID_AD_CA_REPOSITORY, ROOT_SIA_REPO_RSYNC_LOCATION), new X509CertificateInformationAccessDescriptor( X509CertificateInformationAccessDescriptor.ID_AD_RPKI_MANIFEST, ROOT_SIA_MANIFEST_RSYNC_LOCATION), }; builder.withSubjectInformationAccess(descriptors); return builder.build(); }
private static String csr() { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); KeyPair keyPair = keyGen.generateKeyPair(); X500Principal subject = new X500Principal( "CN = edea87b4-034d-48dc-94dd-e7cdcfdde370/10562468, OU = fgdfgretertgdfg, O = VW, L = US"); ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").build(keyPair.getPrivate()); PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(subject, keyPair.getPublic()); PKCS10CertificationRequest csr = builder.build(signer); String type = "CERTIFICATE REQUEST"; PemObject pem = new PemObject(type, csr.getEncoded()); StringWriter str = new StringWriter(); PEMWriter pemWriter = new PEMWriter(str); pemWriter.writeObject(pem); pemWriter.close(); str.close(); Log.d("Test", "" + str); return Base64Util.getStringAsBase64(str.toString()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (OperatorCreationException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ""; }
/** * Generate version 1 self signed {@link java.security.cert.X509Certificate}.. * * @param caKeyPair the CA key pair * @param subject the subject name * @return the x509 certificate * @throws Exception the exception */ public static X509Certificate generateV1SelfSignedCertificate(KeyPair caKeyPair, String subject) throws Exception { try { X500Name subjectDN = new X500Name("CN=" + subject); BigInteger serialNumber = BigInteger.valueOf(System.currentTimeMillis()); Date validityStartDate = new Date(System.currentTimeMillis() - 100000); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.YEAR, 10); Date validityEndDate = new Date(calendar.getTime().getTime()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(caKeyPair.getPublic().getEncoded()); X509v1CertificateBuilder builder = new X509v1CertificateBuilder( subjectDN, serialNumber, validityStartDate, validityEndDate, subjectDN, subPubKeyInfo); X509CertificateHolder holder = builder.build(createSigner(caKeyPair.getPrivate())); return new JcaX509CertificateConverter().getCertificate(holder); } catch (Exception e) { throw new RuntimeException("Error creating X509v1Certificate.", e); } }
public Player(HandleImpl localHandle, HandleImpl dstHandle, final Environment env2) throws Exception { super(); this.destHandle = dstHandle; // this.id = id; env = cloneEnvironment(env2, localHandle.name, localHandle.id.id); this.logger = env.getLogManager().getLogger(Player.class, null); File f = new File(localHandle.name); if (f.exists()) { File f2 = new File(f, "peers"); File[] foo = f2.listFiles(); if (foo != null) { for (int c = 0; c < foo.length; c++) { foo[c].delete(); } } foo = f.listFiles(); if (foo != null) { for (int c = 0; c < foo.length; c++) { foo[c].delete(); } } // System.out.println("Delete "+f+","+f.delete()); } // File f = new File(name+".data"); // if (f.exists()) f.delete(); // f = new File(name+".index"); // if (f.exists()) f.delete(); this.localHandle = localHandle; playerTable.put(localHandle, this); pair = keyPairGen.generateKeyPair(); cert = caTool.sign(localHandle.name, pair.getPublic()); t1 = getTL(); transport = getIdTransport(); idTLTable.put(localHandle, transport); pr = getPeerReview(this, transport, env); app = getApp(); pr.setApp(app); env.getSelectorManager() .invoke( new Runnable() { public void run() { try { pr.init(Player.this.localHandle.name); } catch (IOException ioe) { ioe.printStackTrace(); env2.destroy(); } } }); }
public static PublicKeyRecord createNew(KeyPair kp) throws NoSuchAlgorithmException, InvalidKeySpecException { KeyFactory fact = KeyFactory.getInstance("RSA"); RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(), RSAPublicKeySpec.class); int id = 0; try { Connection conn = DatabaseConnection.getConn(); String sql = "insert into publickey modulus = ?, exponent = ?"; PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, pub.getModulus().toString()); stmt.setString(2, pub.getPublicExponent().toString()); stmt.executeUpdate(); ResultSet generatedKeys = stmt.getGeneratedKeys(); if (generatedKeys.next()) { id = generatedKeys.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } return get(id); }
@Test public void testBadAttributes() throws Exception { DKIMSignature signed = new DKIMSignature(); signed.setAttribute("path", "/hello/world"); signed.setTimestamp(); signed.addHeader("Visa"); signed.addHeader("Visa"); MultivaluedMapImpl<String, String> headers = new MultivaluedMapImpl<String, String>(); headers.add("Visa", "v1"); headers.add("Visa", "v2"); headers.add("Visa", "v3"); signed.sign(headers, null, keys.getPrivate()); String signedHeader = signed.toString(); System.out.println(signedHeader); DKIMSignature verified = new DKIMSignature(signedHeader); HashMap<String, String> requiredAttributes = new HashMap<String, String>(); requiredAttributes.put("path", "/hello/world"); Verification verification = new Verification(); verification.getRequiredAttributes().put("path", "/hello"); MultivaluedMap<String, String> verifiedHeaders = null; try { verifiedHeaders = verification.verify(verified, headers, null, keys.getPublic()); Assert.fail("should fail"); } catch (SignatureException e) { } }
public static boolean isAuthenticated(String username, String connectionHash, SecretKey shared) throws NoSuchAlgorithmException, IOException { String encName = URLEncoder.encode(username, "UTF-8"); MessageDigest sha = MessageDigest.getInstance("SHA-1"); for (byte[] bit : new byte[][] { connectionHash.getBytes("ISO_8859_1"), shared.getEncoded(), keys.getPublic().getEncoded() }) { sha.update(bit); } String encodedHash = URLEncoder.encode(new BigInteger(sha.digest()).toString(16), "UTF-8"); String authURL = "http://session.minecraft.net/game/checkserver.jsp?user="******"&serverId=" + encodedHash; String reply; try (BufferedReader in = new BufferedReader(new InputStreamReader(new URL(authURL).openStream()))) { reply = in.readLine(); } return "YES".equals(reply); }
@Test public void testAttributes() throws Exception { DKIMSignature signed = new DKIMSignature(); signed.setAttribute("path", "/hello/world"); signed.setTimestamp(); signed.addHeader("Visa"); signed.addHeader("Visa"); MultivaluedMapImpl<String, String> headers = new MultivaluedMapImpl<String, String>(); headers.add("Visa", "v1"); headers.add("Visa", "v2"); headers.add("Visa", "v3"); signed.sign(headers, null, keys.getPrivate()); String signedHeader = signed.toString(); System.out.println(signedHeader); DKIMSignature verified = new DKIMSignature(signedHeader); HashMap<String, String> requiredAttributes = new HashMap<String, String>(); requiredAttributes.put("path", "/hello/world"); Verification verification = new Verification(); verification.getRequiredAttributes().put("path", "/hello/world"); MultivaluedMap<String, String> verifiedHeaders = verification.verify(verified, headers, null, keys.getPublic()); Assert.assertEquals(verifiedHeaders.size(), 1); List<String> visas = verifiedHeaders.get("Visa"); Assert.assertNotNull(visas); Assert.assertEquals(visas.size(), 2); System.out.println(visas); Assert.assertEquals(visas.get(0), "v3"); Assert.assertEquals(visas.get(1), "v2"); }