List of usage examples for java.security KeyFactory generatePublic
public final PublicKey generatePublic(KeySpec keySpec) throws InvalidKeySpecException
From source file:org.javlo.external.agitos.dkim.DKIMUtil.java
public boolean checkDNSForPublickey(String signingDomain, String selector) throws DKIMSignerException { Hashtable<String, String> env = new Hashtable<String, String>(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); String recordname = selector + "._domainkey." + signingDomain; String value = null;//w w w .ja v a 2s .c om try { DirContext dnsContext = new InitialDirContext(env); javax.naming.directory.Attributes attribs = dnsContext.getAttributes(recordname, new String[] { "TXT" }); javax.naming.directory.Attribute txtrecord = attribs.get("txt"); if (txtrecord == null) { throw new DKIMSignerException("There is no TXT record available for " + recordname); } // "v=DKIM1; g=*; k=rsa; p=MIGfMA0G ..." value = (String) txtrecord.get(); } catch (NamingException ne) { throw new DKIMSignerException("Selector lookup failed", ne); } if (value == null) { throw new DKIMSignerException("Value of RR " + recordname + " couldn't be retrieved"); } // try to read public key from RR String[] tags = value.split(";"); for (String tag : tags) { tag = tag.trim(); if (tag.startsWith("p=")) { try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); // decode public key, FSTODO: convert to DER format PKCS8EncodedKeySpec pubSpec = new PKCS8EncodedKeySpec(tag.substring(2).getBytes()); RSAPrivateKey pubKey = (RSAPrivateKey) keyFactory.generatePublic(pubSpec); } catch (NoSuchAlgorithmException nsae) { throw new DKIMSignerException("RSA algorithm not found by JVM"); } catch (InvalidKeySpecException ikse) { throw new DKIMSignerException( "The public key " + tag + " in RR " + recordname + " couldn't be decoded."); } // FSTODO: create test signature with privKey and test validation with pubKey to check on a valid key pair return true; } } throw new DKIMSignerException("No public key available in " + recordname); }
From source file:tv.ouya.sample.game.OptionsActivity.java
/** * Called when the activity is first created. *///from w w w. j a va2 s. c o m @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.options); levelToRadioButton = new HashMap<Options.Level, RadioButton>(); levelToRadioButton.put(FREEDOM, ((RadioButton) findViewById(R.id.radio_freedom))); levelToRadioButton.put(ALLEYWAY, ((RadioButton) findViewById(R.id.radio_alleyway))); levelToRadioButton.put(BOXY, ((RadioButton) findViewById(R.id.radio_boxy))); try { InputStream inputStream = getResources().openRawResource(R.raw.key); applicationKey = new byte[inputStream.available()]; inputStream.read(applicationKey); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } // Create a reverse map radioButtonToLevel = new HashMap<RadioButton, Options.Level>(); for (Options.Level level : levelToRadioButton.keySet()) { radioButtonToLevel.put(levelToRadioButton.get(level), level); } // Initialize the UI processReceipts(null); toggleProgressIndicator(true); mOuyaFacade = OuyaFacade.getInstance(); mOuyaFacade.init(this, DEVELOPER_ID); String prevSelectedLevel = mOuyaFacade.getGameData(PREV_SELECTED_LEVEL_KEY); if (prevSelectedLevel != null) { Options.Level prevLevel = Options.Level.valueOf(prevSelectedLevel); Options.getInstance().setLevel(prevLevel); } levelToRadioButton.get(Options.getInstance().getLevel()).setChecked(true); Button quit = (Button) findViewById(R.id.back_button); quit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(applicationKey); try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); mPublicKey = keyFactory.generatePublic(keySpec); } catch (Exception e) { Log.e(LOG_TAG, "Unable to create encryption key", e); } }
From source file:com.vmware.demo.SamlService.java
public String validateSAMLResponse(String samlResponse, String samlCert) throws Exception { String decodedString = ""; try {//from ww w. ja va2s . c om decodedString = decodeSAMLResponse(samlResponse); InputStream inputStream = new ByteArrayInputStream(decodedString.getBytes("UTF-8")); // Parse XML BasicParserPool parserPoolManager = new BasicParserPool(); parserPoolManager.setNamespaceAware(true); parserPoolManager.setIgnoreElementContentWhitespace(true); Document document = parserPoolManager.parse(inputStream); Element metadataRoot = document.getDocumentElement(); QName qName = new QName(metadataRoot.getNamespaceURI(), metadataRoot.getLocalName(), metadataRoot.getPrefix()); // Unmarshall document Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory().getUnmarshaller(qName); Response response = (Response) unmarshaller.unmarshall(metadataRoot); Issuer issuer = response.getIssuer(); logger.info("Parsed response. Issued:" + response.getIssueInstant().toString() + ", issuer: " + issuer.getValue()); java.security.cert.X509Certificate jX509Cert = SamlUtils.parsePemCertificate(samlCert); if (null == jX509Cert) { logger.info("Failed to parse cert. " + samlCert); return ""; } PublicKey publicCert = jX509Cert.getPublicKey(); logger.info("Extracted cert. Cert:" + publicCert); X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicCert.getEncoded()); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = keyFactory.generatePublic(publicKeySpec); logger.debug("Key created by provider: " + keyFactory.getProvider().toString()); // Setup validation BasicX509Credential publicCredential = new BasicX509Credential(); publicCredential.setPublicKey(publicKey); SignatureValidator signatureValidator = new SignatureValidator(publicCredential); Signature signature = response.getSignature(); // Validate try { signatureValidator.validate(signature); logger.info("Assertion signature validated."); } catch (ValidationException e) { logger.error("Failed to validate signature of assertion", e); throw e; } // Get decryption key RSAPrivateKey privateKey = null; BasicX509Credential decryptionCredential = new BasicX509Credential(); decryptionCredential.setPrivateKey(privateKey); StaticKeyInfoCredentialResolver skicr = new StaticKeyInfoCredentialResolver(decryptionCredential); // Decrypt assertion Decrypter decrypter = new Decrypter(null, skicr, new InlineEncryptedKeyResolver()); if (response.getEncryptedAssertions().isEmpty()) { logger.info("Nothing to decrypt in assertion."); } else { Assertion decryptedAssertion; try { decryptedAssertion = decrypter.decrypt(response.getEncryptedAssertions().get(0)); logger.info("Assertion decryption succeeded."); } catch (DecryptionException e) { logger.error("Failed to decrypt assertion", e); throw e; } // Extract attributes, log in output List<AttributeStatement> attributeStatements = decryptedAssertion.getAttributeStatements(); for (int i = 0; i < attributeStatements.size(); i++) { List<Attribute> attributes = attributeStatements.get(i).getAttributes(); for (int x = 0; x < attributes.size(); x++) { String strAttributeName = attributes.get(x).getDOM().getAttribute("Name"); List<XMLObject> attributeValues = attributes.get(x).getAttributeValues(); for (int y = 0; y < attributeValues.size(); y++) { String strAttributeValue = attributeValues.get(y).getDOM().getTextContent(); logger.info(strAttributeName + " = " + strAttributeValue); } } } } } catch (Exception ex) { logger.error("Failed to validate assertion", ex); throw ex; } return decodedString; }
From source file:com.mytalentfolio.h_daforum.CconnectToServer.java
/** * Creates a new instance of {@code PublicKey}. Convert the string formatted * public key into {@code PublicKey} type. * //from w w w . j a va2 s . c o m * @param key * the string formated public key. * @return the new {@code PublicKey} instance. * @throws NoSuchAlgorithmException * if no provider provides the requested algorithm. * @throws InvalidKeyException * if the specified keySpec is invalid. * */ // Converting the Server Public key format to Java compatible from private PublicKey getServerPublicKey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException { // Converting the Server Public key format to Java compatible from key = key.replace("-----BEGIN PUBLIC KEY-----\n", ""); key = key.replace("\n-----END PUBLIC KEY-----", ""); // Creating the public key from the string format received from server KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey serverPublicKeySig = keyFactory .generatePublic(new X509EncodedKeySpec(Base64.decode(key.toString(), Base64.DEFAULT))); return serverPublicKeySig; }
From source file:my.adam.smo.common.AsymmetricEncryptionBox.java
@PostConstruct public void init() throws NoSuchAlgorithmException { keyGen = KeyPairGenerator.getInstance("RSA"); try {//from ww w .ja v a 2s . c om PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(Base64.decode(this.privKeyS)); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); prvKey = keyFactory.generatePrivate(privKeySpec); } catch (InvalidKeySpecException e) { logger.error("invalid private key", e); } try { X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(Base64.decode(this.pubKeyS)); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); pubKey = keyFactory.generatePublic(pubKeySpec); } catch (InvalidKeySpecException e) { logger.error("invalid public key", e); } }
From source file:controlador.ControlEmpleados.java
/** * Solicita al server la SecretKey para cifrar/descifrar el resto de la comunicacin. Primero, hace una * peticin http de cuya respuesta abre un InputStream y almacena el stream de bytes en un fichero binario. * Este fichero es la clave pblica del servidor y se utilizar para descifrar asimtricamente la segunda * peticin, la cual contiene un objeto SecretKey que ser el utilizado para cifrar/descifrar de manera simtrica. *///from ww w.j a v a 2 s. c om public void solicitarClave() { CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpGet httpGet = new HttpGet(Configuration.getInstance().getServerUrl() + "/secretKey?opcion=public"); CloseableHttpResponse response1 = httpclient.execute(httpGet, SessionContext.getInstance().getContext()); try { HttpEntity entity1 = response1.getEntity(); File f = new File("./server1024.publica"); if (f.exists()) { f.delete(); } IOUtils.copy(entity1.getContent(), new FileOutputStream(f)); } finally { response1.close(); } httpGet = new HttpGet(Configuration.getInstance().getServerUrl() + "/secretKey?opcion=secret"); response1 = httpclient.execute(httpGet, SessionContext.getInstance().getContext()); try { HttpEntity entity1 = response1.getEntity(); String respuesta = EntityUtils.toString(entity1); byte[] clave = Base64.decodeBase64(respuesta); //descifro byte[] bufferPub = new byte[5000]; File f = new File("server1024.publica"); System.out.println(f.getAbsolutePath()); FileInputStream in = new FileInputStream(f); int chars = in.read(bufferPub, 0, 5000); in.close(); byte[] bufferPub2 = new byte[chars]; System.arraycopy(bufferPub, 0, bufferPub2, 0, chars); Security.addProvider(new BouncyCastleProvider()); // Cargar el provider BC Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); Cipher cifrador = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC"); KeyFactory keyFactoryRSA = KeyFactory.getInstance("RSA", "BC"); // Hace uso del provider BC // 4.2 Recuperar clave publica desde datos codificados en formato X509 X509EncodedKeySpec clavePublicaSpec = new X509EncodedKeySpec(bufferPub2); PublicKey clavePublica2 = keyFactoryRSA.generatePublic(clavePublicaSpec); cifrador.init(Cipher.DECRYPT_MODE, clavePublica2); // Descrifra con la clave privada byte[] claveAES = cifrador.doFinal(clave); SecretKey originalKey = new SecretKeySpec(claveAES, 0, claveAES.length, "AES"); SessionContext.getInstance().setSecretKey(originalKey); } finally { response1.close(); } } catch (IOException ex) { Logger.getLogger(ControlEmpleados.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(ControlEmpleados.class.getName()).log(Level.SEVERE, null, ex); } finally { try { httpclient.close(); } catch (IOException ex) { Logger.getLogger(ControlEmpleados.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:com.mycompany.bankinterface.crypto.Signer.java
public boolean isVerified(String clearText, String signature, String signerPublicKey) throws SignerException { boolean isVerified = false; byte[] signerPublicKeyBytes = Base64.decodeBase64(signerPublicKey); byte[] signatureAsBytes = Base64.decodeBase64(signature); X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(signerPublicKeyBytes); KeyFactory keyFactory; try {//from w ww . j a va 2 s .c o m keyFactory = KeyFactory.getInstance(PUBLIC_KEY_ALGORITHM, PROVIDER); } catch (NoSuchAlgorithmException | NoSuchProviderException ex) { throw new SignerException("Failed to create key factory", ex); } PublicKey pubKey; try { pubKey = keyFactory.generatePublic(pubKeySpec); } catch (InvalidKeySpecException ex) { throw new SignerException("Failed to create public key", ex); } Signature dsa; try { dsa = Signature.getInstance(SIGNER_ALGORITHM, PROVIDER); } catch (NoSuchAlgorithmException | NoSuchProviderException ex) { throw new SignerException("Could not get signing instance", ex); } try { dsa.initVerify(pubKey); dsa.update(clearText.getBytes()); isVerified = dsa.verify(signatureAsBytes); } catch (InvalidKeyException | SignatureException ex) { throw new SignerException("Could not verify data", ex); } return isVerified; }
From source file:net.arccotangent.pacchat.net.ConnectionHandler.java
public void run() { try {// ww w . ja va2 s . co m String line1 = input.readLine(); switch (line1) { case "101 ping": ch_log.i("Client pinged us, responding with an acknowledgement."); output.write("102 pong"); output.newLine(); output.flush(); output.close(); break; case "302 request key update": ch_log.i("Client is requesting a key update."); KeyUpdate update = new KeyUpdate(ip); KeyUpdateManager.addPendingUpdate(connection_id, update); while (KeyUpdateManager.getUpdate(connection_id).isProcessed()) { try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } boolean accepted = KeyUpdateManager.getUpdate(connection_id).isAccepted(); KeyUpdateManager.completeIncomingUpdate(connection_id, KeyUpdateManager.getUpdate(connection_id)); if (accepted) { ch_log.i("Accepting key update"); try { output.write("303 update"); output.newLine(); output.flush(); String pubkeyB64 = input.readLine(); byte[] pubEncoded = Base64.decodeBase64(pubkeyB64); X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubEncoded); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); output.close(); input.close(); KeyManager.saveKeyByIP(ip, keyFactory.generatePublic(pubSpec)); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { ch_log.e("Error updating sender's key!"); e.printStackTrace(); } } else { ch_log.i("Rejecting key update."); output.write("304 no update"); output.newLine(); output.flush(); output.close(); } break; case "301 getkey": ch_log.i("Client requested our public key, sending."); String pubkeyB64 = Base64.encodeBase64String(Main.getKeypair().getPublic().getEncoded()); output.write(pubkeyB64); output.newLine(); output.flush(); output.close(); break; case "200 encrypted message": //incoming encrypted message ch_log.i("Client sent an encrypted message, attempting verification and decryption."); PrivateKey privkey = Main.getKeypair().getPrivate(); String cryptedMsg = input.readLine() + "\n" + input.readLine() + "\n" + input.readLine(); ch_log.i("Checking for sender's public key."); if (KeyManager.checkIfIPKeyExists(ip)) { ch_log.i("Public key found."); } else { ch_log.i("Public key not found, requesting key from their server."); try { Socket socketGetkey = new Socket(); socketGetkey.connect(new InetSocketAddress(InetAddress.getByName(ip), Server.PORT), 1000); BufferedReader inputGetkey = new BufferedReader( new InputStreamReader(socketGetkey.getInputStream())); BufferedWriter outputGetkey = new BufferedWriter( new OutputStreamWriter(socketGetkey.getOutputStream())); outputGetkey.write("301 getkey"); outputGetkey.newLine(); outputGetkey.flush(); String sender_pubkeyB64 = inputGetkey.readLine(); byte[] pubEncoded = Base64.decodeBase64(sender_pubkeyB64); X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubEncoded); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); outputGetkey.close(); inputGetkey.close(); KeyManager.saveKeyByIP(ip, keyFactory.generatePublic(pubSpec)); } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) { ch_log.e("Error saving sender's key!"); e.printStackTrace(); } } PacchatMessage message = MsgCrypto.decryptAndVerifyMessage(cryptedMsg, privkey, KeyManager.loadKeyByIP(ip)); String msg = message.getMessage(); boolean verified = message.isVerified(); boolean decrypted = message.isDecryptedSuccessfully(); String ANSI_RESET = "\u001B[0m"; String ANSI_CYAN = "\u001B[36m"; String ANSI_BOLD = "\u001B[1m"; if (verified && decrypted) { ch_log.i("Acknowledging message."); output.write("201 message acknowledgement"); output.newLine(); output.flush(); output.close(); System.out.println(ANSI_BOLD + ANSI_CYAN + "-----BEGIN MESSAGE-----" + ANSI_RESET); System.out.println(ANSI_BOLD + ANSI_CYAN + msg + ANSI_RESET); System.out.println(ANSI_BOLD + ANSI_CYAN + "-----END MESSAGE-----" + ANSI_RESET); } else if (!verified && decrypted) { ch_log.w("Notifying client that message authenticity was not verified."); output.write("203 unable to verify"); output.newLine(); output.flush(); output.close(); System.out.println(ANSI_BOLD + ANSI_CYAN + "-----BEGIN MESSAGE-----" + ANSI_RESET); System.out.println(ANSI_BOLD + ANSI_CYAN + msg + ANSI_RESET); System.out.println(ANSI_BOLD + ANSI_CYAN + "-----END MESSAGE-----" + ANSI_RESET); } else if (!verified) { ch_log.w("Notifying client that message could not be decrypted."); output.write("202 unable to decrypt"); output.newLine(); output.flush(); output.close(); } break; case "201 message acknowledgement": ch_log.i("Client sent an invalid message acknowledgement."); output.write("400 invalid transmission header"); output.newLine(); output.flush(); output.close(); case "202 unable to decrypt": ch_log.i("Client sent an invalid 'unable to decrypt' transmission."); output.write("400 invalid transmission header"); output.newLine(); output.flush(); output.close(); case "203 unable to verify": ch_log.i("Client sent an invalid 'unable to verify' transmission."); output.write("400 invalid transmission header"); output.newLine(); output.flush(); output.close(); default: ch_log.i("Client sent an invalid request header: " + line1); output.write("400 invalid transmission header"); output.newLine(); output.flush(); output.close(); break; } } catch (IOException e) { ch_log.e("Error in connection handler " + connection_id); e.printStackTrace(); } }
From source file:com.wso2telco.proxy.entity.ServerInitiatedServiceEndpoints.java
private RSAPublicKey loadPublicKey(String publicKeyContent) throws GeneralSecurityException { KeyFactory kf = KeyFactory.getInstance("RSA"); X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyContent)); return (RSAPublicKey) kf.generatePublic(pubSpec); }