List of usage examples for org.bouncycastle.crypto AsymmetricBlockCipher init
public void init(boolean forEncryption, CipherParameters param);
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 ww . ja v a 2 s .com 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//w ww . j a va 2s . c om * @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); }
From source file:com.foilen.smalltools.crypt.AbstractAsymmetricBlockCipherCrypt.java
License:Open Source License
/** * Encrypt/Decrypt the data with the specified key. * /*from w ww .j a va 2 s . c o m*/ * @param key * the key * @param in * the data to encrypt/decrypt * @param crypt * true to encrypt;false to decrypt * @return the encrypted/decrypted data */ private byte[] process(AsymmetricKeyParameter key, byte[] in, boolean crypt) { log.debug("process() crypt {} in.length {}", crypt, in.length); try { // Prepare cipher AsymmetricBlockCipher asymmetricBlockCipher = generateAsymmetricBlockCipher(); asymmetricBlockCipher.init(crypt, key); // Process return asymmetricBlockCipher.processBlock(in, 0, in.length); } catch (Exception e) { throw new SmallToolsException("Could not process", e); } }
From source file:com.foilen.smalltools.crypt.bouncycastle.asymmetric.AbstractAsymmetricBlockCipherCrypt.java
License:Open Source License
/** * Encrypt/Decrypt the data with the specified key. * * @param key//from www. java 2 s . c om * the key * @param in * the data to encrypt/decrypt * @param crypt * true to encrypt;false to decrypt * @return the encrypted/decrypted data */ private byte[] process(AsymmetricKeyParameter key, byte[] in, boolean crypt) { log.debug("process() crypt {} in.length {}", crypt, in.length); try { // Prepare cipher AsymmetricBlockCipher asymmetricBlockCipher = generateAsymmetricBlockCipher(); asymmetricBlockCipher.init(crypt, key); // Process return asymmetricBlockCipher.processBlock(in, 0, in.length); } catch (Exception e) { throw new SmallToolsException("Could not process", e); } }
From source file:com.geoxp.oss.CryptoHelper.java
License:Apache License
/** * Encrypt data using RSA.// w w w. j a v a2s .com * CAUTION: this can take a while on large data * * @param key RSA key to use for encryption * @param data Cleartext data * @return The ciphertext data or null if an error occured */ public static byte[] encryptRSA(Key key, byte[] data) { // // Get an RSA Cipher instance // //Cipher rsa = null; try { /* The following commented code can be used the BouncyCastle * JCE provider signature is intact, which is not the * case when BC has been repackaged using jarjar rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC"); rsa.init (Cipher.ENCRYPT_MODE, key, CryptoHelper.sr); return rsa.doFinal(data); */ AsymmetricBlockCipher c = new PKCS1Encoding(new RSABlindedEngine()); if (key instanceof RSAPublicKey) { c.init(true, new RSAKeyParameters(true, ((RSAPublicKey) key).getModulus(), ((RSAPublicKey) key).getPublicExponent())); } else if (key instanceof RSAPrivateKey) { c.init(true, new RSAKeyParameters(true, ((RSAPrivateKey) key).getModulus(), ((RSAPrivateKey) key).getPrivateExponent())); } else { return null; } int insize = c.getInputBlockSize(); int offset = 0; ByteArrayOutputStream baos = new ByteArrayOutputStream(); while (offset < data.length) { int len = Math.min(insize, data.length - offset); baos.write(c.processBlock(data, offset, len)); offset += len; } return baos.toByteArray(); /* } catch (NoSuchProviderException nspe) { return null; } catch (NoSuchPaddingException nspe) { return null; } catch (NoSuchAlgorithmException nsae) { return null; } catch (InvalidKeyException ike) { return null; } catch (BadPaddingException bpe) { return null; } catch (IllegalBlockSizeException ibse) { return null; } */ } catch (InvalidCipherTextException icte) { return null; } catch (IOException ioe) { return null; } }
From source file:com.geoxp.oss.CryptoHelper.java
License:Apache License
/** * Decrypt data previously encrypted with RSA * @param key RSA key to use for decryption * @param data Ciphertext data//from w ww . ja v a2s. c om * @return The cleartext data or null if an error occurred */ public static byte[] decryptRSA(Key key, byte[] data) { // // Get an RSA Cipher instance // //Cipher rsa = null; try { /* The following commented code can be used the BouncyCastle * JCE provider signature is intact, which is not the * case when BC has been repackaged using jarjar rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC"); rsa.init (Cipher.DECRYPT_MODE, key, CryptoHelper.sr); return rsa.doFinal(data); */ AsymmetricBlockCipher c = new PKCS1Encoding(new RSABlindedEngine()); if (key instanceof RSAPublicKey) { c.init(false, new RSAKeyParameters(true, ((RSAPublicKey) key).getModulus(), ((RSAPublicKey) key).getPublicExponent())); } else if (key instanceof RSAPrivateKey) { c.init(false, new RSAKeyParameters(true, ((RSAPrivateKey) key).getModulus(), ((RSAPrivateKey) key).getPrivateExponent())); } else { return null; } int insize = c.getInputBlockSize(); int offset = 0; ByteArrayOutputStream baos = new ByteArrayOutputStream(); while (offset < data.length) { int len = Math.min(insize, data.length - offset); baos.write(c.processBlock(data, offset, len)); offset += len; } return baos.toByteArray(); /* } catch (NoSuchProviderException nspe) { return null; } catch (NoSuchPaddingException nspe) { return null; } catch (NoSuchAlgorithmException nsae) { return null; } catch (InvalidKeyException ike) { return null; } catch (BadPaddingException bpe) { return null; } catch (IllegalBlockSizeException ibse) { return null; } */ } catch (InvalidCipherTextException icte) { return null; } catch (IOException ioe) { return null; } }
From source file:com.maiereni.util.EncryptedFileLoader.java
License:Apache License
private AsymmetricBlockCipher getAsymmetricBlockCipher(boolean encoding) throws Exception { KeyPair keyPair = getKeyPair(); AsymmetricKeyParameter key = null;//from w ww .ja v a 2s. c om if (encoding) { key = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded()); } else { key = PublicKeyFactory.createKey(keyPair.getPublic().getEncoded()); } AsymmetricBlockCipher ret = new PKCS1Encoding(new RSAEngine()); ret.init(encoding, key); return ret; }
From source file:com.oth.jasds.crypto.Crypto.java
@Override public String encryptFileKey(byte[] fileKey, PublicKey pubKey) { try {/*from ww w . j a v a 2 s.c o m*/ AsymmetricBlockCipher e = new RSAEngine(); e = new PKCS1Encoding(e); AsymmetricKeyParameter pub = (AsymmetricKeyParameter) PublicKeyFactory.createKey(pubKey.getEncoded()); e.init(true, pub); byte[] encFk = e.processBlock(fileKey, 0, fileKey.length); BASE64Encoder b64 = new BASE64Encoder(); return b64.encode(encFk); } catch (IOException ex) { Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidCipherTextException ex) { Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex); } return null; }
From source file:com.oth.jasds.crypto.Crypto.java
@Override public byte[] decryptFileKey(String fileKey, PrivateKey prvKey) { try {/*from ww w .ja va 2 s. co m*/ AsymmetricBlockCipher e = new RSAEngine(); e = new PKCS1Encoding(e); AsymmetricKeyParameter pub = (AsymmetricKeyParameter) PublicKeyFactory.createKey(prvKey.getEncoded()); e.init(true, pub); BASE64Decoder b64 = new BASE64Decoder(); byte[] fk = b64.decodeBuffer(fileKey); byte[] decfk = e.processBlock(fk, 0, fk.length); return decfk; } catch (IOException ex) { Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidCipherTextException ex) { Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex); } return null; }
From source file:com.raphfrk.craftproxyclient.net.protocol.p16x.P16xProtocol.java
License:Open Source License
private byte[] decryptSecret(AsymmetricCipherKeyPair RSAKeyPair, P16xEncryptionKeyResponse response, PacketChannel client, byte[] token) throws IOException { AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine()); AsymmetricKeyParameter privateKey = RSAKeyPair.getPrivate(); rsa.init(false, privateKey); byte[] decryptedSecret; byte[] decryptedToken; try {//from w w w . j av a 2 s. c om decryptedSecret = rsa.processBlock(response.getEncryptedSecret(), 0, response.getEncryptedSecret().length); } catch (InvalidCipherTextException e) { sendKick("Unable to encrypt shared secret " + e.getMessage(), client); return null; } try { decryptedToken = rsa.processBlock(response.getToken(), 0, response.getToken().length); } catch (InvalidCipherTextException e) { sendKick("Unable to encrypt token " + e.getMessage(), client); return null; } if (!Arrays.areEqual(token, decryptedToken)) { sendKick("Decrypted token mismatch", client); return null; } return decryptedSecret; }