List of usage examples for javax.crypto SecretKey getEncoded
public byte[] getEncoded();
From source file:org.structr.util.StructrLicenseManager.java
private boolean checkVolumeLicense(final Map<String, String> properties, final String serversString) { try {//from www . j av a 2 s . c o m final KeyGenerator kgen = KeyGenerator.getInstance("AES"); final byte[] data = write(properties).getBytes("utf-8"); final String name = properties.get(NameKey); final byte[] expected = name.getBytes("utf-8"); kgen.init(128); for (final String part : serversString.split("[, ]+")) { final String address = part.trim(); if (StringUtils.isNotBlank(address)) { try { logger.info("Trying to verify volume license with server {}", address); final long t0 = System.currentTimeMillis(); final SecretKey aesKey = kgen.generateKey(); // symmetric stream key final byte[] ivspec = RandomUtils.nextBytes(16); // initialization vector for stream cipher final byte[] key = encryptSessionKey(aesKey.getEncoded()); final byte[] encryptedIV = encryptSessionKey(ivspec); final byte[] encryptedData = encryptData(data, aesKey, ivspec); final byte[] response = sendAndReceive(address, key, encryptedIV, encryptedData); final boolean result = verify(expected, response); if (result == true) { logger.info("License verified in {} ms", System.currentTimeMillis() - t0); } return result; } catch (Throwable t) { logger.warn("Unable to verify volume license: {}", t.getMessage()); } } } } catch (Throwable t) { t.printStackTrace(); } return false; }
From source file:com.skplanet.syruppay.token.SyrupPayTokenBuilderTest.java
_ERROR() throws Exception { final String keyFactorySalt = "65594821073030071593"; Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE"); SecretKeySpec secretKeySpec;/* ww w. j a v a 2s. c om*/ try { KeySpec spec = new PBEKeySpec("7244798e1fab1a9175f752a8a7e12beafe2cd27b208f9f2f7ab43173358153fc5eae2499afa66f7386d74cb8cf4765133c513ae2e6acd521acde4f80d747".toCharArray(), keyFactorySalt.getBytes(), 1, 256); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); SecretKey secretKey = secretKeyFactory.generateSecret(spec); secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), "AES"); } catch (Exception e) { throw e; } cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(new byte[cipher.getBlockSize()])); System.out.println(new String(cipher.doFinal(Base64.decodeBase64("yMvtcFwlhwBg22GF-biF4A".getBytes())), "UTF-8")); }
From source file:test.integ.be.fedict.commons.eid.client.JCATest.java
@Test public void testSoftwareRSAKeyWrapping() throws Exception { final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); final KeyPair keyPair = keyPairGenerator.generateKeyPair(); final KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); final SecretKey secretKey = keyGenerator.generateKey(); LOG.debug("secret key algo: " + secretKey.getAlgorithm()); final Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.WRAP_MODE, keyPair.getPublic()); LOG.debug("cipher security provider: " + cipher.getProvider().getName()); LOG.debug("cipher type: " + cipher.getClass().getName()); final byte[] wrappedKey = cipher.wrap(secretKey); cipher.init(Cipher.UNWRAP_MODE, keyPair.getPrivate()); final Key resultKey = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY); assertArrayEquals(secretKey.getEncoded(), resultKey.getEncoded()); }
From source file:org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore.java
public Credentials getCredentialsFromAppAttempt(RMAppAttempt appAttempt) { Credentials credentials = new Credentials(); SecretKey clientTokenMasterKey = appAttempt.getClientTokenMasterKey(); if (clientTokenMasterKey != null) { credentials.addSecretKey(AM_CLIENT_TOKEN_MASTER_KEY_NAME, clientTokenMasterKey.getEncoded()); }//from w w w. ja va 2 s . c om return credentials; }
From source file:Crypto.java
/** * this must be called after creating the initial Crypto object. It creates a salt of SALT_LEN bytes * and generates the salt bytes using secureRandom(). The encryption secret key is created * along with the initialization vectory. The member variable mEcipher is created to be used * by the class later on when either creating a CipherOutputStream, or encrypting a buffer * to be written to disk.// ww w . j a v a2 s .co m * * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws NoSuchPaddingException * @throws InvalidParameterSpecException * @throws IllegalBlockSizeException * @throws BadPaddingException * @throws UnsupportedEncodingException * @throws InvalidKeyException */ public void setupEncrypt() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, InvalidKeyException { SecretKeyFactory factory = null; SecretKey tmp = null; // crate secureRandom salt and store as member var for later use mSalt = new byte[SALT_LEN]; SecureRandom rnd = new SecureRandom(); rnd.nextBytes(mSalt); Db("generated salt :" + Hex.encodeHexString(mSalt)); factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); /* Derive the key, given password and salt. * * in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security" * The end user must also install them (not compiled in) so beware. * see here: http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml */ KeySpec spec = new PBEKeySpec(mPassword.toCharArray(), mSalt, ITERATIONS, KEYLEN_BITS); tmp = factory.generateSecret(spec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); /* Create the Encryption cipher object and store as a member variable */ mEcipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); mEcipher.init(Cipher.ENCRYPT_MODE, secret); AlgorithmParameters params = mEcipher.getParameters(); // get the initialization vectory and store as member var mInitVec = params.getParameterSpec(IvParameterSpec.class).getIV(); Db("mInitVec is :" + Hex.encodeHexString(mInitVec)); }
From source file:com.filelocker.encryption.AES_Encryption.java
/** * this must be called after creating the initial Crypto object. It creates a salt of SALT_LEN bytes * and generates the salt bytes using secureRandom(). The encryption secret key is created * along with the initialization vectory. The member variable vEcipher is created to be used * by the class later on when either creating a CipherOutputStream, or encrypting a buffer * to be written to disk.// ww w .jav a 2s.co m * * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws NoSuchPaddingException * @throws InvalidParameterSpecException * @throws IllegalBlockSizeException * @throws BadPaddingException * @throws UnsupportedEncodingException * @throws InvalidKeyException */ public void setupEncrypt() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, InvalidKeyException { SecretKeyFactory factory = null; SecretKey tmp = null; // crate secureRandom salt and store as member var for later use vSalt = new byte[SALT_LEN]; SecureRandom rnd = new SecureRandom(); rnd.nextBytes(vSalt); Db("generated salt :" + Hex.encodeHexString(vSalt)); factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); /* Derive the key, given password and salt. * * in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security" * The end user must also install them (not compiled in) so beware. * see here: http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml */ KeySpec spec = new PBEKeySpec(vPassword.toCharArray(), vSalt, ITERATIONS, KEYLEN_BITS); tmp = factory.generateSecret(spec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); /* Create the Encryption cipher object and store as a member variable */ vEcipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); vEcipher.init(Cipher.ENCRYPT_MODE, secret); AlgorithmParameters params = vEcipher.getParameters(); // get the initialization vectory and store as member var vInitVec = params.getParameterSpec(IvParameterSpec.class).getIV(); Db("vInitVec is :" + Hex.encodeHexString(vInitVec)); }
From source file:ropes.Crypto.java
/** * this must be called after creating the initial Crypto object. It creates a salt of SALT_LEN bytes * and generates the salt bytes using secureRandom(). The encryption secret key is created * along with the initialization vectory. The member variable mEcipher is created to be used * by the class later on when either creating a CipherOutputStream, or encrypting a buffer * to be written to disk./*from w w w . j ava 2 s . com*/ * * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws NoSuchPaddingException * @throws InvalidParameterSpecException * @throws IllegalBlockSizeException * @throws BadPaddingException * @throws UnsupportedEncodingException * @throws InvalidKeyException */ public void setupEncrypt() { try { SecretKeyFactory factory = null; SecretKey tmp = null; // crate secureRandom salt and store as member var for later use mSalt = new byte[SALT_LEN]; SecureRandom rnd = new SecureRandom(); rnd.nextBytes(mSalt); Db("generated salt :" + Hex.encodeHexString(mSalt)); factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); /* Derive the key, given password and salt. * * in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security" * The end user must also install them (not compiled in) so beware. * see here: http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml */ KeySpec spec = new PBEKeySpec(mPassword.toCharArray(), mSalt, ITERATIONS, KEYLEN_BITS); tmp = factory.generateSecret(spec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); /* Create the Encryption cipher object and store as a member variable */ mEcipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); mEcipher.init(Cipher.ENCRYPT_MODE, secret); AlgorithmParameters params = mEcipher.getParameters(); // get the initialization vectory and store as member var mInitVec = params.getParameterSpec(IvParameterSpec.class).getIV(); Db("mInitVec is :" + Hex.encodeHexString(mInitVec)); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidKeySpecException ex) { Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchPaddingException ex) { Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidKeyException ex) { Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidParameterSpecException ex) { Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:Crypto.java
/** * If a file is being decrypted, we need to know the pasword, the salt and the initialization vector (iv). * We have the password from initializing the class. pass the iv and salt here which is * obtained when encrypting the file initially. * /* w w w . j a v a 2 s .com*/ * @param initvec * @param salt * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws NoSuchPaddingException * @throws InvalidKeyException * @throws InvalidAlgorithmParameterException * @throws DecoderException */ public void setupDecrypt(String initvec, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, DecoderException { SecretKeyFactory factory = null; SecretKey tmp = null; SecretKey secret = null; // since we pass it as a string of input, convert to a actual byte buffer here mSalt = Hex.decodeHex(salt.toCharArray()); Db("got salt " + Hex.encodeHexString(mSalt)); // get initialization vector from passed string mInitVec = Hex.decodeHex(initvec.toCharArray()); Db("got initvector :" + Hex.encodeHexString(mInitVec)); /* Derive the key, given password and salt. */ // in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security" // The end user must also install them (not compiled in) so beware. // see here: // http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); KeySpec spec = new PBEKeySpec(mPassword.toCharArray(), mSalt, ITERATIONS, KEYLEN_BITS); tmp = factory.generateSecret(spec); secret = new SecretKeySpec(tmp.getEncoded(), "AES"); /* Decrypt the message, given derived key and initialization vector. */ mDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); mDecipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(mInitVec)); }
From source file:org.poweredrails.rails.net.handler.login.LoginPacketHandler.java
/** * Handles an encrypt response packet.// w w w. ja va 2s . co m * @param packet encrypt response packet */ public void onEncryptResponse(PacketReceiveEncryptResponse packet) { this.logger.info("Received a PacketReceiveEncryptResponse from a User."); final Session sender = packet.getSender(); Cipher cipher = null; try { cipher = Cipher.getInstance("RSA"); } catch (Exception e) { throw new RuntimeException("Failed to get an instance of a RSA cipher!", e); } SecretKey sharedSecret = null; try { cipher.init(Cipher.DECRYPT_MODE, this.privateKey); sharedSecret = new SecretKeySpec(cipher.doFinal(packet.getSharedSecret()), "AES"); } catch (Exception e) { // TODO: More accurately defined exception. throw new RuntimeException("...", e); } byte[] verifyToken = null; try { cipher.init(Cipher.DECRYPT_MODE, this.privateKey); verifyToken = cipher.doFinal(packet.getVerifyToken()); } catch (Exception e) { // TODO: More accurately defined exception. throw new RuntimeException("...", e); } if (!Arrays.equals(verifyToken, sender.getVerifyToken())) { // TODO: Disconnect user instead! throw new RuntimeException("Invalid verify token!"); } // session.enableEncryption(sharedSecret); String hash; try { final MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(sender.getSessionId().getBytes()); digest.update(sharedSecret.getEncoded()); digest.update(this.publicKey); hash = new BigInteger(digest.digest()).toString(16); } catch (Exception e) { throw new RuntimeException("Failed to generate SHA-1 digest!", e); } new Thread(() -> { final String baseUrl = "https://sessionserver.mojang.com/session/minecraft/hasJoined?username=%s&serverId=%s"; URLConnection connection = null; try { connection = new URL(String.format(baseUrl, sender.getVerifyUsername(), hash)).openConnection(); } catch (IOException e) { throw new RuntimeException("Failed to open a connection to Mojang!", e); } JSONObject response = null; try { final InputStream in = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); StringBuilder builder = new StringBuilder(); String line = null; while ((line = br.readLine()) != null) { builder.append(line).append('\n'); } response = new JSONObject(builder.toString()); } catch (Exception e) { // TODO: Disconnect user instead! throw new RuntimeException("Failed to verify username!", e); } String name = null; String id = null; try { name = response.getString("name"); id = response.getString("id"); } catch (JSONException e) { throw new RuntimeException("Failed to parse Mojang JSON response!", e); } UUID uuid = UUIDUtil.fromFlatString(id); // TODO: Player Properties // TODO: Create new Profile // TODO: Dispatch PlayerLoginEvent this.logger.info("Successfully authenticated Player [" + name + ", " + uuid + "]."); }).start(); }
From source file:com.denel.facepatrol.MainActivity.java
private void decryptfile(Context mcontext, SecretKey key) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { File infile = mcontext.getDatabasePath(dbname_en); InputStream fis = new FileInputStream(infile); File outfile = mcontext.getDatabasePath(dbname); // parent directory for his file if it doesn't exist, // in this case it returns a false. outfile.getParentFile().mkdirs();// www .ja v a 2s. c om // This stream write the decrypted text. This stream will be wrapped by another stream. FileOutputStream fos = new FileOutputStream(outfile); // Length is 16 byte // Careful when taking user input!!! // http://stackoverflow.com/a/3452620/1188357 SecretKeySpec sks = new SecretKeySpec(key.getEncoded(), "AES"); // Create cipher Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, sks); // Wrap the output stream CipherOutputStream cos = new CipherOutputStream(fos, cipher); // Write bytes int b; byte[] d = new byte[8]; while ((b = fis.read(d)) != -1) { cos.write(d, 0, b); } // Flush and close streams. cos.flush(); cos.close(); fis.close(); // delete the encrypted file if (infile.exists()) { infile.delete(); } }