/** * Encrypts input data. The result composes of (msg, padding if needed, mac) and sequence num. * @param data the input byte array * @param offset the offset in input where the input starts * @param len the input length * @return the new encrypted byte array. * @throws SaslException if error happens */ public byte[] wrap(byte[] data, int offset, int len) throws SaslException { // mac byte[] mac = integrity.getHMAC(data, offset, len); integrity.incMySeqNum(); // encrypt byte[] encrypted = new byte[len + 10]; try { int n = encryptor.update(data, offset, len, encrypted, 0); encryptor.update(mac, 0, 10, encrypted, n); } catch (ShortBufferException sbe) { // this should not happen throw new SaslException("Error happens during encrypt data", sbe); } // append seqNum used for mac byte[] wrapped = new byte[encrypted.length + 4]; System.arraycopy(encrypted, 0, wrapped, 0, encrypted.length); System.arraycopy(integrity.getSeqNum(), 0, wrapped, encrypted.length, 4); return wrapped; }
public CryptoAES(String transformation, Properties properties, byte[] inKey, byte[] outKey, byte[] inIv, byte[] outIv) throws IOException { checkTransformation(transformation); // encryptor encryptor = Utils.getCipherInstance(transformation, properties); try { SecretKeySpec outKEYSpec = new SecretKeySpec(outKey, "AES"); IvParameterSpec outIVSpec = new IvParameterSpec(outIv); encryptor.init(Cipher.ENCRYPT_MODE, outKEYSpec, outIVSpec); } catch (InvalidKeyException | InvalidAlgorithmParameterException e) { throw new IOException("Failed to initialize encryptor", e); } // decryptor decryptor = Utils.getCipherInstance(transformation, properties); try { SecretKeySpec inKEYSpec = new SecretKeySpec(inKey, "AES"); IvParameterSpec inIVSpec = new IvParameterSpec(inIv); decryptor.init(Cipher.DECRYPT_MODE, inKEYSpec, inIVSpec); } catch (InvalidKeyException | InvalidAlgorithmParameterException e) { throw new IOException("Failed to initialize decryptor", e); } integrity = new Integrity(outKey, inKey); }
/** * Closes the OpenSSL cipher. Clean the OpenSsl native context. */ @Override public void close() { cipher.clean(); } }
private void initializeForAuth(String cipher, byte[] nonce, SecretKeySpec key) throws GeneralSecurityException { // commons-crypto currently only supports ciphers that require an initial vector; so // create a dummy vector so that we can initialize the ciphers. In the future, if // different ciphers are supported, this will have to be configurable somehow. byte[] iv = new byte[conf.ivLength()]; System.arraycopy(nonce, 0, iv, 0, Math.min(nonce.length, iv.length)); encryptor = CryptoCipherFactory.getCryptoCipher(cipher, cryptoConf); encryptor.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv)); decryptor = CryptoCipherFactory.getCryptoCipher(cipher, cryptoConf); decryptor.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv)); }
/** * Return an <code>OpenSslCipher</code> object that implements the specified * transformation. * * @param transformation the name of the transformation, e.g., * AES/CTR/NoPadding. * @return OpenSslCipher an <code>OpenSslCipher</code> object * @throws NoSuchAlgorithmException if <code>transformation</code> is null, * empty, in an invalid format, or if OpenSsl doesn't implement the * specified algorithm. * @throws NoSuchPaddingException if <code>transformation</code> contains a * padding scheme that is not available. * @throws IllegalStateException if native code cannot be initialised */ public static OpenSsl getInstance(String transformation) throws NoSuchAlgorithmException, NoSuchPaddingException { if (loadingFailureReason != null) { throw new IllegalStateException(loadingFailureReason); } Transform transform = tokenizeTransformation(transformation); int algorithmMode = AlgorithmMode.get(transform.algorithm, transform.mode); int padding = Padding.get(transform.padding); long context = OpenSslNative.initContext(algorithmMode, padding); return new OpenSsl(context, algorithmMode, padding); }
/** * Continues a multiple-part encryption/decryption operation. The data is * encrypted or decrypted, depending on how this cipher was initialized. * * @param input the input byte array * @param inputOffset the offset in input where the input starts * @param inputLen the input length * @param output the byte array for the result * @param outputOffset the offset in output where the result is stored * @return the number of bytes stored in output * @throws ShortBufferException if there is insufficient space in the output * byte array */ public int update(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws ShortBufferException { checkState(); return OpenSslNative.updateByteArray(context, input, inputOffset, inputLen, output, outputOffset, output.length - outputOffset); }
/** * Encrypts or decrypts data in a single-part operation, or finishes a * multiple-part operation. * * @param output the byte array for the result * @param outputOffset the offset in output where the result is stored * @return the number of bytes stored in output * @throws ShortBufferException if the given output byte array is too small * to hold the result * @throws BadPaddingException if this cipher is in decryption mode, and * (un)padding has been requested, but the decrypted data is not * bounded by the appropriate padding bytes * @throws IllegalBlockSizeException if this cipher is a block cipher, no * padding has been requested (only in encryption mode), and the * total input length of the data processed by this cipher is not a * multiple of block size; or if this encryption algorithm is unable * to process the input data provided. */ public int doFinal(byte[] output, int outputOffset) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { checkState(); return OpenSslNative.doFinalByteArray(context, output, outputOffset, output.length - outputOffset); }
/** * Configures the provided {@link Properties} such that {@link CryptoCipherFactory#getCryptoCipher(String, * Properties)} will only try to use the OpenSSL cipher implementation which uses AES-NI. */ public static Properties forceOpenSsl(Properties properties) { properties.setProperty(CryptoCipherFactory.CLASSES_KEY, CryptoCipherFactory.CipherProvider.OPENSSL.getClassName()); return properties; }
/** * Gets the counter for input stream position. * * @param position the given position in the data. * @return the counter for input stream position. */ protected long getCounter(long position) { return position / cipher.getBlockSize(); }
/** * Continues a multiple-part encryption/decryption operation. The data is * encrypted or decrypted, depending on how this cipher was initialized. * * @param inBuffer the input ByteBuffer * @param outBuffer the output ByteBuffer * @return int number of bytes stored in <code>output</code> * @throws ShortBufferException if there is insufficient space in the output * buffer */ @Override public int update(ByteBuffer inBuffer, ByteBuffer outBuffer) throws ShortBufferException { return cipher.update(inBuffer, outBuffer); }
/** * Initialize this cipher with a key and IV. * * @param mode {@link #ENCRYPT_MODE} or {@link #DECRYPT_MODE} * @param key crypto key * @param iv crypto iv */ public void init(int mode, byte[] key, byte[] iv) { context = OpenSslNative .init(context, mode, algorithm, padding, key, iv); }
/** Forcibly clean the context. */ public void clean() { if (context != 0) { OpenSslNative.clean(context); context = 0; } }
private void initializeForAuth(String cipher, byte[] nonce, SecretKeySpec key) throws GeneralSecurityException { // commons-crypto currently only supports ciphers that require an initial vector; so // create a dummy vector so that we can initialize the ciphers. In the future, if // different ciphers are supported, this will have to be configurable somehow. byte[] iv = new byte[conf.ivLength()]; System.arraycopy(nonce, 0, iv, 0, Math.min(nonce.length, iv.length)); encryptor = CryptoCipherFactory.getCryptoCipher(cipher, cryptoConf); encryptor.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv)); decryptor = CryptoCipherFactory.getCryptoCipher(cipher, cryptoConf); decryptor.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv)); }
/** * Initializes the cipher. * * @throws IOException if an I/O error occurs. */ protected void initCipher() throws IOException { try { cipher.init(Cipher.ENCRYPT_MODE, key, params); } catch (InvalidKeyException e) { throw new IOException(e); } catch (InvalidAlgorithmParameterException e) { throw new IOException(e); } }
byte[] peerSeqNum = new byte[4]; try { decryptor.update(data, offset, len - 4, decrypted, 0); } catch (ShortBufferException sbe) {
/** * Gets the padding for input stream position. * * @param position the given position in the data. * @return the padding for input stream position. */ protected byte getPadding(long position) { return (byte) (position % cipher.getBlockSize()); }
@Override protected void finalize() throws Throwable { clean(); }
/** * Continues a multiple-part encryption/decryption operation. The data is * encrypted or decrypted, depending on how this cipher was initialized. * * @param input the input byte array * @param inputOffset the offset in input where the input starts * @param inputLen the input length * @param output the byte array for the result * @param outputOffset the offset in output where the result is stored * @return the number of bytes stored in output * @throws ShortBufferException if there is insufficient space in the output * byte array */ @Override public int update(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws ShortBufferException { return cipher .update(input, inputOffset, inputLen, output, outputOffset); }
/** * Initializes the cipher. * * @throws IOException if an I/O error occurs. */ protected void initCipher() throws IOException { try { cipher.init(Cipher.DECRYPT_MODE, key, params); } catch (InvalidKeyException e) { throw new IOException(e); } catch (InvalidAlgorithmParameterException e) { throw new IOException(e); } }
/** * Checks and floors buffer size. * * @param cipher the {@link CryptoCipher} instance. * @param bufferSize the buffer size. * @return the remaining buffer size. */ static int checkBufferSize(CryptoCipher cipher, int bufferSize) { Utils.checkArgument(bufferSize >= CryptoInputStream.MIN_BUFFER_SIZE, "Minimum value of buffer size is " + CryptoInputStream.MIN_BUFFER_SIZE + "."); return bufferSize - bufferSize % cipher.getBlockSize(); } }