List of usage examples for org.bouncycastle.crypto.digests SHA1Digest SHA1Digest
public SHA1Digest()
From source file:ECIESTest.java
public TestResult perform() { SecureRandom random = new SecureRandom(); ECCurve.Fp curve = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECDomainParameters params = new ECDomainParameters(curve, curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n ECKeyPairGenerator pGen = new ECKeyPairGenerator(); ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(params, random); pGen.init(genParam);/* w ww . j a va 2 s . com*/ AsymmetricCipherKeyPair p1 = pGen.generateKeyPair(); AsymmetricCipherKeyPair p2 = pGen.generateKeyPair(); // // stream test // IESEngine i1 = new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest())); IESEngine i2 = new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest())); byte[] d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; byte[] e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 }; IESParameters p = new IESParameters(d, e, 64); i1.init(true, p1.getPrivate(), p2.getPublic(), p); i2.init(false, p2.getPrivate(), p1.getPublic(), p); byte[] message = Hex.decode("1234567890abcdef"); try { byte[] out1 = i1.processBlock(message, 0, message.length); byte[] out2 = i2.processBlock(out1, 0, out1.length); if (!sameAs(out2, message)) { return new SimpleTestResult(false, this.getName() + ": stream cipher test failed"); } } catch (Exception ex) { return new SimpleTestResult(false, this.getName() + ": stream cipher test exception " + ex.toString()); } // // twofish with IV0 test // BufferedBlockCipher c1 = new PaddedBufferedBlockCipher(new CBCBlockCipher(new TwofishEngine())); BufferedBlockCipher c2 = new PaddedBufferedBlockCipher(new CBCBlockCipher(new TwofishEngine())); i1 = new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), c1); i2 = new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), c2); d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 }; p = new IESWithCipherParameters(d, e, 64, 128); i1.init(true, p1.getPrivate(), p2.getPublic(), p); i2.init(false, p2.getPrivate(), p1.getPublic(), p); message = Hex.decode("1234567890abcdef"); try { byte[] out1 = i1.processBlock(message, 0, message.length); byte[] out2 = i2.processBlock(out1, 0, out1.length); if (!sameAs(out2, message)) { return new SimpleTestResult(false, this.getName() + ": twofish cipher test failed"); } } catch (Exception ex) { return new SimpleTestResult(false, this.getName() + ": twofish cipher test exception " + ex.toString()); } return new SimpleTestResult(true, this.getName() + ": Okay"); }
From source file:GenTestDKs.java
License:Open Source License
public static void main(String[] args) { PKCS12ParametersGenerator pgen = new PKCS12ParametersGenerator(new SHA1Digest()); // SB.4: key lengths for defined OIDs // (168 for triple DES will first exercise chaining.) final int[] keyLens = { 40, 128, 168, 368 }; // SB.4 iteration count is recommended to be 1024 or more final int[] iterCounts = { 1, 2, 4, 8, 128, 1024, 1536, 2048 }; // SB.4 salt should be same length as hash function output // (=160 bits for SHA1.) byte[][] salts = new byte[3][]; salts[0] = new byte[] { 'S', 'A', 'L', 'T' }; System.out.println("4 byte salt"); printByteArray(salts[0]);//from w w w . j a v a 2 s . c om // calls to nextBytes() are only executed once /* SecureRandom sr; try { sr = SecureRandom.getInstance("SHA1PRNG", "SUN"); } catch (Exception e) { System.err.println("UNABLE TO GET RANDOM SOURCE"); return; } */ // salts[1] = new byte[160 / 8]; // sr.nextBytes(salts[1]); salts[1] = new byte[] { (byte) 0x1d, (byte) 0x56, (byte) 0x50, (byte) 0x78, (byte) 0xc3, (byte) 0x50, (byte) 0x6f, (byte) 0x89, (byte) 0xbd, (byte) 0xa7, (byte) 0x3b, (byte) 0xb6, (byte) 0xe3, (byte) 0xe5, (byte) 0xb8, (byte) 0xa3, (byte) 0x68, (byte) 0x3d, (byte) 0xd3, (byte) 0x62 }; System.out.println("20 byte salt (same size as SHA1 output)"); printByteArray(salts[1]); // salts[2] = new byte[200 / 8]; // sr.nextBytes(salts[2]); salts[2] = new byte[] { (byte) 0xe2, (byte) 0x2c, (byte) 0x7b, (byte) 0x03, (byte) 0x16, (byte) 0x3a, (byte) 0xe5, (byte) 0x47, (byte) 0xf8, (byte) 0x23, (byte) 0x9d, (byte) 0xa4, (byte) 0x0d, (byte) 0x6f, (byte) 0x46, (byte) 0xd7, (byte) 0x9e, (byte) 0xa3, (byte) 0xc6, (byte) 0xff, (byte) 0xb3, (byte) 0xf0, (byte) 0x4e, (byte) 0xbe, (byte) 0x61 }; System.out.println("25 byte salt"); printByteArray(salts[2]); final String passwds[] = { "0000", "0001", "PSWD", "password", "abcdefghijklmnopqrstuvwxyz" }; for (int keyLenIdx = 0; keyLenIdx < keyLens.length; ++keyLenIdx) { for (int iterIdx = 0; iterIdx < iterCounts.length; ++iterIdx) { for (int saltIdx = 0; saltIdx < salts.length; ++saltIdx) { for (int pwdIdx = 0; pwdIdx < passwds.length; ++pwdIdx) { testKey(pgen, keyLens[keyLenIdx], iterCounts[iterIdx], passwds[pwdIdx], salts[saltIdx]); } // for (int pwdIdx = 0; pwdIdx < passwds.length; ++pwdIdx) } // for (int saltIdx = 0; saltIdx < salts.length; ++saltIdx) } // for (int iterIdx = 0; iterIdx < iterCounts.length; ++iterIdx) } // for (int keyLenIdx = 0; keyLenIdx < keyLens.length; ++keyLenIdx) }
From source file:VerifyDescriptors.java
License:Open Source License
private static void verifyConsensuses() throws Exception { File certsDirectory = new File("in/certs"); File consensusDirectory = new File("in/consensuses"); if (!certsDirectory.exists() || !consensusDirectory.exists()) { return;/*from w ww .j av a 2 s . co m*/ } Map<String, String> signingKeys = new HashMap<String, String>(); DescriptorReader certsReader = DescriptorSourceFactory.createDescriptorReader(); certsReader.addDirectory(certsDirectory); Iterator<DescriptorFile> descriptorFiles = certsReader.readDescriptors(); int processedCerts = 0, verifiedCerts = 0; while (descriptorFiles.hasNext()) { DescriptorFile descriptorFile = descriptorFiles.next(); if (descriptorFile.getException() != null) { System.err.println("Could not read/parse descriptor file " + descriptorFile.getFileName() + ": " + descriptorFile.getException().getMessage()); continue; } if (descriptorFile.getDescriptors() == null) { continue; } for (Descriptor descriptor : descriptorFile.getDescriptors()) { if (!(descriptor instanceof DirectoryKeyCertificate)) { continue; } DirectoryKeyCertificate cert = (DirectoryKeyCertificate) descriptor; boolean isVerified = true; /* Verify that the contained fingerprint is a hash of the signing * key. */ String dirIdentityKeyHashString = determineKeyHash(cert.getDirIdentityKey()); String fingerprintString = cert.getFingerprint().toLowerCase(); if (!dirIdentityKeyHashString.equals(fingerprintString)) { System.out.println("In " + descriptorFile.getFile() + ", the calculated directory identity key hash " + dirIdentityKeyHashString + " does not match the contained fingerprint " + fingerprintString + "!"); isVerified = false; } /* Verify that the router signature was created using the signing * key. */ if (!verifySignature(cert.getCertificateDigest(), cert.getDirKeyCertification(), cert.getDirIdentityKey())) { System.out.println("In " + descriptorFile.getFile() + ", the decrypted directory key certification does not " + "match the certificate digest!"); isVerified = false; } /* Determine the signing key digest and remember the signing key * to verify consensus signatures. */ String dirSigningKeyString = cert.getDirSigningKey(); PEMReader pemReader2 = new PEMReader(new StringReader(dirSigningKeyString)); RSAPublicKey dirSigningKey = (RSAPublicKey) pemReader2.readObject(); ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); new ASN1OutputStream(baos2) .writeObject(new org.bouncycastle.asn1.pkcs.RSAPublicKey(dirSigningKey.getModulus(), dirSigningKey.getPublicExponent()).toASN1Primitive()); byte[] pkcs2 = baos2.toByteArray(); byte[] dirSigningKeyHashBytes = new byte[20]; SHA1Digest sha1_2 = new SHA1Digest(); sha1_2.update(pkcs2, 0, pkcs2.length); sha1_2.doFinal(dirSigningKeyHashBytes, 0); String dirSigningKeyHashString = Hex.encodeHexString(dirSigningKeyHashBytes).toUpperCase(); signingKeys.put(dirSigningKeyHashString, cert.getDirSigningKey()); processedCerts++; if (isVerified) { verifiedCerts++; } } } System.out.println("Verified " + verifiedCerts + "/" + processedCerts + " certs."); DescriptorReader consensusReader = DescriptorSourceFactory.createDescriptorReader(); consensusReader.addDirectory(consensusDirectory); Iterator<DescriptorFile> consensusFiles = consensusReader.readDescriptors(); int processedConsensuses = 0, verifiedConsensuses = 0; while (consensusFiles.hasNext()) { DescriptorFile consensusFile = consensusFiles.next(); if (consensusFile.getException() != null) { System.err.println("Could not read/parse descriptor file " + consensusFile.getFileName() + ": " + consensusFile.getException().getMessage()); continue; } if (consensusFile.getDescriptors() == null) { continue; } for (Descriptor descriptor : consensusFile.getDescriptors()) { if (!(descriptor instanceof RelayNetworkStatusConsensus)) { continue; } RelayNetworkStatusConsensus consensus = (RelayNetworkStatusConsensus) descriptor; boolean isVerified = true; /* Verify all signatures using the corresponding certificates. */ if (consensus.getDirectorySignatures().isEmpty()) { System.out.println(consensusFile.getFile() + " does not contain any signatures."); continue; } for (DirectorySignature signature : consensus.getDirectorySignatures().values()) { String signingKeyDigest = signature.getSigningKeyDigest(); if (!signingKeys.containsKey(signingKeyDigest)) { System.out.println("Cannot find signing key with digest " + signingKeyDigest + "!"); } if (!verifySignature(consensus.getConsensusDigest(), signature.getSignature(), signingKeys.get(signingKeyDigest))) { System.out.println("In " + consensusFile.getFile() + ", the decrypted signature digest does not match the " + "consensus digest!"); isVerified = false; } } processedConsensuses++; if (isVerified) { verifiedConsensuses++; } } } System.out.println("Verified " + verifiedConsensuses + "/" + processedConsensuses + " consensuses."); }
From source file:VerifyDescriptors.java
License:Open Source License
private static String determineKeyHash(String key) throws Exception { PEMReader pemReader = new PEMReader(new StringReader(key)); RSAPublicKey dirIdentityKey = (RSAPublicKey) pemReader.readObject(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); new ASN1OutputStream(baos) .writeObject(new org.bouncycastle.asn1.pkcs.RSAPublicKey(dirIdentityKey.getModulus(), dirIdentityKey.getPublicExponent()).toASN1Primitive()); byte[] pkcs = baos.toByteArray(); byte[] dirIdentityKeyHashBytes = new byte[20]; SHA1Digest sha1 = new SHA1Digest(); sha1.update(pkcs, 0, pkcs.length);// w ww . j a v a2 s .co m sha1.doFinal(dirIdentityKeyHashBytes, 0); String keyHash = Hex.encodeHexString(dirIdentityKeyHashBytes); return keyHash; }
From source file:android.core.CryptoTest.java
License:Apache License
/** * Tests the SHA-1 implementation./*from ww w.j a v a 2 s. c o m*/ */ @MediumTest public void testSHA1() { Digest oldDigest = new SHA1Digest(); Digest newDigest = OpenSSLMessageDigest.getInstance("SHA-1"); doTestMessageDigest(oldDigest, newDigest); }
From source file:android.webkit.CacheManager.java
License:Apache License
@SuppressWarnings("deprecation") private static void setupFiles(String url, CacheResult cacheRet) { if (true) {// w w w.j a va 2 s. c o m // Note: SHA1 is much stronger hash. But the cost of setupFiles() is // 3.2% cpu time for a fresh load of nytimes.com. While a simple // String.hashCode() is only 0.6%. If adding the collision resolving // to String.hashCode(), it makes the cpu time to be 1.6% for a // fresh load, but 5.3% for the worst case where all the files // already exist in the file system, but database is gone. So it // needs to resolve collision for every file at least once. int hashCode = url.hashCode(); StringBuffer ret = new StringBuffer(8); appendAsHex(hashCode, ret); String path = ret.toString(); File file = new File(mBaseDir, path); if (true) { boolean checkOldPath = true; // Check hash collision. If the hash file doesn't exist, just // continue. There is a chance that the old cache file is not // same as the hash file. As mDataBase.getCache() is more // expansive than "leak" a file until clear cache, don't bother. // If the hash file exists, make sure that it is same as the // cache file. If it is not, resolve the collision. while (file.exists()) { if (checkOldPath) { CacheResult oldResult = mDataBase.getCache(url); if (oldResult != null && oldResult.contentLength > 0) { if (path.equals(oldResult.localPath)) { path = oldResult.localPath; } else { path = oldResult.localPath; file = new File(mBaseDir, path); } break; } checkOldPath = false; } ret = new StringBuffer(8); appendAsHex(++hashCode, ret); path = ret.toString(); file = new File(mBaseDir, path); } } cacheRet.localPath = path; cacheRet.outFile = file; } else { // get hash in byte[] Digest digest = new SHA1Digest(); int digestLen = digest.getDigestSize(); byte[] hash = new byte[digestLen]; int urlLen = url.length(); byte[] data = new byte[urlLen]; url.getBytes(0, urlLen, data, 0); digest.update(data, 0, urlLen); digest.doFinal(hash, 0); // convert byte[] to hex String StringBuffer result = new StringBuffer(2 * digestLen); for (int i = 0; i < digestLen; i = i + 4) { int h = (0x00ff & hash[i]) << 24 | (0x00ff & hash[i + 1]) << 16 | (0x00ff & hash[i + 2]) << 8 | (0x00ff & hash[i + 3]); appendAsHex(h, result); } cacheRet.localPath = result.toString(); cacheRet.outFile = new File(mBaseDir, cacheRet.localPath); } }
From source file:at.archistar.crypto.random.BCDigestRandomSource.java
public BCDigestRandomSource() { this.drng = new DigestRandomGenerator(new SHA1Digest()); }
From source file:bluecrystal.service.service.SignVerifyService.java
License:Open Source License
private Digest getHashById(int hashId) { Digest ret = null;/*from ww w .j a v a2s . com*/ switch (hashId) { case DerEncoder.NDX_SHA1: ret = new SHA1Digest(); break; case DerEncoder.NDX_SHA224: ret = new SHA224Digest(); break; case DerEncoder.NDX_SHA256: ret = new SHA256Digest(); break; case DerEncoder.NDX_SHA384: ret = new SHA384Digest(); break; case DerEncoder.NDX_SHA512: ret = new SHA512Digest(); break; default: break; } return ret; }
From source file:ch.bfh.unicert.certimport.CertificateIssuer.java
License:GNU General Public License
public Certificate createClientCertificate(IdentityData id, String keyStorePath, PublicKey pk, int validity, String applicationIdentifier, String[] roles, String uniBoardWsdlURL, String uniBoardServiceURL, String section) throws CertificateCreationException { X509Certificate caCert;/*from w w w . j a v a 2 s . c o m*/ RSAPrivateCrtKey privKey; try { caCert = this.readIssuerCertificate(this.issuerId); privKey = this.readPrivateKey(this.issuerId, this.privKeyPass); } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException ex) { logger.log(Level.SEVERE, null, ex); throw new CertificateCreationException("230 Could not create client certificate. Key error"); } RSAPrivateCrtKeyParameters cipherParams = this.createIssuerCipherParams(privKey); X509Certificate clientCert; Hashtable extension = new Hashtable(); extension.put(new DERObjectIdentifier(ExtensionOID.APPLICATION_IDENTIFIER.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(applicationIdentifier))); String completeRole = ""; for (String role : roles) { completeRole += role + ", "; } completeRole = completeRole.substring(0, completeRole.length() - 2); extension.put(new DERObjectIdentifier(ExtensionOID.ROLE.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(completeRole))); extension.put(new DERObjectIdentifier(ExtensionOID.IDENTITY_PROVIDER.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(id.getIdentityProvider()))); Map<String, String> extensionMap = new HashMap(); if (id.getOtherValues() != null) { for (Entry<ExtensionOID, String> entry : id.getOtherValues().entrySet()) { extension.put(new DERObjectIdentifier(entry.getKey().getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(entry.getValue()))); extensionMap.put(entry.getKey().getName(), entry.getValue()); } } try { String x509NameString = ""; x509NameString += "CN=" + id.getCommonName(); if (id.getSurname() != null && !id.getSurname().equals("")) { x509NameString += ", SURNAME=" + id.getSurname(); } if (id.getGivenName() != null && !id.getGivenName().equals("")) { x509NameString += ", GIVENNAME=" + id.getGivenName(); } if (id.getUniqueIdentifier() != null && !id.getUniqueIdentifier().equals("")) { x509NameString += ", UID=" + id.getUniqueIdentifier(); } if (id.getOrganisation() != null && !id.getOrganisation().equals("")) { x509NameString += ", O=" + id.getOrganisation(); } if (id.getOrganisationUnit() != null && !id.getOrganisationUnit().equals("")) { x509NameString += ", OU=" + id.getOrganisationUnit(); } if (id.getCountryName() != null && !id.getCountryName().equals("")) { x509NameString += ", C=" + id.getCountryName(); } if (id.getState() != null && !id.getState().equals("")) { x509NameString += ", ST=" + id.getState(); } if (id.getLocality() != null && !id.getLocality().equals("")) { x509NameString += ", L=" + id.getLocality(); } X509Name x509Name = new X509Name(x509NameString); V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator(); certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis()))); certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert)); certGen.setSubject(x509Name); certGen.setExtensions(new X509Extensions(extension)); DERObjectIdentifier sigOID = new DERObjectIdentifier("1.2.840.113549.1.1.5"); AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull()); certGen.setSignature(sigAlgId); certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pk.getEncoded())).readObject())); certGen.setStartDate(new Time(new Date(System.currentTimeMillis()))); certGen.setEndDate(new Time(getExpiryDate(validity).getTime())); TBSCertificateStructure tbsCert = certGen.generateTBSCertificate(); //Sign certificate SHA1Digest digester = new SHA1Digest(); AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine()); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); dOut.writeObject(tbsCert); byte[] signature; byte[] certBlock = bOut.toByteArray(); // first create digest digester.update(certBlock, 0, certBlock.length); byte[] hash = new byte[digester.getDigestSize()]; digester.doFinal(hash, 0); // then sign it rsa.init(true, cipherParams); DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash); byte[] digest = dInfo.getEncoded(ASN1Encodable.DER); signature = rsa.processBlock(digest, 0, digest.length); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(tbsCert); v.add(sigAlgId); v.add(new DERBitString(signature)); // Create CRT data structure clientCert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(v))); clientCert.verify(caCert.getPublicKey()); } catch (IOException | InvalidCipherTextException | CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException | SignatureException e) { logger.log(Level.SEVERE, "Could not create client certificate: {0}", new Object[] { e.getMessage() }); throw new CertificateCreationException("230 Could not create client certificate"); } Certificate cert = new Certificate(clientCert, id.getCommonName(), id.getUniqueIdentifier(), id.getOrganisation(), id.getOrganisationUnit(), id.getCountryName(), id.getState(), id.getLocality(), id.getSurname(), id.getGivenName(), applicationIdentifier, roles, id.getIdentityProvider(), extensionMap); //post message on UniBoard if corresponding JNDI parameter is defined postOnUniBoard(cert, uniBoardWsdlURL, uniBoardServiceURL, section, (RSAPublicKey) caCert.getPublicKey(), privKey); return cert; }
From source file:ch.bfh.unicert.issuer.CertificateIssuerBean.java
License:GNU General Public License
/** * Actually creates the requestor certificate. * * @param id requestor identity data//from ww w . j a v a2s . c o m * @param caCert certificate of the certification authority * @param cipherParams issuer private key parameters used for signing * @param pk public key of the requestor to certify * @param expiry the expiry date * @param applicationIdentifier the application identifier for which te certificate is issued * @param role role for which the certificate is issued * @return the certificate object containing the X509 certificate * @throws CertificateCreationException if an error occurs */ private Certificate createClientCertificate(IdentityData id, X509Certificate caCert, CipherParameters cipherParams, PublicKey pk, Calendar expiry, String applicationIdentifier, String[] roles) throws CertificateCreationException { X509Certificate clientCert; Hashtable extension = new Hashtable(); extension.put(new DERObjectIdentifier(ExtensionOID.APPLICATION_IDENTIFIER.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(applicationIdentifier))); String completeRole = ""; for (String role : roles) { completeRole += role + ", "; } completeRole = completeRole.substring(0, completeRole.length() - 2); extension.put(new DERObjectIdentifier(ExtensionOID.ROLE.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(completeRole))); extension.put(new DERObjectIdentifier(ExtensionOID.IDENTITY_PROVIDER.getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(id.getIdentityProvider()))); Map<String, String> extensionMap = new HashMap(); if (id.getOtherValues() != null) { for (Entry<ExtensionOID, String> entry : id.getOtherValues().entrySet()) { extension.put(new DERObjectIdentifier(entry.getKey().getOID()), new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(entry.getValue()))); extensionMap.put(entry.getKey().getName(), entry.getValue()); } } try { String x509NameString = ""; x509NameString += "CN=" + id.getCommonName(); if (id.getSurname() != null && !id.getSurname().equals("")) { x509NameString += ", SURNAME=" + id.getSurname(); } if (id.getGivenName() != null && !id.getGivenName().equals("")) { x509NameString += ", GIVENNAME=" + id.getGivenName(); } if (id.getUniqueIdentifier() != null && !id.getUniqueIdentifier().equals("")) { x509NameString += ", UID=" + id.getUniqueIdentifier(); } if (id.getOrganisation() != null && !id.getOrganisation().equals("")) { x509NameString += ", O=" + id.getOrganisation(); } if (id.getOrganisationUnit() != null && !id.getOrganisationUnit().equals("")) { x509NameString += ", OU=" + id.getOrganisationUnit(); } if (id.getCountryName() != null && !id.getCountryName().equals("")) { x509NameString += ", C=" + id.getCountryName(); } if (id.getState() != null && !id.getState().equals("")) { x509NameString += ", ST=" + id.getState(); } if (id.getLocality() != null && !id.getLocality().equals("")) { x509NameString += ", L=" + id.getLocality(); } X509Name x509Name = new X509Name(x509NameString); V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator(); certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis()))); certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert)); certGen.setSubject(x509Name); certGen.setExtensions(new X509Extensions(extension)); DERObjectIdentifier sigOID = new DERObjectIdentifier("1.2.840.113549.1.1.5"); AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull()); certGen.setSignature(sigAlgId); certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pk.getEncoded())).readObject())); certGen.setStartDate(new Time(new Date(System.currentTimeMillis()))); certGen.setEndDate(new Time(expiry.getTime())); TBSCertificateStructure tbsCert = certGen.generateTBSCertificate(); //Sign certificate SHA1Digest digester = new SHA1Digest(); AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine()); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); dOut.writeObject(tbsCert); byte[] signature; byte[] certBlock = bOut.toByteArray(); // first create digest digester.update(certBlock, 0, certBlock.length); byte[] hash = new byte[digester.getDigestSize()]; digester.doFinal(hash, 0); // then sign it rsa.init(true, cipherParams); DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash); byte[] digest = dInfo.getEncoded(ASN1Encodable.DER); signature = rsa.processBlock(digest, 0, digest.length); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(tbsCert); v.add(sigAlgId); v.add(new DERBitString(signature)); // Create CRT data structure clientCert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(v))); clientCert.verify(caCert.getPublicKey()); } catch (IOException | CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException | InvalidCipherTextException | SignatureException e) { logger.log(Level.SEVERE, "Could not create client certificate: {0}", new Object[] { e.getMessage() }); throw new CertificateCreationException("230 Could not create client certificate"); } return new Certificate(clientCert, id.getCommonName(), id.getUniqueIdentifier(), id.getOrganisation(), id.getOrganisationUnit(), id.getCountryName(), id.getState(), id.getLocality(), id.getSurname(), id.getGivenName(), applicationIdentifier, roles, id.getIdentityProvider(), extensionMap); }