List of usage examples for org.bouncycastle.crypto.engines RSAEngine RSAEngine
RSAEngine
From source file:VerifyDescriptors.java
License:Open Source License
private static boolean verifySignature(String digest, String signature, String signingKey) throws Exception { byte[] signatureBytes = Base64.decodeBase64(signature.substring(0 + "-----BEGIN SIGNATURE-----\n".length(), signature.length() - "-----END SIGNATURE-----\n".length()).replaceAll("\n", "")); RSAPublicKey rsaSigningKey = (RSAPublicKey) new PEMReader(new StringReader(signingKey)).readObject(); RSAKeyParameters rsakp = new RSAKeyParameters(false, rsaSigningKey.getModulus(), rsaSigningKey.getPublicExponent()); PKCS1Encoding pe = new PKCS1Encoding(new RSAEngine()); pe.init(false, rsakp);//from w ww .j a va 2 s . co m byte[] decryptedSignatureDigest = pe.processBlock(signatureBytes, 0, signatureBytes.length); String decryptedSignatureDigestString = Hex.encodeHexString(decryptedSignatureDigest); return decryptedSignatureDigestString.equalsIgnoreCase(digest); }
From source file:cf.monteux.silvertunnel.netlib.layer.tor.util.Encryption.java
License:Open Source License
/** * decrypt data with asymmetric key. create asymmetrically encrypted data:<br> * <ul>//from w w w . j av a 2 s .c om * <li>OAEP padding [42 bytes] (RSA-encrypted)</li> * <li>Symmetric key [16 bytes]</li> * <li>First part of data [70 bytes]</li> * <li>Second part of data [x-70 bytes] (Symmetrically encrypted)</li> * </ul> * encrypt and store in result * * @param priv key to use for decryption * @param data to be decrypted, needs currently to be at least 70 bytes long * @return raw data */ public static byte[] asymDecrypt(final RSAPrivateKey priv, final byte[] data) throws TorException { if (data == null) { throw new NullPointerException("can't encrypt NULL data"); } if (data.length < 70) { throw new TorException("input array too short"); } try { int encryptedBytes = 0; // init OAEP final OAEPEncoding oaep = new OAEPEncoding(new RSAEngine()); oaep.init(false, new RSAKeyParameters(true, priv.getModulus(), priv.getPrivateExponent())); // apply RSA+OAEP encryptedBytes = oaep.getInputBlockSize(); final byte[] oaepInput = new byte[encryptedBytes]; System.arraycopy(data, 0, oaepInput, 0, encryptedBytes); final byte[] part1 = oaep.decodeBlock(oaepInput, 0, encryptedBytes); // extract symmetric key final byte[] symmetricKey = new byte[16]; System.arraycopy(part1, 0, symmetricKey, 0, 16); // init AES final AESCounterMode aes = new AESCounterMode(symmetricKey); // apply AES final byte[] aesInput = new byte[data.length - encryptedBytes]; System.arraycopy(data, encryptedBytes, aesInput, 0, aesInput.length); final byte[] part2 = aes.processStream(aesInput); // replace unencrypted data final byte[] result = new byte[part1.length - 16 + part2.length]; System.arraycopy(part1, 16, result, 0, part1.length - 16); System.arraycopy(part2, 0, result, part1.length - 16, part2.length); return result; } catch (final InvalidCipherTextException e) { logger.error("Encryption.asymDecrypt(): can't decrypt cipher text:" + e.getMessage()); throw new TorException("Encryption.asymDecrypt(): InvalidCipherTextException:" + e.getMessage()); } }
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 va 2 s . co 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 w ww . j a v a 2 s .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:co.lqnt.lockbox.Cipher.java
License:Open Source License
/** * Construct a new bi-directional cipher. *//*from www . j a v a 2 s . c o m*/ public Cipher() { CodecInterface base64UriCodec = new Base64UriCodec(); AsymmetricBlockCipher rsaCipher = new OAEPEncoding(new RSAEngine(), new SHA1Digest()); BufferedBlockCipher aesCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding()); Digest sha1Digest = new SHA1Digest(); SecureRandom random = new SecureRandom(); this.encryptionCipher = new EncryptionCipher(base64UriCodec, rsaCipher, aesCipher, sha1Digest, random); this.decryptionCipher = new DecryptionCipher(base64UriCodec, rsaCipher, aesCipher, sha1Digest); }
From source file:co.lqnt.lockbox.DecryptionCipher.java
License:Open Source License
/** * Construct a new decryption cipher./*from ww w . ja va 2 s. c om*/ */ public DecryptionCipher() { this.base64UriCodec = new Base64UriCodec(); this.rsaCipher = new OAEPEncoding(new RSAEngine(), new SHA1Digest()); this.aesCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding()); this.sha1Digest = new SHA1Digest(); this.asciiCharset = Charset.forName("US-ASCII"); }
From source file:co.lqnt.lockbox.EncryptionCipher.java
License:Open Source License
/** * Construct a new encryption cipher./*from w w w. j a va 2 s .co m*/ */ public EncryptionCipher() { this.base64UriCodec = new Base64UriCodec(); this.rsaCipher = new OAEPEncoding(new RSAEngine(), new SHA1Digest()); this.aesCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding()); this.sha1Digest = new SHA1Digest(); this.random = new SecureRandom(); this.asciiCharset = Charset.forName("US-ASCII"); }
From source file:com.foilen.smalltools.crypt.asymmetric.RSACrypt.java
License:Open Source License
@Override protected AsymmetricBlockCipher generateAsymmetricBlockCipher() { return new PKCS1Encoding(new RSAEngine()); }
From source file:com.licel.jcardsim.crypto.AssymetricCipherImpl.java
License:Apache License
public AssymetricCipherImpl(byte algorithm) { this.algorithm = algorithm; switch (algorithm) { case ALG_RSA_NOPAD: engine = new RSAEngine(); paddingEngine = null;/* w w w . j av a2 s . c om*/ break; case ALG_RSA_PKCS1: engine = new PKCS1Encoding(new RSAEngine()); paddingEngine = null; break; default: CryptoException.throwIt(CryptoException.NO_SUCH_ALGORITHM); break; } }
From source file:com.licel.jcardsim.crypto.AsymmetricCipherImpl.java
License:Apache License
public AsymmetricCipherImpl(byte algorithm) { this.algorithm = algorithm; switch (algorithm) { case ALG_RSA_NOPAD: engine = new RSAEngine(); paddingEngine = null;/*from w ww.ja v a2 s.c o m*/ break; case ALG_RSA_PKCS1: engine = new PKCS1Encoding(new RSAEngine()); paddingEngine = null; break; default: CryptoException.throwIt(CryptoException.NO_SUCH_ALGORITHM); break; } }