Java Code Examples for javax.crypto.Cipher#ENCRYPT_MODE

The following examples show how to use javax.crypto.Cipher#ENCRYPT_MODE . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Encrypt.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a Cipher object for the requested encryption/decryption mode.
 *
 * @param mode encryption or decryption mode
 * @return Cipher object initiated to perform requested mode operation
 */
private Cipher createCipher(int mode, AlgorithmParameters params)
        throws Exception {
    Cipher ci;
    if (Cipher.ENCRYPT_MODE == mode) {
        // create a new Cipher object for encryption
        ci = Cipher.getInstance(transformation, provider);

        // initiate it with the saved parameters
        if (params != null) {
            ci.init(Cipher.ENCRYPT_MODE, key, params);
        } else {
            // initiate the cipher without parameters
            ci.init(Cipher.ENCRYPT_MODE, key);
        }
    } else {
        // it is expected that parameters already generated
        // before decryption
        ci = Cipher.getInstance(transformation, provider);
        ci.init(Cipher.DECRYPT_MODE, key, params);
    }

    return ci;
}
 
Example 2
Source File: AESPBEWrapper.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Initiate the Cipher object using given "mode".
 * @return a cipher object.
 * @throws GeneralSecurityException all security exceptions are thrown.
 */
@Override
protected Cipher initCipher(int mode) throws GeneralSecurityException {
    Provider provider = Security.getProvider("SunJCE");
    if (provider == null) {
        throw new RuntimeException("SunJCE provider does not exist.");
    }
    // get Cipher instance
    Cipher ci = Cipher.getInstance(transformation, provider);
    if (Cipher.ENCRYPT_MODE == mode) {
        ci.init(Cipher.ENCRYPT_MODE, key);
        pbeParams = ci.getParameters();
    } else {
        ci.init(Cipher.DECRYPT_MODE, key, pbeParams);
    }
    return ci;
}
 
Example 3
Source File: Encrypt.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a Cipher object for the requested encryption/decryption mode.
 *
 * @param mode encryption or decryption mode
 * @return Cipher object initiated to perform requested mode operation
 */
private Cipher createCipher(int mode, AlgorithmParameters params)
        throws Exception {
    Cipher ci;
    if (Cipher.ENCRYPT_MODE == mode) {
        // create a new Cipher object for encryption
        ci = Cipher.getInstance(transformation, provider);

        // initiate it with the saved parameters
        if (params != null) {
            ci.init(Cipher.ENCRYPT_MODE, key, params);
        } else {
            // initiate the cipher without parameters
            ci.init(Cipher.ENCRYPT_MODE, key);
        }
    } else {
        // it is expected that parameters already generated
        // before decryption
        ci = Cipher.getInstance(transformation, provider);
        ci.init(Cipher.DECRYPT_MODE, key, params);
    }

    return ci;
}
 
Example 4
Source File: Encrypt.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a Cipher object for the requested encryption/decryption mode.
 *
 * @param mode encryption or decryption mode
 * @return Cipher object initiated to perform requested mode operation
 */
private Cipher createCipher(int mode, AlgorithmParameters params)
        throws Exception {
    Cipher ci;
    if (Cipher.ENCRYPT_MODE == mode) {
        // create a new Cipher object for encryption
        ci = Cipher.getInstance(transformation, provider);

        // initiate it with the saved parameters
        if (params != null) {
            ci.init(Cipher.ENCRYPT_MODE, key, params);
        } else {
            // initiate the cipher without parameters
            ci.init(Cipher.ENCRYPT_MODE, key);
        }
    } else {
        // it is expected that parameters already generated
        // before decryption
        ci = Cipher.getInstance(transformation, provider);
        ci.init(Cipher.DECRYPT_MODE, key, params);
    }

    return ci;
}
 
Example 5
Source File: GXDLMSSecureClient.java    From gurux.dlms.java with GNU General Public License v2.0 6 votes vote down vote up
public static Cipher getCipher(final boolean encrypt, final byte[] kek)
        throws NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException, InvalidAlgorithmParameterException {
    GXByteBuffer iv = new GXByteBuffer();
    // iv.set(IV);

    // iv.set(p.getSystemTitle());
    // iv.setUInt32(p.getInvocationCounter());
    SecretKeySpec eks = new SecretKeySpec(kek, "AES");
    Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
    int mode;
    if (encrypt) {
        mode = Cipher.ENCRYPT_MODE;
    } else {
        mode = Cipher.DECRYPT_MODE;
    }
    c.init(mode, eks, new GCMParameterSpec(12 * 8, iv.array()));
    return c;
}
 
Example 6
Source File: Encrypt.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a Cipher object for the requested encryption/decryption mode.
 *
 * @param mode encryption or decryption mode
 * @return Cipher object initiated to perform requested mode operation
 */
private Cipher createCipher(int mode, AlgorithmParameters params)
        throws Exception {
    Cipher ci;
    if (Cipher.ENCRYPT_MODE == mode) {
        // create a new Cipher object for encryption
        ci = Cipher.getInstance(transformation, provider);

        // initiate it with the saved parameters
        if (params != null) {
            ci.init(Cipher.ENCRYPT_MODE, key, params);
        } else {
            // initiate the cipher without parameters
            ci.init(Cipher.ENCRYPT_MODE, key);
        }
    } else {
        // it is expected that parameters already generated
        // before decryption
        ci = Cipher.getInstance(transformation, provider);
        ci.init(Cipher.DECRYPT_MODE, key, params);
    }

    return ci;
}
 
Example 7
Source File: PBKDF2Wrapper.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Perform encryption/decryption operation (depending on the specified
 * edMode) on the same byte buffer. Compare result with the result at an
 * allocated buffer. If both results are equal - return true, otherwise
 * return false.
 *
 * @param edMode specified mode
 * @param inputText text to decrypt
 * @param offset offset in the text
 * @param len input length
 * @return ture - test passed; false - test failed
 */
@Override
public boolean execute(int edMode, byte[] inputText, int offset, int len) {
    int needBytesForResult = -1;
    String KEY_ALGORITHM = "AES";

    try {
        // init Cipher
        if (Cipher.ENCRYPT_MODE == edMode) {
            ci.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getEncoded(),
                    KEY_ALGORITHM));
            iv = ci.getParameters().getParameterSpec(IvParameterSpec.class).
                    getIV();
        } else {
            ci.init(Cipher.DECRYPT_MODE,
                    new SecretKeySpec(key.getEncoded(), KEY_ALGORITHM),
                    new IvParameterSpec(iv));
        }

        // First, generate the cipherText at an allocated buffer
        byte[] outputText = ci.doFinal(inputText, offset, len);

        // Second, generate cipherText again at the same buffer of plainText
        int myoff = offset / 2;
        int off = ci.update(inputText, offset, len, inputText, myoff);
        ci.doFinal(inputText, myoff + off);

        // Compare to see whether the two results are the same or not
        return equalsBlock(inputText, myoff, outputText, 0,
                outputText.length);
    } catch (Exception ex) {
        out.println("Catch unexpected exception within " + algo
                + " " + edMode + ": " + ex.getMessage()
                + ". getOutputSize()" + "returned " + needBytesForResult);
        ex.printStackTrace(out);

        return false;
    }
}
 
Example 8
Source File: MockCipherSpi.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Override
protected void engineInit(int opmode, Key key, AlgorithmParameters params,
        SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
    if (opmode != Cipher.ENCRYPT_MODE) {
        throw new InvalidKeyException("expected rejection");
    }
}
 
Example 9
Source File: CipherLite.java    From cos-java-sdk-v5 with MIT License 5 votes vote down vote up
/**
 * Returns the inverse of the current {@link CipherLite}.
 */
CipherLite createInverse() throws InvalidKeyException,
        NoSuchAlgorithmException, NoSuchProviderException,
        NoSuchPaddingException, InvalidAlgorithmParameterException {
    int inversedMode;
    if (cipherMode == Cipher.DECRYPT_MODE)
        inversedMode = Cipher.ENCRYPT_MODE;
    else if (cipherMode == Cipher.ENCRYPT_MODE)
        inversedMode = Cipher.DECRYPT_MODE;
    else
        throw new UnsupportedOperationException();
    return scheme.createCipherLite(secreteKey, cipher.getIV(),
            inversedMode, cipher.getProvider());
}
 
Example 10
Source File: PBKDF2Wrapper.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Perform encryption/decryption operation (depending on the specified
 * edMode) on the same byte buffer. Compare result with the result at an
 * allocated buffer. If both results are equal - return true, otherwise
 * return false.
 *
 * @param edMode specified mode
 * @param inputText text to decrypt
 * @param offset offset in the text
 * @param len input length
 * @return ture - test passed; false - test failed
 */
@Override
public boolean execute(int edMode, byte[] inputText, int offset, int len) {
    int needBytesForResult = -1;
    String KEY_ALGORITHM = "AES";

    try {
        // init Cipher
        if (Cipher.ENCRYPT_MODE == edMode) {
            ci.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getEncoded(),
                    KEY_ALGORITHM));
            iv = ci.getParameters().getParameterSpec(IvParameterSpec.class).
                    getIV();
        } else {
            ci.init(Cipher.DECRYPT_MODE,
                    new SecretKeySpec(key.getEncoded(), KEY_ALGORITHM),
                    new IvParameterSpec(iv));
        }

        // First, generate the cipherText at an allocated buffer
        byte[] outputText = ci.doFinal(inputText, offset, len);

        // Second, generate cipherText again at the same buffer of plainText
        int myoff = offset / 2;
        int off = ci.update(inputText, offset, len, inputText, myoff);
        ci.doFinal(inputText, myoff + off);

        // Compare to see whether the two results are the same or not
        return equalsBlock(inputText, myoff, outputText, 0,
                outputText.length);
    } catch (Exception ex) {
        out.println("Catch unexpected exception within " + algo
                + " " + edMode + ": " + ex.getMessage()
                + ". getOutputSize()" + "returned " + needBytesForResult);
        ex.printStackTrace(out);

        return false;
    }
}
 
Example 11
Source File: SecureEncryptor.java    From CogniCrypt with Eclipse Public License 2.0 5 votes vote down vote up
public byte[] encrypt(byte[] plaintext, javax.crypto.SecretKey key) {
	byte[] ivBytes = new byte[key.getEncoded().length];
	byte[] res = null;
	int mode = Cipher.ENCRYPT_MODE;

	CrySLCodeGenerator.getInstance().includeClass("java.security.SecureRandom").addParameter(ivBytes, "next").includeClass("javax.crypto.spec.IvParameterSpec")
		.addParameter(ivBytes, "iv").includeClass("javax.crypto.Cipher").addParameter(mode, "encmode").addParameter(plaintext, "plainText").addParameter(key, "key")
		.addReturnObject(res).generate();

	byte[] ret = new byte[ivBytes.length + res.length];
	System.arraycopy(ivBytes, 0, ret, 0, ivBytes.length);
	System.arraycopy(res, 0, ret, ivBytes.length, res.length);
	return ret;
}
 
Example 12
Source File: AesCipherDataSink.java    From MediaSDK with Apache License 2.0 5 votes vote down vote up
@Override
public void open(DataSpec dataSpec) throws IOException {
  wrappedDataSink.open(dataSpec);
  long nonce = CryptoUtil.getFNV64Hash(dataSpec.key);
  cipher = new AesFlushingCipher(Cipher.ENCRYPT_MODE, secretKey, nonce,
      dataSpec.absoluteStreamPosition);
}
 
Example 13
Source File: PBKDF2Wrapper.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Perform encryption/decryption operation (depending on the specified
 * edMode) on the same byte buffer. Compare result with the result at an
 * allocated buffer. If both results are equal - return true, otherwise
 * return false.
 *
 * @param edMode specified mode
 * @param inputText text to decrypt
 * @param offset offset in the text
 * @param len input length
 * @return ture - test passed; false - test failed
 */
@Override
public boolean execute(int edMode, byte[] inputText, int offset, int len) {
    int needBytesForResult = -1;
    String KEY_ALGORITHM = "AES";

    try {
        // init Cipher
        if (Cipher.ENCRYPT_MODE == edMode) {
            ci.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getEncoded(),
                    KEY_ALGORITHM));
            iv = ci.getParameters().getParameterSpec(IvParameterSpec.class).
                    getIV();
        } else {
            ci.init(Cipher.DECRYPT_MODE,
                    new SecretKeySpec(key.getEncoded(), KEY_ALGORITHM),
                    new IvParameterSpec(iv));
        }

        // First, generate the cipherText at an allocated buffer
        byte[] outputText = ci.doFinal(inputText, offset, len);

        // Second, generate cipherText again at the same buffer of plainText
        int myoff = offset / 2;
        int off = ci.update(inputText, offset, len, inputText, myoff);
        ci.doFinal(inputText, myoff + off);

        // Compare to see whether the two results are the same or not
        return equalsBlock(inputText, myoff, outputText, 0,
                outputText.length);
    } catch (Exception ex) {
        out.println("Catch unexpected exception within " + algo
                + " " + edMode + ": " + ex.getMessage()
                + ". getOutputSize()" + "returned " + needBytesForResult);
        ex.printStackTrace(out);

        return false;
    }
}
 
Example 14
Source File: PBECipherWrapper.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void initCipher(int mode) throws InvalidKeyException,
        InvalidAlgorithmParameterException, InvalidParameterSpecException {
    if (Cipher.ENCRYPT_MODE == mode) {
        ci.init(Cipher.ENCRYPT_MODE, key);
        pbeParams = ci.getParameters();
    } else {
        ci.init(Cipher.DECRYPT_MODE, key, pbeParams);
    }
}
 
Example 15
Source File: PBECipherWrapper.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void initCipher(int mode) throws InvalidKeyException,
        InvalidAlgorithmParameterException, InvalidParameterSpecException {
    if (Cipher.ENCRYPT_MODE == mode) {
        ci.init(Cipher.ENCRYPT_MODE, key);
        pbeParams = ci.getParameters();
    } else {
        ci.init(Cipher.DECRYPT_MODE, key, pbeParams);
    }
}
 
Example 16
Source File: IESCipher.java    From ripple-lib-java with ISC License 4 votes vote down vote up
public int engineGetOutputSize(int inputLen)
{
    int len1, len2, len3;

    len1 = engine.getMac().getMacSize();

    if (key != null)
    {
        len2 = 1 + 2 * (((ECKey)key).getParameters().getCurve().getFieldSize() + 7) / 8;
    }
    else
    {
        throw new IllegalStateException("cipher not initialised");
    }

    if (engine.getCipher() == null)
    {
        len3 = inputLen;
    }
    else if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE)
    {
        len3 = engine.getCipher().getOutputSize(inputLen);
    }
    else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE)
    {
        len3 = engine.getCipher().getOutputSize(inputLen - len1 - len2);
    }
    else
    {
        throw new IllegalStateException("cipher not initialised");
    }

    if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE)
    {
        return buffer.size() + len1 + len2 + len3;
    }
    else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE)
    {
        return buffer.size() - len1 - len2 + len3;
    }
    else
    {
        throw new IllegalStateException("cipher not initialised");
    }

}
 
Example 17
Source File: AESPBEWrapper.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Perform encryption/decryption operation (depending on the specified
 * edMode) on the same byte buffer. Compare result with the result at an
 * allocated buffer. If both results are equal - return true, otherwise
 * return false.
 *
 * @param edMode specified mode
 * @param inputText text to decrypt
 * @param offset offset in the text
 * @param len input length
 * @return ture - test passed; false - test failed
 */
@Override
public boolean execute(int edMode, byte[] inputText, int offset, int len) {
    boolean isUnlimited;
    try {
        isUnlimited =
            (Cipher.getMaxAllowedKeyLength(this.algo) == Integer.MAX_VALUE);
    } catch (NoSuchAlgorithmException nsae) {
        out.println("Got unexpected exception for " + this.algo);
        nsae.printStackTrace(out);
        return false;
    }
    try {
        // init Cipher
        if (Cipher.ENCRYPT_MODE == edMode) {
            ci.init(Cipher.ENCRYPT_MODE, this.key);
            pbeParams = ci.getParameters();
        } else {
            ci.init(Cipher.DECRYPT_MODE, this.key, pbeParams);
        }

        if (this.algo.endsWith("AES_256") && !isUnlimited) {
            out.print("Expected exception not thrown for " + this.algo);
            return false;
        }

        // First, generate the cipherText at an allocated buffer
        byte[] outputText = ci.doFinal(inputText, offset, len);

        // Second, generate cipherText again at the same buffer of plainText
        int myoff = offset / 2;
        int off = ci.update(inputText, offset, len, inputText, myoff);
        ci.doFinal(inputText, myoff + off);

        // Compare to see whether the two results are the same or not
        return equalsBlock(inputText, myoff, outputText, 0,
                outputText.length);
    } catch (Exception ex) {
        if ((ex instanceof InvalidKeyException)
                && this.algo.endsWith("AES_256") && !isUnlimited) {
            out.println("Expected InvalidKeyException thrown");
            return true;
        } else {
            out.println("Got unexpected exception for " + algo);
            ex.printStackTrace(out);
            return false;
        }
    }
}
 
Example 18
Source File: IESCipher.java    From RipplePower with Apache License 2.0 4 votes vote down vote up
public int engineGetOutputSize(int inputLen)
{
    int len1, len2, len3;

    len1 = engine.getMac().getMacSize();

    if (key != null)
    {
        len2 = 1 + 2 * (((ECKey)key).getParameters().getCurve().getFieldSize() + 7) / 8;
    }
    else
    {
        throw new IllegalStateException("cipher not initialised");
    }

    if (engine.getCipher() == null)
    {
        len3 = inputLen;
    }
    else if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE)
    {
        len3 = engine.getCipher().getOutputSize(inputLen);
    }
    else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE)
    {
        len3 = engine.getCipher().getOutputSize(inputLen - len1 - len2);
    }
    else
    {
        throw new IllegalStateException("cipher not initialised");
    }

    if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE)
    {
        return buffer.size() + len1 + len2 + len3;
    }
    else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE)
    {
        return buffer.size() - len1 - len2 + len3;
    }
    else
    {
        throw new IllegalStateException("cipher not initialised");
    }

}
 
Example 19
Source File: AESPBEWrapper.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Perform encryption/decryption operation (depending on the specified
 * edMode) on the same byte buffer. Compare result with the result at an
 * allocated buffer. If both results are equal - return true, otherwise
 * return false.
 *
 * @param edMode specified mode
 * @param inputText text to decrypt
 * @param offset offset in the text
 * @param len input length
 * @return ture - test passed; false - test failed
 */
@Override
public boolean execute(int edMode, byte[] inputText, int offset, int len) {
    boolean isUnlimited;
    try {
        isUnlimited =
            (Cipher.getMaxAllowedKeyLength(this.algo) == Integer.MAX_VALUE);
    } catch (NoSuchAlgorithmException nsae) {
        out.println("Got unexpected exception for " + this.algo);
        nsae.printStackTrace(out);
        return false;
    }
    try {
        // init Cipher
        if (Cipher.ENCRYPT_MODE == edMode) {
            ci.init(Cipher.ENCRYPT_MODE, this.key);
            pbeParams = ci.getParameters();
        } else {
            ci.init(Cipher.DECRYPT_MODE, this.key, pbeParams);
        }

        if (this.algo.endsWith("AES_256") && !isUnlimited) {
            out.print("Expected exception not thrown for " + this.algo);
            return false;
        }

        // First, generate the cipherText at an allocated buffer
        byte[] outputText = ci.doFinal(inputText, offset, len);

        // Second, generate cipherText again at the same buffer of plainText
        int myoff = offset / 2;
        int off = ci.update(inputText, offset, len, inputText, myoff);
        ci.doFinal(inputText, myoff + off);

        // Compare to see whether the two results are the same or not
        return equalsBlock(inputText, myoff, outputText, 0,
                outputText.length);
    } catch (Exception ex) {
        if ((ex instanceof InvalidKeyException)
                && this.algo.endsWith("AES_256") && !isUnlimited) {
            out.println("Expected InvalidKeyException thrown");
            return true;
        } else {
            out.println("Got unexpected exception for " + algo);
            ex.printStackTrace(out);
            return false;
        }
    }
}
 
Example 20
Source File: ProtocolDecoderPHE.java    From TorrentEngine with GNU General Public License v3.0 3 votes vote down vote up
protected void
setupCrypto()

	throws IOException
{
	try{
	    //"HASH('keyA', S, SKEY)" if you're A
	    //"HASH('keyB', S, SKEY)" if you're B

	    SHA1Hasher	hasher = new SHA1Hasher();
	    
	    hasher.update( KEYA_IV );
	    hasher.update( secret_bytes );
	    hasher.update( shared_secret );
	    	
	    byte[]	a_key = hasher.getDigest();
	    
	    hasher = new SHA1Hasher();
	    
	    hasher.update( KEYB_IV );
	    hasher.update( secret_bytes );
	    hasher.update( shared_secret );
	    	
	    byte[]	b_key = hasher.getDigest();
	    
	    SecretKeySpec	secret_key_spec_a = new SecretKeySpec( a_key, RC4_STREAM_ALG );
	        
	    SecretKeySpec	secret_key_spec_b = new SecretKeySpec( b_key, RC4_STREAM_ALG );
	        	        
	    write_cipher 	= new TransportCipher( RC4_STREAM_CIPHER, Cipher.ENCRYPT_MODE, outbound?secret_key_spec_a:secret_key_spec_b );
		    
	    read_cipher 	= new TransportCipher( RC4_STREAM_CIPHER, Cipher.DECRYPT_MODE, outbound?secret_key_spec_b:secret_key_spec_a );
	    
	}catch( Throwable e ){
		
		e.printStackTrace();
		
		throw( new IOException( Debug.getNestedExceptionMessage(e)));
	}
}