List of usage examples for org.bouncycastle.crypto.util PublicKeyFactory createKey
public static AsymmetricKeyParameter createKey(SubjectPublicKeyInfo keyInfo) throws IOException
From source file:be.neutrinet.ispng.vpn.api.VPNClientCertificate.java
@Put public Representation storeCSR(Representation csrstream) { if (!getRequestAttributes().containsKey("client")) { return clientError("MALFORMED_REQUEST", Status.CLIENT_ERROR_BAD_REQUEST); }//from w w w.j a v a 2 s .c o m StreamRepresentation sr = (StreamRepresentation) csrstream; // Do all kinds of security checks try { Client client = Clients.dao.queryForId(getAttribute("client").toString()); PEMParser parser = new PEMParser(sr.getReader()); PKCS10CertificationRequest csr = (PKCS10CertificationRequest) parser.readObject(); SubjectPublicKeyInfo pkInfo = csr.getSubjectPublicKeyInfo(); RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(pkInfo); // This makes the NSA work harder on their quantum computer // Require 4096 bit key // http://stackoverflow.com/a/20622933 if (!(rsa.getModulus().bitLength() > 2048)) { ClientError err = new ClientError("ILLEGAL_KEY_SIZE"); return new JacksonRepresentation(err); } X500Name subject = X500Name.getInstance(csr.getSubject()); RDN[] rdns = subject.getRDNs(BCStyle.CN); if (rdns == null || rdns.length == 0) { return clientError("NO_CSR_CN", Status.CLIENT_ERROR_BAD_REQUEST); } String CN = IETFUtils.valueToString(rdns[0].getFirst().getValue()); if (CN == null || CN.isEmpty()) { return clientError("INVALID_CSR_CN", Status.CLIENT_ERROR_BAD_REQUEST); } if (getQueryValue("rekey") != null && Boolean.parseBoolean(getQueryValue("rekey"))) { if (!getRequestAttributes().containsKey("cert")) { return clientError("MALFORMED_REQUEST", Status.CLIENT_ERROR_BAD_REQUEST); } Certificate old = Certificates.dao.queryForId(getAttribute("cert")); if (old == null) return clientError("MALFORMED_REQUEST", Status.CLIENT_ERROR_BAD_REQUEST); old.revocationDate = new Date(); if (old.get() == null) { // this can happen when the old certificate is no longer present on the system // in which case the rekey has to go through } else if (pkInfo.getPublicKeyData().getString() .equals(old.get().getSubjectPublicKeyInfo().getPublicKeyData().getString())) { return clientError("REKEY_USING_SAME_KEY", Status.CLIENT_ERROR_NOT_ACCEPTABLE); } Certificates.dao.update(old); } for (Certificate existingCert : Certificates.dao.queryForEq("client_id", client)) { if (existingCert.revocationDate.getTime() > System.currentTimeMillis()) { return clientError("ANOTHER_CLIENT_CERT_ACTIVE", Status.CLIENT_ERROR_NOT_ACCEPTABLE); } } // couple CN to client client.commonName = CN; Clients.dao.update(client); String caStorePath = VPN.cfg.getProperty("ca.storeDir", "ca"); File dir = new File(caStorePath); if (!dir.isDirectory()) { dir.mkdirs(); } Certificate cert = new Certificate(); cert.client = client; Certificates.dao.create(cert); FileWriter fw = new FileWriter(caStorePath + "/" + cert.id + ".csr"); PEMWriter pw = new PEMWriter(fw); pw.writeObject(csr); pw.flush(); return new JacksonRepresentation<>(cert); } catch (Exception ex) { Logger.getLogger(getClass()).error("Failed to validate CSR and/or sign CSR", ex); } return DEFAULT_ERROR; }
From source file:co.lqnt.lockbox.util.BcKeyParametersFactory.java
License:Open Source License
/** * Create a new Bouncy Castle public key parameters instance. * * @param keyInformation The Bouncy Castle public key information. * * @return The Bouncy Castle public key parameters. * @throws IOException If the key conversion fails. *//*from w w w.j av a 2 s. c om*/ public AsymmetricKeyParameter createPublicKeyParameters(final SubjectPublicKeyInfo keyInformation) throws IOException { return PublicKeyFactory.createKey(keyInformation); }
From source file:com.aqnote.shared.cryptology.cert.gen.CertGenerator.java
License:Open Source License
public X509Certificate signCert(PKCS10CertificationRequest pkcs10CSR, X500Name issuer, KeyPair pKeyPair) throws Exception { SubjectPublicKeyInfo pkInfo = pkcs10CSR.getSubjectPublicKeyInfo(); RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(pkInfo); RSAPublicKeySpec rsaSpec = new RSAPublicKeySpec(rsa.getModulus(), rsa.getExponent()); KeyFactory kf = KeyFactory.getInstance(ALG_RSA); PublicKey publicKey = kf.generatePublic(rsaSpec); SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(publicKey.getEncoded())); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, BigInteger.valueOf(System.currentTimeMillis()), new Date(System.currentTimeMillis() - DateConstant.ONE_DAY), new Date(System.currentTimeMillis() + DateConstant.ONE_YEAR), pkcs10CSR.getSubject(), keyInfo); ContentSigner signer = new JcaContentSignerBuilder(ALG_SIG_SHA256_RSA).setProvider(JCE_PROVIDER) .build(pKeyPair.getPrivate()); X509Certificate signedCert = new JcaX509CertificateConverter().setProvider(JCE_PROVIDER) .getCertificate(certBuilder.build(signer)); signedCert.verify(pKeyPair.getPublic()); return signedCert; }
From source file:com.logicoy.pdmp.pmpi.crypto.EncryptionClient.java
License:Apache License
public String rsaEncryptPassword(String publicKeyInPEM, String password) { String encrypted = ""; try {/* w w w . j a v a 2 s. co m*/ RSAKeyParameters rsaPublicKey; Reader reader = new StringReader(publicKeyInPEM); PemObject pemObj = new PemReader(reader).readPemObject(); rsaPublicKey = (RSAKeyParameters) PublicKeyFactory.createKey(pemObj.getContent()); byte[] bytesToEncrypt = password.getBytes(Charset.forName("UTF-8")); PKCS1Encoding encryptEngine = new PKCS1Encoding(new RSAEngine()); encryptEngine.init(true, rsaPublicKey); encrypted = new String( Base64.encode(encryptEngine.processBlock(bytesToEncrypt, 0, bytesToEncrypt.length)), Charset.forName("UTF-8")); } catch (Exception ex) { logger.severe(" Failure attempting to encrypt via RSA. \r\n PublicKeyInPEM:" + publicKeyInPEM + "\r\n Exception : " + ex.toString()); throw new RuntimeException( " Failure attempting to encrypt the RSA encrypted password. See Interface log for more details. Message : " + ex.getMessage()); } return encrypted; }
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 w w.j a v a2s.com 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 {/*w w w. j ava2 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 w ww . j a v a2s . com*/ 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 boolean sendEncryptionKeyResponse(byte[] secret, PacketChannel client, PacketChannel server, P16xEncryptionKeyRequest request) throws IOException { AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine()); AsymmetricKeyParameter publicKey = PublicKeyFactory.createKey(request.getPubKey()); rsa.init(true, publicKey);// ww w . jav a 2 s. c om byte[] encryptedSecret; byte[] encryptedToken; try { encryptedSecret = rsa.processBlock(secret, 0, secret.length); } catch (InvalidCipherTextException e) { sendKick("Unable to encrypt shared secret " + e.getMessage(), client); return false; } try { encryptedToken = rsa.processBlock(request.getToken(), 0, request.getToken().length); } catch (InvalidCipherTextException e) { sendKick("Unable to encrypt token " + e.getMessage(), client); return false; } server.writePacket(new P16xEncryptionKeyResponse(encryptedSecret, encryptedToken)); return true; }
From source file:com.raphfrk.craftproxyclient.net.protocol.p17xlogin.P17xLoginProtocol.java
License:Open Source License
private boolean sendEncryptionKeyResponse(byte[] secret, PacketChannel client, PacketChannel server, P17xEncryptionKeyRequest request) throws IOException { AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine()); AsymmetricKeyParameter publicKey = PublicKeyFactory.createKey(request.getPubKey()); rsa.init(true, publicKey);/*w w w .j a v a 2 s .co m*/ byte[] encryptedSecret; byte[] encryptedToken; try { encryptedSecret = rsa.processBlock(secret, 0, secret.length); } catch (InvalidCipherTextException e) { sendKick("Unable to encrypt shared secret " + e.getMessage(), client); return false; } try { encryptedToken = rsa.processBlock(request.getToken(), 0, request.getToken().length); } catch (InvalidCipherTextException e) { sendKick("Unable to encrypt token " + e.getMessage(), client); return false; } server.writePacket(new P17xEncryptionKeyResponse(encryptedSecret, encryptedToken)); return true; }
From source file:de.rub.nds.tlsattacker.tls.protocol.handshake.DHClientKeyExchangeHandler.java
License:Apache License
@Override byte[] prepareKeyExchangeMessage() { if (tlsContext.getServerDHParameters() == null) { // we are probably handling a simple DH ciphersuite, we try to // establish server public key parameters from the server // certificate message Certificate x509Cert = tlsContext.getServerCertificate(); SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo(); DHPublicKeyParameters parameters; try {//from w w w . j a va2 s. c o m parameters = (DHPublicKeyParameters) PublicKeyFactory.createKey(keyInfo); tlsContext.setServerDHParameters(new ServerDHParams(parameters)); } catch (IOException e) { throw new WorkflowExecutionException("Problem in parsing public key parameters from certificate", e); } } // generate client's original dh public and private key, based on the // server's public parameters AsymmetricCipherKeyPair kp = TlsDHUtils.generateDHKeyPair(new SecureRandom(), tlsContext.getServerDHParameters().getPublicKey().getParameters()); DHPublicKeyParameters dhPublic = (DHPublicKeyParameters) kp.getPublic(); DHPrivateKeyParameters dhPrivate = (DHPrivateKeyParameters) kp.getPrivate(); protocolMessage.setG(dhPublic.getParameters().getG()); protocolMessage.setP(dhPublic.getParameters().getP()); protocolMessage.setY(dhPublic.getY()); protocolMessage.setX(dhPrivate.getX()); // set the modified values of client's private and public parameters DHParameters newParams = new DHParameters(protocolMessage.getP().getValue(), protocolMessage.getG().getValue()); // DHPublicKeyParameters newDhPublic = new // DHPublicKeyParameters(dhMessage.getY().getValue(), newParams); DHPrivateKeyParameters newDhPrivate = new DHPrivateKeyParameters(protocolMessage.getX().getValue(), newParams); byte[] serializedPublicKey = BigIntegers.asUnsignedByteArray(protocolMessage.getY().getValue()); protocolMessage.setSerializedPublicKey(serializedPublicKey); protocolMessage.setSerializedPublicKeyLength(serializedPublicKey.length); byte[] result = ArrayConverter .concatenate( ArrayConverter.intToBytes(protocolMessage.getSerializedPublicKeyLength().getValue(), HandshakeByteLength.DH_PARAM_LENGTH), protocolMessage.getSerializedPublicKey().getValue()); byte[] premasterSecret = TlsDHUtils .calculateDHBasicAgreement(tlsContext.getServerDHParameters().getPublicKey(), newDhPrivate); protocolMessage.setPremasterSecret(premasterSecret); LOGGER.debug("Computed PreMaster Secret: {}", ArrayConverter.bytesToHexString(protocolMessage.getPremasterSecret().getValue())); byte[] random = tlsContext.getClientServerRandom(); PRFAlgorithm prfAlgorithm = AlgorithmResolver.getPRFAlgorithm(tlsContext.getProtocolVersion(), tlsContext.getSelectedCipherSuite()); byte[] masterSecret = PseudoRandomFunction.compute(prfAlgorithm, protocolMessage.getPremasterSecret().getValue(), PseudoRandomFunction.MASTER_SECRET_LABEL, random, HandshakeByteLength.MASTER_SECRET); LOGGER.debug("Computed Master Secret: {}", ArrayConverter.bytesToHexString(masterSecret)); protocolMessage.setMasterSecret(masterSecret); tlsContext.setMasterSecret(protocolMessage.getMasterSecret().getValue()); return result; }