List of usage examples for java.security.spec X509EncodedKeySpec X509EncodedKeySpec
public X509EncodedKeySpec(byte[] encodedKey)
From source file:it.scoppelletti.programmerpower.security.spi.EncodedKeyFactory.java
@Override protected KeySpec getKeySpec(String alg, KeyRep.Type keyType, Properties props, String prefix) { String name, value;//from w w w. j av a2 s .c o m byte[] data; KeySpec keySpec; name = Strings.concat(prefix, EncodedKeyFactory.PROP_DATA); value = props.getProperty(name); if (Strings.isNullOrEmpty(value)) { throw new ArgumentNullException(name); } data = Base64.decodeBase64(value); switch (keyType) { case PUBLIC: keySpec = new X509EncodedKeySpec(data); break; case PRIVATE: keySpec = new PKCS8EncodedKeySpec(data); break; default: throw new EnumConstantNotPresentException(KeyRep.Type.class, keyType.toString()); } return keySpec; }
From source file:im.whistle.crypt.Crypt.java
/** * Encrypts a message.//from w ww.ja v a2 s .com * @param args Arguments: data, publicKey[, privateKey] * @param callback Callback */ public static void encrypt(JSONArray args, AsyncCallback<JSONArray> callback) { try { PRNGProvider.init(); // Ensure OpenSSL fix // Get the arguments String data = args.getString(0); String pub = args.getString(1); String priv = null; if (args.length() == 3) { priv = args.getString(2); } String sig = null; // Convert everything into byte arrays byte[] dataRaw = data.getBytes("utf-8"); byte[] pubRaw = Base64.decode(stripKey(pub), Base64.DEFAULT); // Generate random AES key and IV byte[] aesKey = new byte[AES_BYTES]; new SecureRandom().nextBytes(aesKey); byte[] aesIv = new byte[16]; // Block size new SecureRandom().nextBytes(aesIv); Cipher c = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC"); c.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(aesKey, "AES"), new IvParameterSpec(aesIv)); // Encrypt data with AES byte[] encData = c.doFinal(dataRaw); // Encrypt aes data with RSA X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubRaw); KeyFactory kf = KeyFactory.getInstance("RSA", "BC"); c = Cipher.getInstance("RSA/None/OAEPWithSHA-1AndMGF1Padding", "BC"); c.init(Cipher.ENCRYPT_MODE, kf.generatePublic(publicKeySpec)); c.update(aesKey); c.update(aesIv); byte[] encKey = c.doFinal(); // Concatenate and transform byte[] encRaw = new byte[encKey.length + encData.length]; System.arraycopy(encKey, 0, encRaw, 0, encKey.length); System.arraycopy(encData, 0, encRaw, encKey.length, encData.length); encKey = null; encData = null; String enc = new String(Base64.encode(encRaw /* needed for sign */, Base64.NO_WRAP), "utf-8"); // Sign if (priv != null) { // Fail on error (no try-catch) byte[] privRaw = Base64.decode(stripKey(priv), Base64.DEFAULT); PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privRaw); Signature s = Signature.getInstance("SHA1withRSA", "BC"); s.initSign(kf.generatePrivate(privateKeySpec)); s.update(encRaw); sig = new String(Base64.encode(s.sign(), Base64.NO_WRAP), "utf-8"); } JSONArray res = new JSONArray(); res.put(enc); res.put(sig); callback.success(res); } catch (Exception ex) { Log.w("whistle", "Encrypt error: " + ex.getMessage(), ex); callback.error(ex); } }
From source file:org.limewire.activation.impl.ActivationCommunicatorImpl.java
private String getEncryptedToken(String licenseId, String randomNumber) throws IOException { // get public key from string byte[] cipherData; byte[] keyBytes = Base64.decodeBase64(activationSettings.getServerKey().getBytes()); try {// ww w . j ava 2 s . c o m KeyFactory fac = KeyFactory.getInstance(ENCRYPTION_ALGORITHM); PublicKey publicKey = fac.generatePublic(new X509EncodedKeySpec(keyBytes)); byte[] messageToEcrypt = StringUtils.toUTF8Bytes(licenseId + "," + randomNumber); cipherData = cipherProvider.encrypt(messageToEcrypt, publicKey, CIPHER_TYPE); } catch (GeneralSecurityException e) { throw IOUtils.getIOException("Security exception while initializing key", e); } String noEncoding = new String(Base64.encodeBase64(cipherData)); return EncodingUtils.encode(noEncoding); }
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 w w w .java 2 s . co m 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.zxy.commons.codec.rsa.AbstractRSAUtils.java
/** * /*from w ww . j a va2s . c o m*/ * * * @param info ? * @return ? * @throws GeneralSecurityException GeneralSecurityException */ public String encode(String info) throws GeneralSecurityException { // ?token? byte[] pubKeyText = this.getPubKeyText(); X509EncodedKeySpec bobPKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(pubKeyText)); KeyFactory keyFactory = null; if (provider == null) { keyFactory = KeyFactory.getInstance(ALGORITHM); } else { keyFactory = KeyFactory.getInstance(ALGORITHM, provider); } // ? PublicKey pubkey = keyFactory.generatePublic(bobPKeySpec); // CipherECB?PKCS5Padding Cipher cipher = null; if (provider == null) { cipher = Cipher.getInstance(ALGORITHM); } else { cipher = Cipher.getInstance(ALGORITHM, provider); } // ? cipher.init(Cipher.ENCRYPT_MODE, pubkey); byte[] cipherText = cipher.doFinal(info.getBytes()); return new String(Base64.encodeBase64(cipherText)); }
From source file:enc_mods.aes.java
/** * Encrypts the AES key to a file using an RSA public key *//*from ww w . java2s .c om*/ public void saveKey(File out, File publicKeyFile) { try { // read public key to be used to encrypt the AES key byte[] encodedKey = new byte[(int) publicKeyFile.length()]; new FileInputStream(publicKeyFile).read(encodedKey); // create public key X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedKey); KeyFactory kf = KeyFactory.getInstance("RSA"); PublicKey pk = kf.generatePublic(publicKeySpec); // write AES key cipher.init(Cipher.ENCRYPT_MODE, pk); CipherOutputStream os = new CipherOutputStream(new FileOutputStream(out), cipher); os.write(key); os.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.emc.vipr.services.s3.S3ClientFactory.java
/** * Creates an EncryptionClient for testing. Loads the public and private keys from * the properties file (not suitable for production). * * @return/*from ww w . ja v a2s .co m*/ * @throws IOException */ public static AmazonS3EncryptionClient getEncryptionClient() throws IOException { try { Properties props = ViprConfig.getProperties(); String accessKey = ViprConfig.getPropertyNotEmpty(props, ViprConfig.PROP_S3_ACCESS_KEY_ID); String secretKey = ViprConfig.getPropertyNotEmpty(props, ViprConfig.PROP_S3_SECRET_KEY); String endpoint = ViprConfig.getPropertyNotEmpty(props, ViprConfig.PROP_S3_ENDPOINT); String publicKey = ViprConfig.getPropertyNotEmpty(props, ViprConfig.PROP_PUBLIC_KEY); String privateKey = ViprConfig.getPropertyNotEmpty(props, ViprConfig.PROP_PRIVATE_KEY); byte[] pubKeyBytes = Base64.decodeBase64(publicKey.getBytes("US-ASCII")); byte[] privKeyBytes = Base64.decodeBase64(privateKey.getBytes("US-ASCII")); X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubKeyBytes); PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(privKeyBytes); PublicKey pubKey; PrivateKey privKey; try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); pubKey = keyFactory.generatePublic(pubKeySpec); privKey = keyFactory.generatePrivate(privKeySpec); } catch (GeneralSecurityException e) { throw new RuntimeException("Could not load key pair: " + e, e); } EncryptionMaterials keys = new EncryptionMaterials(new KeyPair(pubKey, privKey)); BasicAWSCredentials creds = new BasicAWSCredentials(accessKey, secretKey); AmazonS3EncryptionClient client = new AmazonS3EncryptionClient(creds, keys); client.setEndpoint(endpoint); checkProxyConfig(client, props); return client; } catch (Exception e) { log.info("Could not load configuration: " + e); return null; } }
From source file:com.cws.esolutions.security.dao.keymgmt.impl.FileKeyManager.java
/** * @see com.cws.esolutions.security.dao.keymgmt.interfaces.KeyManager#returnKeys(java.lang.String) *//*from w ww . j a va 2s . c o m*/ public synchronized KeyPair returnKeys(final String guid) throws KeyManagementException { final String methodName = FileKeyManager.CNAME + "#returnKeys(final String guid) throws KeyManagementException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", guid); } KeyPair keyPair = null; InputStream pubStream = null; InputStream privStream = null; final File keyDirectory = FileUtils.getFile(keyConfig.getKeyDirectory() + "/" + guid); try { if (!(keyDirectory.exists())) { throw new KeyManagementException("Configured key directory does not exist and unable to create it"); } File publicFile = FileUtils .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PUBLICKEY_FILE_EXT); File privateFile = FileUtils .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PRIVATEKEY_FILE_EXT); if ((publicFile.exists()) && (privateFile.exists())) { privStream = new FileInputStream(privateFile); byte[] privKeyBytes = IOUtils.toByteArray(privStream); pubStream = new FileInputStream(publicFile); byte[] pubKeyBytes = IOUtils.toByteArray(pubStream); // files exist KeyFactory keyFactory = KeyFactory.getInstance(keyConfig.getKeyAlgorithm()); // generate private key PKCS8EncodedKeySpec privateSpec = new PKCS8EncodedKeySpec(privKeyBytes); PrivateKey privKey = keyFactory.generatePrivate(privateSpec); // generate pubkey X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(pubKeyBytes); PublicKey pubKey = keyFactory.generatePublic(publicSpec); // make the keypair keyPair = new KeyPair(pubKey, privKey); } else { // files dont exist throw new KeyManagementException("Failed to locate user keys"); } } catch (FileNotFoundException fnfx) { throw new KeyManagementException(fnfx.getMessage(), fnfx); } catch (InvalidKeySpecException iksx) { throw new KeyManagementException(iksx.getMessage(), iksx); } catch (IOException iox) { throw new KeyManagementException(iox.getMessage(), iox); } catch (NoSuchAlgorithmException nsax) { throw new KeyManagementException(nsax.getMessage(), nsax); } finally { if (privStream != null) { IOUtils.closeQuietly(privStream); } if (pubStream != null) { IOUtils.closeQuietly(pubStream); } } return keyPair; }
From source file:tkbautobooking.TKBAutoBooking.java
private boolean checkPermission(String userId, String rsaData) { try {//from w ww. ja va 2 s .c o m KeyFactory kf = KeyFactory.getInstance("RSA"); PublicKey publicKey = kf .generatePublic(new X509EncodedKeySpec(Hex.decodeHex(RSA_PUBLIC_KEY.toCharArray()))); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, publicKey); byte[] decodeBytes = cipher.doFinal(Hex.decodeHex(rsaData.toCharArray())); String decodeString = new String(decodeBytes); return userId.equals(decodeString); } catch (NoSuchAlgorithmException | DecoderException | InvalidKeySpecException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex) { return false; } }
From source file:com.sharky.Security.java
public static PublicKey generatePublicKey(String encodedPublicKey) { try {//from ww w.ja va2 s. c om byte[] decodedKey = Base64.decode(encodedPublicKey); KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM); return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey)); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (InvalidKeySpecException e) { throw new IllegalArgumentException(e); } catch (Base64DecoderException e) { throw new IllegalArgumentException(e); } }