List of usage examples for org.bouncycastle.crypto.digests SHA1Digest update
public void update(byte[] in, int inOff, int len)
From source file:org.fnppl.opensdx.security.SecurityHelper.java
License:Open Source License
public static byte[][] getMD5SHA1SHA256(byte[] data) { byte[] ret = new byte[16 + 20 + 32]; //160 bit = 20 byte + md5 128bit = 16 + sha256 256bit = 32 byte byte[] md5ret = new byte[16]; byte[] sha1ret = new byte[20]; byte[] sha256ret = new byte[32]; org.bouncycastle.crypto.digests.MD5Digest md5 = new org.bouncycastle.crypto.digests.MD5Digest(); md5.update(data, 0, data.length);// ww w .jav a 2 s .c o m md5.doFinal(ret, 0); org.bouncycastle.crypto.digests.SHA1Digest sha1 = new org.bouncycastle.crypto.digests.SHA1Digest(); sha1.update(data, 0, data.length); sha1.doFinal(ret, 16); org.bouncycastle.crypto.digests.SHA256Digest sha256 = new org.bouncycastle.crypto.digests.SHA256Digest(); sha256.update(data, 0, data.length); sha256.doFinal(ret, 16 + 20); System.arraycopy(ret, 0, md5ret, 0, md5ret.length); System.arraycopy(ret, 16, sha1ret, 0, sha1ret.length); System.arraycopy(ret, 16 + 20, sha256ret, 0, sha256ret.length); return new byte[][] { ret, md5ret, sha1ret, sha256ret }; }
From source file:org.fnppl.opensdx.security.SecurityHelper.java
License:Open Source License
public static byte[][] getMD5SHA1(InputStream fin) throws Exception { byte[] md5ret = new byte[16]; byte[] sha1ret = new byte[20]; org.bouncycastle.crypto.digests.MD5Digest md5 = new org.bouncycastle.crypto.digests.MD5Digest(); org.bouncycastle.crypto.digests.SHA1Digest sha1 = new org.bouncycastle.crypto.digests.SHA1Digest(); int read = -1; byte[] buff = new byte[4096]; while ((read = fin.read(buff)) != -1) { md5.update(buff, 0, read);/*from w w w. ja v a 2 s . c o m*/ sha1.update(buff, 0, read); } sha1.doFinal(sha1ret, 0); md5.doFinal(md5ret, 0); return new byte[][] { md5ret, sha1ret, }; }
From source file:org.fnppl.opensdx.security.SecurityHelper.java
License:Open Source License
public static byte[][] getMD5SHA1SHA256(InputStream fin) throws Exception { byte[] ret = new byte[16 + 20 + 32]; //160 bit = 20 byte + md5 128bit = 16 + sha256 256bit = 32 byte byte[] md5ret = new byte[16]; byte[] sha1ret = new byte[20]; byte[] sha256ret = new byte[32]; org.bouncycastle.crypto.digests.MD5Digest md5 = new org.bouncycastle.crypto.digests.MD5Digest(); org.bouncycastle.crypto.digests.SHA1Digest sha1 = new org.bouncycastle.crypto.digests.SHA1Digest(); org.bouncycastle.crypto.digests.SHA256Digest sha256 = new org.bouncycastle.crypto.digests.SHA256Digest(); int read = -1; byte[] buff = new byte[4096]; while ((read = fin.read(buff)) != -1) { md5.update(buff, 0, read);// www . j ava2s .c om sha1.update(buff, 0, read); sha256.update(buff, 0, read); } sha1.doFinal(ret, 16); md5.doFinal(ret, 0); sha256.doFinal(ret, 16 + 20); System.arraycopy(ret, 0, md5ret, 0, md5ret.length); System.arraycopy(ret, 16, sha1ret, 0, sha1ret.length); System.arraycopy(ret, 16 + 20, sha256ret, 0, sha256ret.length); return new byte[][] { ret, md5ret, sha1ret, sha256ret }; }
From source file:org.fnppl.opensdx.security.SecurityHelper.java
License:Open Source License
public static byte[] getSHA1(byte[] data) { byte[] ret = new byte[20]; //160 bit = 20 byte org.bouncycastle.crypto.digests.SHA1Digest sha1 = new org.bouncycastle.crypto.digests.SHA1Digest(); sha1.update(data, 0, data.length); sha1.doFinal(ret, 0);/* w w w.j a v a 2s. c om*/ return ret; }
From source file:org.fnppl.opensdx.security.SecurityHelper.java
License:Open Source License
public static byte[] getSHA1(InputStream in) throws Exception { byte[] ret = new byte[20];//160 bit = 20 byte org.bouncycastle.crypto.digests.SHA1Digest sha1 = new org.bouncycastle.crypto.digests.SHA1Digest(); int read = -1; byte[] buff = new byte[1024]; while ((read = in.read(buff)) != -1) { sha1.update(buff, 0, read); }/*w w w .j av a2s .c o m*/ sha1.doFinal(ret, 0); return ret; }
From source file:org.fnppl.opensdx.security.SecurityHelper.java
License:Open Source License
private static void updateSha1(SHA1Digest sha1, String s) { try {// ww w .j av a2s .co m byte[] b = s.getBytes("UTF-8"); sha1.update(b, 0, b.length); //System.out.println("update sha1: "+s); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:org.jcryptool.visual.hashing.views.HashingView.java
License:Open Source License
private String computeHash(String hashName, String inputText, Text hashText) { hash = hash.getName(hashName);//w ww. j a v a 2 s. co m byte[] digest = null; switch (hash) { case MD2: MD2Digest md2 = new MD2Digest(); md2.update(inputText.getBytes(), 0, inputText.getBytes().length); digest = new byte[md2.getDigestSize()]; md2.doFinal(digest, 0); break; case MD4: MD4Digest md4 = new MD4Digest(); md4.update(inputText.getBytes(), 0, inputText.getBytes().length); digest = new byte[md4.getDigestSize()]; md4.doFinal(digest, 0); break; case MD5: MD5Digest md5 = new MD5Digest(); md5.update(inputText.getBytes(), 0, inputText.getBytes().length); digest = new byte[md5.getDigestSize()]; md5.doFinal(digest, 0); break; case SHA1: SHA1Digest sha1 = new SHA1Digest(); sha1.update(inputText.getBytes(), 0, inputText.getBytes().length); digest = new byte[sha1.getDigestSize()]; sha1.doFinal(digest, 0); break; case SHA256: SHA256Digest sha256 = new SHA256Digest(); sha256.update(inputText.getBytes(), 0, inputText.getBytes().length); digest = new byte[sha256.getDigestSize()]; sha256.doFinal(digest, 0); break; case SHA512: SHA512Digest sha512 = new SHA512Digest(); sha512.update(inputText.getBytes(), 0, inputText.getBytes().length); digest = new byte[sha512.getDigestSize()]; sha512.doFinal(digest, 0); break; case SHA3_224: SHA3.Digest224 sha3_224 = new SHA3.Digest224(); sha3_224.update(inputText.getBytes(), 0, inputText.getBytes().length); digest = new byte[sha3_224.getDigestLength()]; digest = sha3_224.digest(); break; case SHA3_256: SHA3.Digest256 sha3_256 = new SHA3.Digest256(); sha3_256.update(inputText.getBytes(), 0, inputText.getBytes().length); digest = new byte[sha3_256.getDigestLength()]; digest = sha3_256.digest(); break; case SHA3_384: SHA3.Digest384 sha3_384 = new SHA3.Digest384(); sha3_384.update(inputText.getBytes(), 0, inputText.getBytes().length); digest = new byte[sha3_384.getDigestLength()]; digest = sha3_384.digest(); break; case SHA3_512: SHA3.Digest512 sha3_512 = new SHA3.Digest512(); sha3_512.update(inputText.getBytes(), 0, inputText.getBytes().length); digest = new byte[sha3_512.getDigestLength()]; digest = sha3_512.digest(); break; case SKEIN_256: Skein.Digest_256_256 skein_256 = new Skein.Digest_256_256(); skein_256.update(inputText.getBytes(), 0, inputText.getBytes().length); digest = new byte[skein_256.getDigestLength()]; digest = skein_256.digest(); break; case SKEIN_512: Skein.Digest_512_512 skein_512 = new Skein.Digest_512_512(); skein_512.update(inputText.getBytes(), 0, inputText.getBytes().length); digest = new byte[skein_512.getDigestLength()]; digest = skein_512.digest(); break; case SKEIN_1024: Skein.Digest_1024_1024 skein_1024 = new Skein.Digest_1024_1024(); skein_1024.update(inputText.getBytes(), 0, inputText.getBytes().length); digest = new byte[skein_1024.getDigestLength()]; digest = skein_1024.digest(); break; case RIPEMD160: RIPEMD160Digest ripemd160 = new RIPEMD160Digest(); ripemd160.update(inputText.getBytes(), 0, inputText.getBytes().length); digest = new byte[ripemd160.getDigestSize()]; ripemd160.doFinal(digest, 0); break; case SM3: SM3Digest sm3 = new SM3Digest(); sm3.update(inputText.getBytes(), 0, inputText.getBytes().length); digest = new byte[sm3.getDigestSize()]; sm3.doFinal(digest, 0); break; case TIGER: TigerDigest tiger = new TigerDigest(); tiger.update(inputText.getBytes(), 0, inputText.getBytes().length); digest = new byte[tiger.getDigestSize()]; tiger.doFinal(digest, 0); break; case GOST3411: GOST3411Digest gost3411 = new GOST3411Digest(); gost3411.update(inputText.getBytes(), 0, inputText.getBytes().length); digest = new byte[gost3411.getDigestSize()]; gost3411.doFinal(digest, 0); break; case WHIRLPOOL: WhirlpoolDigest whirlpool = new WhirlpoolDigest(); whirlpool.update(inputText.getBytes(), 0, inputText.getBytes().length); digest = new byte[whirlpool.getDigestSize()]; whirlpool.doFinal(digest, 0); break; default: break; } String hashHexValue = new String(Hex.encode(digest)); if (btnHexadezimal.getSelection()) { String hashValueOutput = hashHexValue.toUpperCase().replaceAll(".{2}", "$0 "); //$NON-NLS-1$ //$NON-NLS-2$ hashText.setText(hashValueOutput); } else if (btnDezimal.getSelection()) { String hashValue = hexToDecimal(hashHexValue); hashValue = hashValue.replaceAll(".{3}", "$0 "); //$NON-NLS-1$ //$NON-NLS-2$ hashText.setText(hashValue); } else if (btnBinary.getSelection()) { String hashValue = hexToBinary(hashHexValue); hashValue = hashValue.replaceAll(".{8}", "$0#"); //$NON-NLS-1$ //$NON-NLS-2$ hashText.setText(hashValue); } return hashHexValue; }
From source file:org.nfc.eclipse.ndef.signature.SignatureVerifier.java
License:Open Source License
public Boolean verify(CertificateFormat certificateFormat, byte[] certificateBytes, SignatureType signatureType, byte[] signatureBytes, byte[] coveredBytes) throws CertificateException, NoSuchProviderException { if (Security.getProvider("BC") == null) { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); }/*from www . j a va 2 s . c om*/ Certificate certificate = null; if (certificateFormat == CertificateFormat.X_509) { java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory.getInstance("X.509", "BC"); certificate = cf.generateCertificate(new ByteArrayInputStream(certificateBytes)); } if (signatureType == SignatureType.RSASSA_PKCS1_v1_5_WITH_SHA_1) { BCRSAPublicKey key = (BCRSAPublicKey) certificate.getPublicKey(); RSAKeyParameters pubParameters = new RSAKeyParameters(false, key.getModulus(), key.getPublicExponent()); SHA1Digest digest = new SHA1Digest(); RSADigestSigner rsaDigestSigner = new RSADigestSigner(digest); rsaDigestSigner.init(false, pubParameters); rsaDigestSigner.update(coveredBytes, 0, coveredBytes.length); return rsaDigestSigner.verifySignature(signatureBytes); } else if (signatureType == SignatureType.RSASSA_PSS_SHA_1) { BCRSAPublicKey key = (BCRSAPublicKey) certificate.getPublicKey(); RSAKeyParameters pubParameters = new RSAKeyParameters(false, key.getModulus(), key.getPublicExponent()); AsymmetricBlockCipher rsaEngine = new RSABlindedEngine(); rsaEngine.init(false, pubParameters); SHA1Digest digest = new SHA1Digest(); PSSSigner signer = new PSSSigner(rsaEngine, digest, digest.getDigestSize()); signer.init(true, pubParameters); signer.update(coveredBytes, 0, coveredBytes.length); return signer.verifySignature(signatureBytes); } else if (signatureType == SignatureType.ECDSA) { // http://en.wikipedia.org/wiki/Elliptic_Curve_DSA // http://stackoverflow.com/questions/11339788/tutorial-of-ecdsa-algorithm-to-sign-a-string // http://www.bouncycastle.org/wiki/display/JA1/Elliptic+Curve+Key+Pair+Generation+and+Key+Factories // http://java2s.com/Open-Source/Java/Security/Bouncy-Castle/org/bouncycastle/crypto/test/ECTest.java.htm /* BCRSAPublicKey key = (BCRSAPublicKey) certificate.getPublicKey(); RSAKeyParameters pubParameters = new RSAKeyParameters(false, key.getModulus(), key.getPublicExponent()); org.bouncycastle.crypto.signers.ECDSASigner signer = new org.bouncycastle.crypto.signers.ECDSASigner(); signer.init(false, pubParameters); SHA1Digest digest = new SHA1Digest(); digest.update(coveredBytes, 0, coveredBytes.length); return signer.verifySignature(signatureBytes); */ } else if (signatureType == SignatureType.DSA) { ASN1InputStream aIn = new ASN1InputStream(signatureBytes); ASN1Primitive o; try { o = aIn.readObject(); ASN1Sequence asn1Sequence = (ASN1Sequence) o; BigInteger r = DERInteger.getInstance(asn1Sequence.getObjectAt(0)).getValue(); BigInteger s = DERInteger.getInstance(asn1Sequence.getObjectAt(1)).getValue(); BCDSAPublicKey key = (BCDSAPublicKey) certificate.getPublicKey(); // DSA Domain parameters DSAParams params = key.getParams(); if (params == null) { return Boolean.FALSE; } DSAParameters parameters = new DSAParameters(params.getP(), params.getQ(), params.getG()); DSASigner signer = new DSASigner(); signer.init(false, new DSAPublicKeyParameters(key.getY(), parameters)); SHA1Digest digest = new SHA1Digest(); digest.update(coveredBytes, 0, coveredBytes.length); byte[] message = new byte[digest.getDigestSize()]; digest.doFinal(message, 0); return signer.verifySignature(message, r, s); } catch (IOException e) { return Boolean.FALSE; } } return null; }
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. * //ww w .j av a 2 s .c om * @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 .jav a2s . c o m * @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; }