List of usage examples for javax.crypto SecretKey getEncoded
public byte[] getEncoded();
From source file:org.cryptonode.jncryptor.AES256v2Cryptor.java
@Override public SecretKey keyForPassword(char[] password, byte[] salt) throws CryptorException { Validate.notNull(salt, "Salt value cannot be null."); Validate.isTrue(salt.length == SALT_LENGTH, "Salt value must be %d bytes.", SALT_LENGTH); try {/*w w w . j a v a 2 s . co m*/ SecretKeyFactory factory = SecretKeyFactory.getInstance(KEY_DERIVATION_ALGORITHM); SecretKey tmp = factory .generateSecret(new PBEKeySpec(password, salt, PBKDF_ITERATIONS, AES_256_KEY_SIZE * 8)); return new SecretKeySpec(tmp.getEncoded(), AES_NAME); } catch (GeneralSecurityException e) { throw new CryptorException( String.format("Failed to generate key from password using %s.", KEY_DERIVATION_ALGORITHM), e); } }
From source file:org.sonatype.sisu.encryptor.RsaAesEncryptor.java
public void encrypt(InputStream plainInput, OutputStream encryptedOutput, PublicKey key) throws IOException, GeneralSecurityException { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(KEY_SIZE);//www. j ava 2s.c om SecretKey aesKey = kgen.generateKey(); byte[] data = IOUtil.toByteArray(plainInput); byte[] encryptedData = getCipher("AES", aesKey, Cipher.ENCRYPT_MODE).doFinal(data); byte[] raw = aesKey.getEncoded(); byte[] encryptedKey = getCipher("RSA/ECB/PKCS1Padding", key, javax.crypto.Cipher.ENCRYPT_MODE).doFinal(raw); // useful when debugging but can't be left uncommented due to NEXUS-2530 // if ( getLogger().isDebugEnabled() ) // { // log.debug( "before encrypt: " + new String( Base64.encodeBase64( raw ) ) ); // log.debug( "Encrypted key: " + new String( Base64.encodeBase64( encryptedKey ) ) ); // log.debug( "Encrypted data: " + new String( Base64.encodeBase64( encryptedData ) ) ); // } Base64OutputStream output = new Base64OutputStream(encryptedOutput); IOUtil.copy(encryptedKey, output); IOUtil.copy(encryptedData, output); output.close(); encryptedOutput.flush(); }
From source file:net.sourceforge.jencrypt.lib.CryptoWrapper.java
private byte[] getHashedPassword(CryptoWrapperBuilder builder) throws NoSuchAlgorithmException, InvalidKeySpecException { /* Apply PBKDF2 (Password-Based Key Derivation Function 2) with * HMAC-SHA-1 to the password (for further details, see RFC-2898). *//*ww w . j a v a 2s .c om*/ SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); PBEKeySpec spec = new PBEKeySpec(builder.password.toCharArray(), salt, keyDerivationIterationCount, builder.keySize); SecretKey secret = factory.generateSecret(spec); return secret.getEncoded(); }
From source file:com.thoughtworks.go.apiv3.datasharing.usagedata.UsageStatisticsControllerV3.java
public String getEncryptedUsageStatistics(Request request, Response response) throws Exception { HttpLocalizedOperationResult result = new HttpLocalizedOperationResult(); Map<String, Object> body = readRequestBodyAsJSON(request); String signature = (String) body.get(SIGNATURE_KEY); String publicKey = (String) body.get(SUBORDINATE_PUBLIC_KEY); boolean isVerified = verifySignatureAndPublicKey(signature, publicKey, result); if (isVerified) { SecretKey secretKey = EncryptionHelper.generateAESKey(); String aesEncryptedData = EncryptionHelper.encryptUsingAES(secretKey, getUsageStatistics(request, response)); String rsaEncryptedKey = EncryptionHelper .encryptUsingRSA(Base64.getEncoder().encodeToString(secretKey.getEncoded()), publicKey); return jsonizeAsTopLevelObject(request, writer -> EncryptedDataRepresenter.toJSON(writer, aesEncryptedData, rsaEncryptedKey)); }/*from w ww. j av a 2s .co m*/ return renderHTTPOperationResult(result, request, response); }
From source file:com.joyent.manta.client.multipart.EncryptedMultipartManagerTest.java
private SettableConfigContext<BaseChainedConfigContext> testConfigContext(SecretKey key) { StandardConfigContext settable = new StandardConfigContext(); settable.setMantaUser("test"); settable.setPrivateKeyContent(UnitTestConstants.PRIVATE_KEY); settable.setMantaKeyId(UnitTestConstants.FINGERPRINT); settable.setEncryptionPrivateKeyBytes(key.getEncoded()); return new TestConfigContext(settable); }
From source file:org.lsc.utils.security.SymmetricEncryption.java
/** * Generate a random key file.//from w w w .ja v a 2s . c om * @param keyPath The filename where to write the key * @param algo The supported algorithm to use * @param strength The encryption strength * @return boolean false if an error occurred * @throws NoSuchAlgorithmException * @throws NoSuchProviderException */ public boolean generateRandomKeyFile(String keyPath, String algo, int strength) throws NoSuchAlgorithmException, NoSuchProviderException { OutputStream os = null; try { KeyGenerator kg = KeyGenerator.getInstance(algo, securityProvider.getName()); SecretKey cipherKey = kg.generateKey(); SecureRandom sr = new SecureRandom(); kg.init(strength, sr); os = new FileOutputStream(keyPath); os.write(cipherKey.getEncoded()); } catch (IOException e) { LOGGER.error("Unable to write new generated key in " + keyPath + ". Encountered exception is : " + e.getLocalizedMessage(), e); return false; } finally { try { if (os != null) { os.close(); } } catch (IOException e1) { } } return true; }
From source file:cn.ctyun.amazonaws.services.s3.internal.crypto.EncryptionUtils.java
/** * Encrypts a symmetric key using the provided encryption materials and returns * it in raw byte array form./*from www . j a v a 2s .c o m*/ */ public static byte[] getEncryptedSymmetricKey(SecretKey toBeEncrypted, EncryptionMaterials materials, Provider cryptoProvider) { Key keyToDoEncryption; if (materials.getKeyPair() != null) { // Do envelope encryption with public key from key pair keyToDoEncryption = materials.getKeyPair().getPublic(); } else { // Do envelope encryption with symmetric key keyToDoEncryption = materials.getSymmetricKey(); } try { Cipher cipher; byte[] toBeEncryptedBytes = toBeEncrypted.getEncoded(); if (cryptoProvider != null) { cipher = Cipher.getInstance(keyToDoEncryption.getAlgorithm(), cryptoProvider); } else { cipher = Cipher.getInstance(keyToDoEncryption.getAlgorithm()); // Use default JCE Provider } cipher.init(Cipher.ENCRYPT_MODE, keyToDoEncryption); return cipher.doFinal(toBeEncryptedBytes); } catch (Exception e) { throw new AmazonClientException("Unable to encrypt symmetric key: " + e.getMessage(), e); } }
From source file:com.microsoft.azure.storage.queue.QueueEncryptionPolicy.java
/** * Return an encrypted base64 encoded message along with encryption related metadata given a plain text message. * // w w w. j a va 2s.c o m * @param inputMessage * The input message in bytes. * @return The encrypted message that will be uploaded to the service. * @throws StorageException * An exception representing any error which occurred during the operation. */ String encryptMessage(byte[] inputMessage) throws StorageException { Utility.assertNotNull("inputMessage", inputMessage); if (this.keyWrapper == null) { throw new IllegalArgumentException(SR.KEY_MISSING); } CloudQueueEncryptedMessage encryptedMessage = new CloudQueueEncryptedMessage(); EncryptionData encryptionData = new EncryptionData(); encryptionData.setEncryptionAgent(new EncryptionAgent(Constants.EncryptionConstants.ENCRYPTION_PROTOCOL_V1, EncryptionAlgorithm.AES_CBC_256)); try { KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(256); Cipher myAes = Cipher.getInstance("AES/CBC/PKCS5Padding"); SecretKey aesKey = keyGen.generateKey(); myAes.init(Cipher.ENCRYPT_MODE, aesKey); // Wrap key Pair<byte[], String> encryptedKey = this.keyWrapper .wrapKeyAsync(aesKey.getEncoded(), null /* algorithm */).get(); encryptionData.setWrappedContentKey(new WrappedContentKey(this.keyWrapper.getKid(), encryptedKey.getKey(), encryptedKey.getValue())); encryptedMessage.setEncryptedMessageContents( new String(Base64.encode(myAes.doFinal(inputMessage, 0, inputMessage.length)))); encryptionData.setContentEncryptionIV(myAes.getIV()); encryptedMessage.setEncryptionData(encryptionData); return encryptedMessage.serialize(); } catch (Exception e) { throw StorageException.translateClientException(e); } }
From source file:hudson.cli.Connection.java
/** * Upgrades a connection with transport encryption by the specified symmetric cipher. * * @return//from ww w.j a va 2s. co m * A new {@link Connection} object that includes the transport encryption. */ public Connection encryptConnection(SecretKey sessionKey, String algorithm) throws IOException, GeneralSecurityException { Cipher cout = Cipher.getInstance(algorithm); cout.init(Cipher.ENCRYPT_MODE, sessionKey, new IvParameterSpec(sessionKey.getEncoded())); CipherOutputStream o = new CipherOutputStream(out, cout); Cipher cin = Cipher.getInstance(algorithm); cin.init(Cipher.DECRYPT_MODE, sessionKey, new IvParameterSpec(sessionKey.getEncoded())); CipherInputStream i = new CipherInputStream(in, cin); return new Connection(i, o); }
From source file:ch.bfh.evoting.alljoyn.MessageEncrypter.java
/** * Key derivation method from the given password * @param password password to derive/* ww w . ja v a2 s.c om*/ */ private void derivateKey(char[] password) { //Inspired from http://stackoverflow.com/questions/992019/java-256-bit-aes-password-based-encryption SecretKeyFactory factory; try { factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); //1000 iteration should be enough since the attack has to be done online and //salt changes for each group KeySpec spec = new PBEKeySpec(password, this.salt, 1000, 256); SecretKey tmp = factory.generateSecret(spec); secretKey = new SecretKeySpec(tmp.getEncoded(), "AES"); this.isReady = true; } catch (NoSuchAlgorithmException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); } catch (InvalidKeySpecException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); } }