List of usage examples for javax.crypto.spec GCMParameterSpec GCMParameterSpec
public GCMParameterSpec(int tLen, byte[] src)
From source file:io.stallion.utils.Encrypter.java
public static String encryptString(String password, String value) { String salt = KeyGenerators.string().generateKey(); SecretKeySpec skeySpec = makeKeySpec(password, salt); byte[] iv = KeyGenerators.secureRandom(16).generateKey(); String ivString = Hex.encodeHexString(iv); try {// ww w . ja v a2s.c o m Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new GCMParameterSpec(128, iv)); /* Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(iv)); */ byte[] encrypted = cipher.doFinal(value.getBytes(Charset.forName("UTF-8"))); String s = StringUtils.strip(new Base32().encodeAsString(encrypted), "=").toLowerCase(); // Strip line breaks s = salt + ivString + s.replaceAll("(\\n|\\r)", ""); return s; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.joyent.manta.client.crypto.AesGcmCipherDetails.java
@Override public AlgorithmParameterSpec getEncryptionParameterSpec(final byte[] iv) { Validate.notNull(iv, "Initialization vector must not be null"); Validate.isTrue(iv.length == getIVLengthInBytes(), "Initialization vector has the wrong byte count [%d] " + "expected [%d] bytes", iv.length, getIVLengthInBytes());/* www. jav a 2s .com*/ int tagSizeInBits = getAuthenticationTagOrHmacLengthInBytes() << 3; return new GCMParameterSpec(tagSizeInBits, iv); }
From source file:io.stallion.utils.Encrypter.java
private static String doDecryptString(String password, String encryptedBase32) throws Exception { encryptedBase32 = StringUtils.strip(encryptedBase32, "="); String salt = encryptedBase32.substring(0, 16); String ivString = encryptedBase32.substring(16, 48); byte[] iv = new byte[0]; try {//from w w w . j a v a 2s . co m iv = Hex.decodeHex(ivString.toCharArray()); } catch (DecoderException e) { throw new RuntimeException(e); } encryptedBase32 = encryptedBase32.substring(48); Base32 decoder = new Base32(); byte[] encrypted = decoder.decode(encryptedBase32.toUpperCase()); SecretKeySpec skeySpec = makeKeySpec(password, salt); /* Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(iv)); */ Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); cipher.init(Cipher.DECRYPT_MODE, skeySpec, new GCMParameterSpec(128, iv)); byte[] original = cipher.doFinal(encrypted); return new String(original, Charset.forName("UTF-8")); }
From source file:keywhiz.service.crypto.ContentCryptographer.java
private byte[] gcm(Mode mode, String info, byte[] nonce, byte[] data) { try {// www .j ava2s.c o m Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM, encryptionProvider); SecretKey derivedKey = deriveKey(cipher.getBlockSize(), info); GCMParameterSpec gcmParameters = new GCMParameterSpec(TAG_BITS, nonce); cipher.init(mode.cipherMode, derivedKey, gcmParameters); return cipher.doFinal(data); } catch (IllegalBlockSizeException | InvalidAlgorithmParameterException | NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException | BadPaddingException e) { throw Throwables.propagate(e); } }
From source file:com.owncloud.android.utils.EncryptionUtils.java
/** * @param file file do crypt * @param encryptionKeyBytes key, either from metadata or {@link EncryptionUtils#generateKey()} * @param iv initialization vector, either from metadata or {@link EncryptionUtils#randomBytes(int)} * @return encryptedFile with encryptedBytes and authenticationTag *///from w w w . ja va2 s.c o m @RequiresApi(api = Build.VERSION_CODES.KITKAT) public static EncryptedFile encryptFile(File file, byte[] encryptionKeyBytes, byte[] iv) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IOException { Cipher cipher = Cipher.getInstance(AES_CIPHER); Key key = new SecretKeySpec(encryptionKeyBytes, AES); GCMParameterSpec spec = new GCMParameterSpec(128, iv); cipher.init(Cipher.ENCRYPT_MODE, key, spec); RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); byte[] fileBytes = new byte[(int) randomAccessFile.length()]; randomAccessFile.readFully(fileBytes); byte[] cryptedBytes = cipher.doFinal(fileBytes); String authenticationTag = encodeBytesToBase64String( Arrays.copyOfRange(cryptedBytes, cryptedBytes.length - (128 / 8), cryptedBytes.length)); return new EncryptedFile(cryptedBytes, authenticationTag); }
From source file:com.owncloud.android.utils.EncryptionUtils.java
/** * @param file encrypted file * @param encryptionKeyBytes key from metadata * @param iv initialization vector from metadata * @param authenticationTag authenticationTag from metadata * @return decrypted byte[]/* w ww. ja va2s .co m*/ */ @RequiresApi(api = Build.VERSION_CODES.KITKAT) public static byte[] decryptFile(File file, byte[] encryptionKeyBytes, byte[] iv, byte[] authenticationTag) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IOException { Cipher cipher = Cipher.getInstance(AES_CIPHER); Key key = new SecretKeySpec(encryptionKeyBytes, AES); GCMParameterSpec spec = new GCMParameterSpec(128, iv); cipher.init(Cipher.DECRYPT_MODE, key, spec); RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); byte[] fileBytes = new byte[(int) randomAccessFile.length()]; randomAccessFile.readFully(fileBytes); // check authentication tag byte[] extractedAuthenticationTag = Arrays.copyOfRange(fileBytes, fileBytes.length - (128 / 8), fileBytes.length); if (!Arrays.equals(extractedAuthenticationTag, authenticationTag)) { throw new SecurityException("Tag not correct"); } return cipher.doFinal(fileBytes); }
From source file:com.owncloud.android.utils.EncryptionUtils.java
/** * Encrypt string with RSA algorithm, ECB mode, OAEPWithSHA-256AndMGF1 padding * Asymmetric encryption, with private and public key * * @param string String to encrypt * @param encryptionKeyBytes key, either from metadata or {@link EncryptionUtils#generateKey()} * @return encrypted string/*from ww w. jav a2s . c om*/ */ @RequiresApi(api = Build.VERSION_CODES.KITKAT) public static String encryptStringSymmetric(String string, byte[] encryptionKeyBytes) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { Cipher cipher = Cipher.getInstance(AES_CIPHER); byte[] iv = randomBytes(ivLength); Key key = new SecretKeySpec(encryptionKeyBytes, AES); GCMParameterSpec spec = new GCMParameterSpec(128, iv); cipher.init(Cipher.ENCRYPT_MODE, key, spec); byte[] bytes = encodeStringToBase64Bytes(string); byte[] cryptedBytes = cipher.doFinal(bytes); String encodedCryptedBytes = encodeBytesToBase64String(cryptedBytes); String encodedIV = encodeBytesToBase64String(iv); return encodedCryptedBytes + ivDelimiter + encodedIV; }
From source file:com.owncloud.android.utils.EncryptionUtils.java
/** * Decrypt string with RSA algorithm, ECB mode, OAEPWithSHA-256AndMGF1 padding * Asymmetric encryption, with private and public key * * @param string string to decrypt * @param encryptionKeyBytes key from metadata * @return decrypted string/* w w w. j av a 2s. c o m*/ */ @RequiresApi(api = Build.VERSION_CODES.KITKAT) public static String decryptStringSymmetric(String string, byte[] encryptionKeyBytes) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { Cipher cipher = Cipher.getInstance(AES_CIPHER); int delimiterPosition = string.lastIndexOf(ivDelimiter); String cipherString = string.substring(0, delimiterPosition); String ivString = string.substring(delimiterPosition + ivDelimiter.length(), string.length()); byte[] iv = new IvParameterSpec(decodeStringToBase64Bytes(ivString)).getIV(); Key key = new SecretKeySpec(encryptionKeyBytes, AES); GCMParameterSpec spec = new GCMParameterSpec(128, iv); cipher.init(Cipher.DECRYPT_MODE, key, spec); byte[] bytes = decodeStringToBase64Bytes(cipherString); byte[] encodedBytes = cipher.doFinal(bytes); return decodeBase64BytesToString(encodedBytes); }
From source file:password.pwm.util.secure.SecureEngine.java
public static byte[] encryptToBytes(final String value, final PwmSecurityKey key, final PwmBlockAlgorithm blockAlgorithm) throws PwmUnrecoverableException { try {//from ww w . j av a2 s. c om if (value == null || value.length() < 1) { return null; } final SecretKey aesKey = key.getKey(blockAlgorithm.getBlockKey()); final byte[] nonce; final Cipher cipher; if (blockAlgorithm == PwmBlockAlgorithm.AES128_GCM) { nonce = AES_GCM_NONCE_GENERATOR.nextValue(); final GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, nonce); cipher = Cipher.getInstance(blockAlgorithm.getAlgName()); cipher.init(Cipher.ENCRYPT_MODE, aesKey, spec); } else { cipher = Cipher.getInstance(blockAlgorithm.getAlgName()); cipher.init(Cipher.ENCRYPT_MODE, aesKey, cipher.getParameters()); nonce = null; } final byte[] encryptedBytes = cipher.doFinal(value.getBytes(PwmConstants.DEFAULT_CHARSET)); final byte[] output; if (blockAlgorithm.getHmacAlgorithm() != null) { final byte[] hashChecksum = computeHmacToBytes(blockAlgorithm.getHmacAlgorithm(), key, encryptedBytes); output = appendByteArrays(blockAlgorithm.getPrefix(), hashChecksum, encryptedBytes); } else { if (nonce == null) { output = appendByteArrays(blockAlgorithm.getPrefix(), encryptedBytes); } else { final byte[] nonceLength = new byte[1]; nonceLength[0] = (byte) nonce.length; output = appendByteArrays(blockAlgorithm.getPrefix(), nonceLength, nonce, encryptedBytes); } } return output; } catch (Exception e) { final String errorMsg = "unexpected error performing simple crypt operation: " + e.getMessage(); final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_CRYPT_ERROR, errorMsg); LOGGER.error(errorInformation.toDebugStr()); throw new PwmUnrecoverableException(errorInformation); } }
From source file:password.pwm.util.secure.SecureEngine.java
public static String decryptBytes(final byte[] value, final PwmSecurityKey key, final PwmBlockAlgorithm blockAlgorithm) throws PwmUnrecoverableException { try {// w ww. j a v a 2 s . c o m if (value == null || value.length < 1) { return null; } byte[] workingValue = verifyAndStripPrefix(blockAlgorithm, value); final SecretKey aesKey = key.getKey(blockAlgorithm.getBlockKey()); if (blockAlgorithm.getHmacAlgorithm() != null) { final HmacAlgorithm hmacAlgorithm = blockAlgorithm.getHmacAlgorithm(); final int CHECKSUM_SIZE = hmacAlgorithm.getLength(); if (workingValue.length <= CHECKSUM_SIZE) { throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_CRYPT_ERROR, "incoming " + blockAlgorithm.toString() + " data is missing checksum")); } final byte[] inputChecksum = Arrays.copyOfRange(workingValue, 0, CHECKSUM_SIZE); final byte[] inputPayload = Arrays.copyOfRange(workingValue, CHECKSUM_SIZE, workingValue.length); final byte[] computedChecksum = computeHmacToBytes(hmacAlgorithm, key, inputPayload); if (!Arrays.equals(inputChecksum, computedChecksum)) { throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_CRYPT_ERROR, "incoming " + blockAlgorithm.toString() + " data has incorrect checksum")); } workingValue = inputPayload; } final Cipher cipher; if (blockAlgorithm == PwmBlockAlgorithm.AES128_GCM) { final int nonceLength = workingValue[0]; workingValue = Arrays.copyOfRange(workingValue, 1, workingValue.length); if (workingValue.length <= nonceLength) { throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_CRYPT_ERROR, "incoming " + blockAlgorithm.toString() + " data is missing nonce")); } final byte[] nonce = Arrays.copyOfRange(workingValue, 0, nonceLength); workingValue = Arrays.copyOfRange(workingValue, nonceLength, workingValue.length); final GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, nonce); cipher = Cipher.getInstance(blockAlgorithm.getAlgName()); cipher.init(Cipher.DECRYPT_MODE, aesKey, spec); } else { cipher = Cipher.getInstance(blockAlgorithm.getAlgName()); cipher.init(Cipher.DECRYPT_MODE, aesKey); } final byte[] decrypted = cipher.doFinal(workingValue); return new String(decrypted, PwmConstants.DEFAULT_CHARSET); } catch (Exception e) { final String errorMsg = "unexpected error performing simple decrypt operation: " + e.getMessage(); final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_CRYPT_ERROR, errorMsg); throw new PwmUnrecoverableException(errorInformation); } }