List of usage examples for org.bouncycastle.asn1.x509 RSAPublicKeyStructure RSAPublicKeyStructure
public RSAPublicKeyStructure(BigInteger modulus, BigInteger publicExponent)
From source file:cf.monteux.silvertunnel.netlib.layer.tor.util.Encryption.java
License:Open Source License
/** * converts a RSAPublicKey into PKCS1-encoding (ASN.1). * * @param pubKeyStruct/*from w w w . j a v a2s . co m*/ * @return PKCS1-encoded RSA PUBLIC KEY * @see JCERSAPublicKey */ public static byte[] getPKCS1EncodingFromRSAPublicKey(final RSAPublicKey pubKeyStruct) { try { final RSAPublicKeyStructure myKey = new RSAPublicKeyStructure(pubKeyStruct.getModulus(), pubKeyStruct.getPublicExponent()); final ByteArrayOutputStream bOut = new ByteArrayOutputStream(); final ASN1OutputStream aOut = new ASN1OutputStream(bOut); aOut.writeObject(myKey.toASN1Object()); aOut.close(); return bOut.toByteArray(); } catch (final Exception e) { return null; } }
From source file:org.opcfoundation.ua.utils.CertificateUtils.java
License:Open Source License
/** * //from ww w . j a va 2s . c om * @param commonName - Common Name (CN) for generated certificate * @param organisation - Organisation (O) for generated certificate * @param applicationUri - Alternative name (one of x509 extensiontype) for generated certificate. Must not be null * @param validityTime - the time that the certificate is valid (in days) * @return * @throws IOException * @throws InvalidKeySpecException * @throws NoSuchAlgorithmException * @throws CertificateEncodingException * @throws InvalidKeyException * @throws IllegalStateException * @throws NoSuchProviderException * @throws SignatureException * @throws CertificateParsingException */ public static org.opcfoundation.ua.transport.security.KeyPair createApplicationInstanceCertificate( String commonName, String organisation, String applicationUri, int validityTime) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException, CertificateEncodingException, InvalidKeyException, IllegalStateException, NoSuchProviderException, SignatureException, CertificateParsingException { if (applicationUri == null) throw new NullPointerException("applicationUri must not be null"); //Add provider for generator Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); //Initializes generator SecureRandom srForCert = new SecureRandom(); RSAKeyPairGenerator genForCert = new RSAKeyPairGenerator(); //Used for generating prime Random r = new Random(System.currentTimeMillis()); int random = -1; while (random < 3) { random = r.nextInt(32); } //calculate(generate) possible value for public modulus //used method is "monte carlo -algorithm", so we calculate it as long as it generates value. BigInteger value = null; while (value == null) { value = BigInteger.probablePrime(random, new SecureRandom()); } //Generate (Java) keypair genForCert.init(new RSAKeyGenerationParameters(value, srForCert, KEY_SIZE, 80)); AsymmetricCipherKeyPair keypairForCert = genForCert.generateKeyPair(); //Extract the keys from parameters logger.debug("Generated keypair, extracting components and creating public structure for certificate"); RSAKeyParameters clientPublicKey = (RSAKeyParameters) keypairForCert.getPublic(); RSAPrivateCrtKeyParameters clientPrivateKey = (RSAPrivateCrtKeyParameters) keypairForCert.getPrivate(); // used to get proper encoding for the certificate RSAPublicKeyStructure clientPkStruct = new RSAPublicKeyStructure(clientPublicKey.getModulus(), clientPublicKey.getExponent()); logger.debug("New public key is '" + makeHexString(clientPkStruct.getEncoded()) + ", exponent=" + clientPublicKey.getExponent() + ", modulus=" + clientPublicKey.getModulus()); // JCE format needed for the certificate - because getEncoded() is necessary... PublicKey certPubKey = KeyFactory.getInstance("RSA") .generatePublic(new RSAPublicKeySpec(clientPublicKey.getModulus(), clientPublicKey.getExponent())); // and this one for the KeyStore PrivateKey certPrivKey = KeyFactory.getInstance("RSA").generatePrivate( new RSAPrivateCrtKeySpec(clientPublicKey.getModulus(), clientPublicKey.getExponent(), clientPrivateKey.getExponent(), clientPrivateKey.getP(), clientPrivateKey.getQ(), clientPrivateKey.getDP(), clientPrivateKey.getDQ(), clientPrivateKey.getQInv())); //The data for the certificate.. Calendar expiryTime = Calendar.getInstance(); expiryTime.add(Calendar.DAY_OF_YEAR, validityTime); X509Name certificateX509Name = new X509Name( "CN=" + commonName + ", O=" + organisation + ", C=" + System.getProperty("user.country")); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); BigInteger serial = BigInteger.valueOf(System.currentTimeMillis()); certGen.setSerialNumber(serial); //Issuer and subject must be the same (because this is self signed) certGen.setIssuerDN(certificateX509Name); certGen.setSubjectDN(certificateX509Name); //expiry & start time for this certificate certGen.setNotBefore(new Date(System.currentTimeMillis() - 1000 * 60 * 60)); //take 60 minutes (1000 ms * 60 s * 60) away from system clock (in case there is some lag in system clocks) certGen.setNotAfter(expiryTime.getTime()); certGen.setPublicKey(certPubKey); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); //******* X.509 V3 Extensions ***************** SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(certPubKey.getEncoded())).readObject()); SubjectKeyIdentifier ski = new SubjectKeyIdentifier(apki); /*certGen.addExtension(X509Extensions.SubjectKeyIdentifier, true, new DEROctetString(ski//new SubjectKeyIdentifier Structure(apki/*certPubKey))); */ certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, ski); certGen.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, /*new DEROctetString(new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation | KeyUsage.dataEncipherment | KeyUsage.keyCertSign ))*/new KeyUsage( KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation | KeyUsage.dataEncipherment | KeyUsage.keyCertSign)); BasicConstraints b = new BasicConstraints(false); Vector<KeyPurposeId> extendedKeyUsages = new Vector<KeyPurposeId>(); extendedKeyUsages.add(KeyPurposeId.id_kp_serverAuth); extendedKeyUsages.add(KeyPurposeId.id_kp_clientAuth); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, /*new DEROctetString(new ExtendedKeyUsage(extendedKeyUsages))*/new ExtendedKeyUsage( extendedKeyUsages)); // create the extension value ASN1EncodableVector names = new ASN1EncodableVector(); names.add(new GeneralName(GeneralName.uniformResourceIdentifier, applicationUri)); // GeneralName dnsName = new GeneralName(GeneralName.dNSName, applicationUri); // names.add(dnsName); final GeneralNames subjectAltNames = new GeneralNames(new DERSequence(names)); certGen.addExtension(X509Extensions.SubjectAlternativeName, true, subjectAltNames); // AuthorityKeyIdentifier final GeneralNames certificateIssuer = new GeneralNames(new GeneralName(certificateX509Name)); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki, certificateIssuer, serial); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, aki); //***** generate certificate ***********/ X509Certificate cert = certGen.generate(certPrivKey, "BC"); //Encapsulate Certificate and private key to CertificateKeyPair Cert certificate = new Cert(cert); org.opcfoundation.ua.transport.security.PrivKey UAkey = new org.opcfoundation.ua.transport.security.PrivKey( (RSAPrivateKey) certPrivKey); return new org.opcfoundation.ua.transport.security.KeyPair(certificate, UAkey); }
From source file:org.openconcerto.modules.finance.payment.ebics.crypto.X509CertificateGenerator.java
License:Open Source License
/** * This method implements the public one, but offers an additional parameter which is only used * when creating a new CA, namely the export alias to use. * /*w ww .j a va2 s . c o m*/ * @param commonName @see #createCertificate(String, int, String, String) * @param validityDays @see #createCertificate(String, int, String, String) * @param exportFile @see #createCertificate(String, int, String, String) * @param exportPassword @see #createCertificate(String, int, String, String) * @param exportAlias If this additional parameter is null, a default value will be used as the * "friendly name" in the PKCS12 file. * @return @see #createCertificate(String, int, String, String) * * @see #X509CertificateGenerator(boolean) */ protected boolean createCertificate(String commonName, int validityDays, String exportFile, String exportPassword, String exportAlias) throws IOException, InvalidKeyException, SecurityException, SignatureException, NoSuchAlgorithmException, DataLengthException, CryptoException, KeyStoreException, CertificateException, InvalidKeySpecException { if (commonName == null || exportFile == null || exportPassword == null || validityDays < 1) { throw new IllegalArgumentException("Can not work with null parameter"); } System.out.println("Generating certificate for distinguished common subject name '" + commonName + "', valid for " + validityDays + " days"); SecureRandom sr = new SecureRandom(); // the JCE representation PublicKey pubKey; PrivateKey privKey; // the BCAPI representation RSAPrivateCrtKeyParameters privateKey = null; System.out.println("Creating RSA keypair"); // generate the keypair for the new certificate RSAKeyPairGenerator gen = new RSAKeyPairGenerator(); // TODO: what are these values?? gen.init(new RSAKeyGenerationParameters(BigInteger.valueOf(0x10001), sr, 1024, 80)); AsymmetricCipherKeyPair keypair = gen.generateKeyPair(); System.out .println("Generated keypair, extracting components and creating public structure for certificate"); RSAKeyParameters publicKey = (RSAKeyParameters) keypair.getPublic(); privateKey = (RSAPrivateCrtKeyParameters) keypair.getPrivate(); // used to get proper encoding for the certificate RSAPublicKeyStructure pkStruct = new RSAPublicKeyStructure(publicKey.getModulus(), publicKey.getExponent()); System.out.println("New public key is '" + new String(Hex.encode(pkStruct.getEncoded())) + ", exponent=" + publicKey.getExponent() + ", modulus=" + publicKey.getModulus()); // TODO: these two lines should go away // JCE format needed for the certificate - because getEncoded() is necessary... pubKey = KeyFactory.getInstance("RSA") .generatePublic(new RSAPublicKeySpec(publicKey.getModulus(), publicKey.getExponent())); // and this one for the KeyStore privKey = KeyFactory.getInstance("RSA") .generatePrivate(new RSAPrivateCrtKeySpec(publicKey.getModulus(), publicKey.getExponent(), privateKey.getExponent(), privateKey.getP(), privateKey.getQ(), privateKey.getDP(), privateKey.getDQ(), privateKey.getQInv())); Calendar expiry = Calendar.getInstance(); expiry.add(Calendar.DAY_OF_YEAR, validityDays); X500Name x509Name = new X500Name("CN=" + commonName); V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator(); certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis()))); if (caCert != null) { // Attention: this is a catch! Just using // "new X509Name(caCert.getSubjectDN().getName())" will not work! // I don't know why, because the issuerDN strings look similar with both versions. certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert)); } else { // aha, no CA set, which means that we should create a self-signed certificate (called // from createCA) certGen.setIssuer(x509Name); } certGen.setSubject(x509Name); // TODO GM: DERObjectIdentifier sigOID = PKCSObjectIdentifiers.sha1WithRSAEncryption;// DERObjectIdentifier. // X509Util.getAlgorithmOID(CertificateSignatureAlgorithm); AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull()); certGen.setSignature(sigAlgId); // certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo(sigAlgId, // pkStruct.toASN1Object())); // TODO: why does the coding above not work? - make me work without PublicKey class certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded())).readObject())); certGen.setStartDate(new Time(new Date(System.currentTimeMillis()))); certGen.setEndDate(new Time(expiry.getTime())); // These X509v3 extensions are not strictly necessary, but be nice and provide them... Hashtable extensions = new Hashtable(); Vector extOrdering = new Vector(); addExtensionHelper(X509Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey), extOrdering, extensions); if (caCert != null) { // again: only if we have set CA addExtensionHelper(X509Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert), extOrdering, extensions); } else { // but if we create a new self-signed cert, set its capability to be a CA // this is a critical extension (true)! addExtensionHelper(X509Extension.basicConstraints, true, new BasicConstraints(0), extOrdering, extensions); } certGen.setExtensions(new X509Extensions(extOrdering, extensions)); System.out.println("Certificate structure generated, creating SHA1 digest"); // attention: hard coded to be SHA1+RSA! SHA1Digest digester = new SHA1Digest(); AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine()); TBSCertificateStructure tbsCert = certGen.generateTBSCertificate(); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); dOut.writeObject(tbsCert); // and now sign byte[] signature; byte[] certBlock = bOut.toByteArray(); // first create digest System.out.println("Block to sign is '" + new String(Hex.encode(certBlock)) + "'"); digester.update(certBlock, 0, certBlock.length); byte[] hash = new byte[digester.getDigestSize()]; digester.doFinal(hash, 0); // and sign that if (caCert != null) { rsa.init(true, caPrivateKey); } else { // no CA - self sign System.out.println("No CA has been set, creating self-signed certificate as a new CA"); rsa.init(true, privateKey); } DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash); byte[] digest = dInfo.getEncoded(ASN1Encodable.DER); signature = rsa.processBlock(digest, 0, digest.length); System.out.println("SHA1/RSA signature of digest is '" + new String(Hex.encode(signature)) + "'"); // and finally construct the certificate structure ASN1EncodableVector v = new ASN1EncodableVector(); v.add(tbsCert); v.add(sigAlgId); v.add(new DERBitString(signature)); X509CertificateObject clientCert = new X509CertificateObject( new X509CertificateStructure(new DERSequence(v))); System.out.println("Verifying certificate for correct signature with CA public key"); /* * if (caCert != null) { clientCert.verify(caCert.getPublicKey()); } else { * clientCert.verify(pubKey); } */ // and export as PKCS12 formatted file along with the private key and the CA certificate System.out.println("Exporting certificate in PKCS12 format"); PKCS12BagAttributeCarrier bagCert = clientCert; // if exportAlias is set, use that, otherwise a default name bagCert.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(exportAlias == null ? CertificateExportFriendlyName : exportAlias)); bagCert.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, new SubjectKeyIdentifierStructure(pubKey)); // this does not work as in the example /* * PKCS12BagAttributeCarrier bagKey = (PKCS12BagAttributeCarrier)privKey; * bagKey.setBagAttribute( PKCSObjectIdentifiers.pkcs_9_at_localKeyId, new * SubjectKeyIdentifierStructure(tmpKey)); */ JDKPKCS12KeyStore store; store = new JDKPKCS12KeyStore.BCPKCS12KeyStore(); store.engineLoad(null, null); FileOutputStream fOut = new FileOutputStream(exportFile); X509Certificate[] chain; if (caCert != null) { chain = new X509Certificate[2]; // first the client, then the CA certificate - this is the expected order for a // certificate chain chain[0] = clientCert; chain[1] = caCert; } else { // for a self-signed certificate, there is no chain... chain = new X509Certificate[1]; chain[0] = clientCert; } store.engineSetKeyEntry(exportAlias == null ? KeyExportFriendlyName : exportAlias, privKey, exportPassword.toCharArray(), chain); store.engineStore(fOut, exportPassword.toCharArray()); return true; }
From source file:org.openuat.channel.X509CertificateGenerator.java
License:Open Source License
/** This method implements the public one, but offers an additional parameter which is only used when * creating a new CA, namely the export alias to use. * @param commonName @see #createCertificate(String, int, String, String) * @param validityDays @see #createCertificate(String, int, String, String) * @param exportFile @see #createCertificate(String, int, String, String) * @param exportPassword @see #createCertificate(String, int, String, String) * @param exportAlias If this additional parameter is null, a default value will be used as the "friendly name" in the PKCS12 file. * @return @see #createCertificate(String, int, String, String) * /* w w w .j a va2 s.com*/ * @see #X509CertificateGenerator(boolean) */ protected boolean createCertificate(String commonName, int validityDays, String exportFile, String exportPassword, String exportAlias) throws IOException, InvalidKeyException, SecurityException, SignatureException, NoSuchAlgorithmException, DataLengthException, CryptoException, KeyStoreException, CertificateException, InvalidKeySpecException { if (commonName == null || exportFile == null || exportPassword == null || validityDays < 1) { throw new IllegalArgumentException("Can not work with null parameter"); } logger.info("Generating certificate for distinguished common subject name '" + commonName + "', valid for " + validityDays + " days"); SecureRandom sr = new SecureRandom(); // the JCE representation PublicKey pubKey; PrivateKey privKey; // the BCAPI representation RSAPrivateCrtKeyParameters privateKey = null; logger.debug("Creating RSA keypair"); // generate the keypair for the new certificate if (useBCAPI) { RSAKeyPairGenerator gen = new RSAKeyPairGenerator(); // TODO: what are these values?? gen.init(new RSAKeyGenerationParameters(BigInteger.valueOf(0x10001), sr, 1024, 80)); AsymmetricCipherKeyPair keypair = gen.generateKeyPair(); logger.debug("Generated keypair, extracting components and creating public structure for certificate"); RSAKeyParameters publicKey = (RSAKeyParameters) keypair.getPublic(); privateKey = (RSAPrivateCrtKeyParameters) keypair.getPrivate(); // used to get proper encoding for the certificate RSAPublicKeyStructure pkStruct = new RSAPublicKeyStructure(publicKey.getModulus(), publicKey.getExponent()); logger.debug("New public key is '" + new String(Hex.encodeHex(pkStruct.getEncoded())) + ", exponent=" + publicKey.getExponent() + ", modulus=" + publicKey.getModulus()); // TODO: these two lines should go away // JCE format needed for the certificate - because getEncoded() is necessary... pubKey = KeyFactory.getInstance("RSA") .generatePublic(new RSAPublicKeySpec(publicKey.getModulus(), publicKey.getExponent())); // and this one for the KeyStore privKey = KeyFactory.getInstance("RSA") .generatePrivate(new RSAPrivateCrtKeySpec(publicKey.getModulus(), publicKey.getExponent(), privateKey.getExponent(), privateKey.getP(), privateKey.getQ(), privateKey.getDP(), privateKey.getDQ(), privateKey.getQInv())); } else { // this is the JSSE way of key generation KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024, sr); KeyPair keypair = keyGen.generateKeyPair(); privKey = keypair.getPrivate(); pubKey = keypair.getPublic(); } Calendar expiry = Calendar.getInstance(); expiry.add(Calendar.DAY_OF_YEAR, validityDays); X509Name x509Name = new X509Name("CN=" + commonName); V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator(); certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis()))); if (caCert != null) { // Attention: this is a catch! Just using "new X509Name(caCert.getSubjectDN().getName())" will not work! // I don't know why, because the issuerDN strings look similar with both versions. certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert)); } else { // aha, no CA set, which means that we should create a self-signed certificate (called from createCA) certGen.setIssuer(x509Name); } certGen.setSubject(x509Name); DERObjectIdentifier sigOID = X509Util.getAlgorithmOID(CertificateSignatureAlgorithm); AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull()); certGen.setSignature(sigAlgId); //certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo(sigAlgId, pkStruct.toASN1Object())); // TODO: why does the coding above not work? - make me work without PublicKey class certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded())).readObject())); certGen.setStartDate(new Time(new Date(System.currentTimeMillis()))); certGen.setEndDate(new Time(expiry.getTime())); // These X509v3 extensions are not strictly necessary, but be nice and provide them... Hashtable extensions = new Hashtable(); Vector extOrdering = new Vector(); addExtensionHelper(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey), extOrdering, extensions); if (caCert != null) { // again: only if we have set CA addExtensionHelper(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert), extOrdering, extensions); } else { // but if we create a new self-signed cert, set its capability to be a CA // this is a critical extension (true)! addExtensionHelper(X509Extensions.BasicConstraints, true, new BasicConstraints(0), extOrdering, extensions); } certGen.setExtensions(new X509Extensions(extOrdering, extensions)); logger.debug("Certificate structure generated, creating SHA1 digest"); // attention: hard coded to be SHA1+RSA! SHA1Digest digester = new SHA1Digest(); AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine()); TBSCertificateStructure tbsCert = certGen.generateTBSCertificate(); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); dOut.writeObject(tbsCert); // and now sign byte[] signature; if (useBCAPI) { byte[] certBlock = bOut.toByteArray(); // first create digest logger.debug("Block to sign is '" + new String(Hex.encodeHex(certBlock)) + "'"); digester.update(certBlock, 0, certBlock.length); byte[] hash = new byte[digester.getDigestSize()]; digester.doFinal(hash, 0); // and sign that if (caCert != null) { rsa.init(true, caPrivateKey); } else { // no CA - self sign logger.info("No CA has been set, creating self-signed certificate as a new CA"); rsa.init(true, privateKey); } DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash); byte[] digest = dInfo.getEncoded(ASN1Encodable.DER); signature = rsa.processBlock(digest, 0, digest.length); } else { // or the JCE way Signature sig = Signature.getInstance(sigOID.getId()); if (caCert != null) { PrivateKey caPrivKey = KeyFactory.getInstance("RSA") .generatePrivate(new RSAPrivateCrtKeySpec(caPrivateKey.getModulus(), caPrivateKey.getPublicExponent(), caPrivateKey.getExponent(), caPrivateKey.getP(), caPrivateKey.getQ(), caPrivateKey.getDP(), caPrivateKey.getDQ(), caPrivateKey.getQInv())); sig.initSign(caPrivKey, sr); } else { logger.info("No CA has been set, creating self-signed certificate as a new CA"); sig.initSign(privKey, sr); } sig.update(bOut.toByteArray()); signature = sig.sign(); } logger.debug("SHA1/RSA signature of digest is '" + new String(Hex.encodeHex(signature)) + "'"); // and finally construct the certificate structure ASN1EncodableVector v = new ASN1EncodableVector(); v.add(tbsCert); v.add(sigAlgId); v.add(new DERBitString(signature)); X509CertificateObject clientCert = new X509CertificateObject( new X509CertificateStructure(new DERSequence(v))); logger.debug("Verifying certificate for correct signature with CA public key"); /* if (caCert != null) { clientCert.verify(caCert.getPublicKey()); } else { clientCert.verify(pubKey); }*/ // and export as PKCS12 formatted file along with the private key and the CA certificate logger.debug("Exporting certificate in PKCS12 format"); PKCS12BagAttributeCarrier bagCert = clientCert; // if exportAlias is set, use that, otherwise a default name bagCert.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(exportAlias == null ? CertificateExportFriendlyName : exportAlias)); bagCert.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, new SubjectKeyIdentifierStructure(pubKey)); // this does not work as in the example /*PKCS12BagAttributeCarrier bagKey = (PKCS12BagAttributeCarrier)privKey; bagKey.setBagAttribute( PKCSObjectIdentifiers.pkcs_9_at_localKeyId, new SubjectKeyIdentifierStructure(tmpKey));*/ Object store; if (!useBCAPI) { store = java.security.KeyStore.getInstance("PKCS12"); ((java.security.KeyStore) store).load(null, null); } else { store = new JDKPKCS12KeyStore(null, sigOID, sigOID); ((JDKPKCS12KeyStore) store).engineLoad(null, null); } FileOutputStream fOut = new FileOutputStream(exportFile); X509Certificate[] chain; if (caCert != null) { chain = new X509Certificate[2]; // first the client, then the CA certificate - this is the expected order for a certificate chain chain[0] = clientCert; chain[1] = caCert; } else { // for a self-signed certificate, there is no chain... chain = new X509Certificate[1]; chain[0] = clientCert; } if (!useBCAPI) { ((java.security.KeyStore) store).setKeyEntry(exportAlias == null ? KeyExportFriendlyName : exportAlias, privKey, exportPassword.toCharArray(), chain); ((java.security.KeyStore) store).store(fOut, exportPassword.toCharArray()); } else { ((JDKPKCS12KeyStore) store).engineSetKeyEntry(exportAlias == null ? KeyExportFriendlyName : exportAlias, privKey, exportPassword.toCharArray(), chain); ((JDKPKCS12KeyStore) store).engineStore(fOut, exportPassword.toCharArray()); } return true; }
From source file:org.silvertunnel.netlib.layer.tor.util.Encryption.java
License:Open Source License
/** * converts a RSAPublicKey into PKCS1-encoding (ASN.1) * /*from w w w. j av a2 s. c om*/ * @param rsaPublicKey * @see JCERSAPublicKey * @return PKCS1-encoded RSA PUBLIC KEY */ public static byte[] getPKCS1EncodingFromRSAPublicKey(RSAPublicKey pubKeyStruct) { try { RSAPublicKeyStructure myKey = new RSAPublicKeyStructure(pubKeyStruct.getModulus(), pubKeyStruct.getPublicExponent()); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream aOut = new ASN1OutputStream(bOut); aOut.writeObject(myKey.toASN1Object()); return bOut.toByteArray(); } catch (Exception e) { return null; } }
From source file:TorJava.Common.Encryption.java
License:Open Source License
/** * makes RSA public key from string//from w w w . j a v a 2 s .co m * * @param s * string that contais the key * @return * @see JCERSAPublicKey */ public static RSAPublicKeyStructure extractRSAKey(String s) { PEMReader reader = new PEMReader(new StringReader(s)); JCERSAPublicKey JCEKey; RSAPublicKeyStructure theKey; try { Object o = reader.readObject(); if (!(o instanceof JCERSAPublicKey)) throw new IOException("Common.extractRSAKey: no public key found for signing key in string '" + s + "' type " + o.getClass().getName()); JCEKey = (JCERSAPublicKey) o; theKey = new RSAPublicKeyStructure(JCEKey.getModulus(), JCEKey.getPublicExponent()); } catch (IOException e) { Logger.logDirectory(Logger.WARNING, "Common.extractRSAKey: Caught exception:" + e.getMessage()); theKey = null; } return theKey; }
From source file:TorJava.Common.Encryption.java
License:Open Source License
/** * copy from one format to another// ww w. j av a 2 s . c o m */ public static RSAPublicKeyStructure getRSAPublicKeyStructureFromJCERSAPublicKey(JCERSAPublicKey jpub) { return new RSAPublicKeyStructure(jpub.getModulus(), jpub.getPublicExponent()); }
From source file:TorJava.Server.java
License:Open Source License
/** * extracts all relevant information from the router discriptor and saves it * in the member variables./*ww w.j a va 2s.c o m*/ * * @param rd * string encoded router descriptor */ private void parseRouterDescriptor(String rd) throws TorException { this.routerDescriptor = rd; // Router item: nickname, hostname, onion-router-port, socks-port, dir-port Pattern p = Pattern.compile("^router (\\w+) (\\S+) (\\d+) (\\d+) (\\d+)", Pattern.DOTALL + Pattern.MULTILINE + Pattern.CASE_INSENSITIVE + Pattern.UNIX_LINES); Matcher m = p.matcher(rd); m.find(); this.nickname = m.group(1); this.hostname = m.group(2); this.orPort = Integer.parseInt(m.group(3)); this.socksPort = Integer.parseInt(m.group(4)); this.dirPort = Integer.parseInt(m.group(5)); // secondary information platform = Parsing.parseStringByRE(rd, "^platform (.*?)$", "unknown"); published = dateFormat.parse(Parsing.parseStringByRE(rd, "^published (.*?)$", ""), (new ParsePosition(0))); uptime = Integer.parseInt(Parsing.parseStringByRE(rd, "^uptime (\\d+)", "0")); fingerprint = Encoding.parseHex(Parsing.parseStringByRE(rd, "^opt fingerprint (.*?)$", "")); contact = Parsing.parseStringByRE(rd, "^contact (.*?)$", ""); // make that IF description is from a trusted server, that fingerprint is correct if (tor.config.trustedServers.containsKey(nickname)) { String fingerprintFromConfig = (String) (tor.config.trustedServers.get(nickname)).get("fingerprint"); if (!Encoding.toHexString(fingerprint).equalsIgnoreCase(fingerprintFromConfig)) throw new TorException("Server " + nickname + " is trusted, but fingerprint check failed"); } // bandwith p = Pattern.compile("^bandwidth (\\d+) (\\d+) (\\d+)?", Pattern.DOTALL + Pattern.MULTILINE + Pattern.CASE_INSENSITIVE + Pattern.UNIX_LINES); m = p.matcher(rd); if (m.find()) { bandwidthAvg = Integer.parseInt(m.group(1)); bandwidthBurst = Integer.parseInt(m.group(2)); bandwidthObserved = Integer.parseInt(m.group(3)); } ; // onion key String stringOnionKey = Parsing.parseStringByRE(rd, "^onion-key\n(.*?END RSA PUBLIC KEY......)", ""); onionKey = Encryption.extractRSAKey(stringOnionKey); // signing key String stringSigningKey = Parsing.parseStringByRE(rd, "^signing-key\n(.*?END RSA PUBLIC KEY-----\n)", ""); signingKey = Encryption.extractRSAKey(stringSigningKey); SHA1Digest sha1 = new SHA1Digest(); // verify signing-key against fingerprint try { RSAPublicKeyStructure signingKey_asn = new RSAPublicKeyStructure(signingKey.getModulus(), signingKey.getPublicExponent()); byte[] pkcs = Encryption.getPKCS1EncodingFromRSAPublicKey(signingKey_asn); byte[] key_hash = new byte[20]; sha1.update(pkcs, 0, pkcs.length); sha1.doFinal(key_hash, 0); if (!Encoding.arraysEqual(key_hash, fingerprint)) throw new TorException("Server " + nickname + " doesn't verify signature vs fingerprint"); } catch (Exception e) { throw new TorException("Server " + nickname + " doesn't verify signature vs fingerprint"); } // parse family String stringFamily = Parsing.parseStringByRE(rd, "^family (.*?)$", ""); if (stringFamily == "") stringFamily = Parsing.parseStringByRE(rd, "^opt family (.*?)$", ""); Pattern p_family = Pattern.compile("(\\S+)"); Matcher m_family = p_family.matcher(stringFamily); while (m_family.find()) { String host = m_family.group(1); family.add(host); } // check the validity of the signature router_signature = Encoding.parseBase64(Parsing.parseStringByRE(rd, "^router-signature\n-----BEGIN SIGNATURE-----(.*?)-----END SIGNATURE-----", "")); byte[] sha1_input = (Parsing.parseStringByRE(rd, "^(router .*?router-signature\n)", "")).getBytes(); if (!Encryption.verifySignature(router_signature, signingKey, sha1_input)) { Logger.logCrypto(Logger.ERROR, "Server -> router-signature check failed for " + nickname); throw new TorException("Server " + nickname + ": description signature verification failed"); } // exit policy exitpolicy = parseExitPolicy(rd); // usually in directory the hostname is already set to the IP // so, following resolve just converts it to the InetAddress try { address = InetAddress.getByName(hostname); } catch (UnknownHostException e) { throw new TorException("Server.ParseRouterDescriptor: Unresolvable hostname " + hostname); } }
From source file:TorJava.ServiceDescriptor.java
License:Open Source License
/** * constructor for creating a service descriptor *//* w w w. jav a 2s.co m*/ ServiceDescriptor(int version, RSAKeyParameters publicKey, RSAKeyParameters privateKey, HashSet<IntroductionPoint> given_introPoints) throws TorException { if (version != 0) throw new TorException("not implemented"); // FIXME: service // descriptors of // version != 0 are not // supported, yet this.version = version; this.timestamp = (int) (System.currentTimeMillis() / 1000L); this.publicKey = new RSAPublicKeyStructure(publicKey.getModulus(), publicKey.getExponent()); this.privateKey = privateKey; updateURL(); // store intro-points introPoints = given_introPoints; numberOfIntroPoints = given_introPoints.size(); byte[] temp = new byte[introPoints.size() * 100]; int temp_fill = 0; Iterator<IntroductionPoint> i = introPoints.iterator(); while (i.hasNext()) { byte[] s = i.next().getIdentityDigest().getBytes(); System.arraycopy(s, 0, temp, temp_fill, s.length); temp_fill += s.length + 1; } this.bytesIntroPoints = new byte[temp_fill]; System.arraycopy(temp, 0, bytesIntroPoints, 0, temp_fill); }