Java Code Examples for javax.crypto.Cipher.doFinal()

The following are Jave code examples for showing how to use doFinal() of the javax.crypto.Cipher class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: sunbird-utils   File: DefaultDecryptionServiceImpl.java   View Source Code Vote up 7 votes
/**
 * this method is used to decrypt password.
 * 
 * @param value encrypted password.
 * @return decrypted password.
 */
public static String decrypt(String value) {
  try {
    sunbird_encryption = DefaultEncryptionServivceImpl.getSalt();
    Key key = generateKey();
    Cipher c = Cipher.getInstance(ALGORITHM);
    c.init(Cipher.DECRYPT_MODE, key);

    String dValue = null;
    String valueToDecrypt = value.trim();
    for (int i = 0; i < ITERATIONS; i++) {
      byte[] decordedValue = new sun.misc.BASE64Decoder().decodeBuffer(valueToDecrypt);
      byte[] decValue = c.doFinal(decordedValue);
      dValue = new String(decValue).substring(sunbird_encryption.length());
      valueToDecrypt = dValue;
    }
    return dValue;
  } catch (Exception ex) {
    ProjectLogger.log("Exception Occurred while decrypting value");
  }
  return value;
}
 
Example 2
Project: os   File: AESUtils.java   View Source Code Vote up 6 votes
private static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {  
    KeyGenerator kgen = KeyGenerator.getInstance("AES");  
    kgen.init(128, new SecureRandom(encryptKey.getBytes()));  
  
    Cipher cipher = Cipher.getInstance("AES");  
    cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));  
      
    return cipher.doFinal(content.getBytes("utf-8"));  
}
 
Example 3
Project: dble   File: DecryptUtil.java   View Source Code Vote up 6 votes
public static String decrypt(PublicKey publicKey, String cipherText)
        throws Exception {
    Cipher cipher = Cipher.getInstance("RSA");
    try {
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
    } catch (InvalidKeyException e) {
        //  IBM JDK not support Private key encryption, public key decryption
        // so fake an PrivateKey for it
        RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
        RSAPrivateKeySpec spec = new RSAPrivateKeySpec(rsaPublicKey.getModulus(), rsaPublicKey.getPublicExponent());
        Key fakePrivateKey = KeyFactory.getInstance("RSA").generatePrivate(spec);
        cipher = Cipher.getInstance("RSA"); //It is a stateful object. so we need to get new one.
        cipher.init(Cipher.DECRYPT_MODE, fakePrivateKey);
    }

    if (cipherText == null || cipherText.length() == 0) {
        return cipherText;
    }

    byte[] cipherBytes = Base64.base64ToByteArray(cipherText);
    byte[] plainBytes = cipher.doFinal(cipherBytes);

    return new String(plainBytes);
}
 
Example 4
Project: oscm   File: AESEncrypter.java   View Source Code Vote up 6 votes
/**
 * Encrypts a given byte array based on a shared secret.
 *
 * @param bytes
 * @return the encrypted bytes as Base64
 * @throws GeneralSecurityException
 *             on any problem during encryption
 */
public static byte[] encrypt(byte[] bytes) throws GeneralSecurityException {

    SecretKeySpec skeySpec = new SecretKeySpec(
            Base64.decodeBase64(ENCRYPTION_KEY), "AES");

    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

    byte[] encrypted = cipher.doFinal(bytes);
    return Base64.encodeBase64(encrypted);
}
 
Example 5
Project: CryptoVoice   File: Call.java   View Source Code Vote up 5 votes
private byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] data = cipher.doFinal(clear);
    byte[] iv = cipher.getIV();
    byte[] packet = new byte[data.length+iv.length];
    for (int i = 0; i < iv.length; i++)
        packet[i] = iv[i];
    for (int i = 0; i < data.length; i++)
        packet[iv.length+i] = data[i];
    return data;
}
 
Example 6
Project: BankAccount_PasaskevakosG_BootCamp3   File: AdvancedEncryptionStandard.java   View Source Code Vote up 5 votes
/**
 * Decrypt Text
 */
public static String decrypt(String encryptedText) {
    try {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
        SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] cipherText = Base64.getDecoder().decode(encryptedText.getBytes("UTF8"));
        String decryptedString = new String(cipher.doFinal(cipherText), "UTF-8");
        return decryptedString;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 7
Project: jeesupport   File: DESUtils.java   View Source Code Vote up 5 votes
/**
 * 加密
 * 
 * @param _key
 *            密钥
 * @param _dat
 *            待加密数据
 * @return
 * @throws Exception
 */
public static byte[] s_encrypt( byte[] _key , byte[] _dat ) throws Exception {

	// 还原密钥
	Key k = _s_to_key( _key );

	// 实例化
	Cipher cipher = Cipher.getInstance( ALGORITHM );

	// 初始化,设置为加密模式
	cipher.init( Cipher.ENCRYPT_MODE , k );

	// 执行操作
	return cipher.doFinal( _dat );
}
 
Example 8
Project: CacheManage   File: Des3Util.java   View Source Code Vote up 5 votes
/**
 * 加密
 *
 * @param plainText 要加密文字
 * @return 加密文字
 * @throws Exception
 */
public static String encode(String plainText) throws Exception {
    if (TextUtils.isEmpty(secretKey) || TextUtils.isEmpty(iv))
        throw new NullPointerException("u should init first");
    SecretKey deskey = null;
    DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
    SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
    deskey = keyfactory.generateSecret(spec);
    Cipher cipher = Cipher.getInstance(DESEDE_CBC_PKCS5_PADDING);
    IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
    cipher.init(1, deskey, ips);
    byte[] encryptData = cipher.doFinal(plainText.getBytes(encoding));
    return Base64Util.encode(encryptData);
}
 
Example 9
Project: mesh-core-on-android   File: AES128.java   View Source Code Vote up 5 votes
public static byte[] encrypt(byte[] key, byte[] text) throws Exception {      
    SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");      
    Cipher cipher = Cipher.getInstance("AES");      
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);      
    byte[] encrypted = cipher.doFinal(text);      
    return encrypted;      
}
 
Example 10
Project: BreakfastServer   File: EncodeUtils.java   View Source Code Vote up 5 votes
/**
 * AES加密
 * @param content 待加密的内容
 * @param encryptKey 加密密钥
 * @return 加密后的byte[]
 * @throws Exception
 */
public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(128, new SecureRandom(encryptKey.getBytes()));

    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));

    return cipher.doFinal(content.getBytes("utf-8"));
}
 
Example 11
Project: LJFramework   File: RSAUtils.java   View Source Code Vote up 5 votes
/**
 * 用公钥加密 <br>
 * 每次加密的字节数,不能超过密钥的长度值减去11
 *
 * @param data 需加密数据的byte数据
 * @param publicKey 公钥
 * @return 加密后的byte型数据
 */
public static byte[] encryptData(byte[] data, PublicKey publicKey) {
    try {
        Cipher cipher = Cipher.getInstance(RSA);
        // 编码前设定编码方式及密钥
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        // 传入编码数据并返回编码结果
        return cipher.doFinal(data);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 12
Project: PreferenceRoom   File: SecurityUtils.java   View Source Code Vote up 5 votes
public static String decrypt(String input) {
    if(input == null) return null;
    byte[] decrypted = null;
    try{
        SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, skey);
        decrypted = cipher.doFinal(Base64.decode(input, Base64.DEFAULT));
    } catch(Exception e){
        e.printStackTrace();
    }
    return new String(decrypted);
}
 
Example 13
Project: jdk8u-jdk   File: Encrypt.java   View Source Code Vote up 5 votes
private void combination_14(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {
    Cipher c = createCipher(mode, params);
    // prepare ByteBuffer to test
    ByteBuffer buf = ByteBuffer.allocateDirect(AAD.length);
    buf.put(AAD);

    // process the first half of AAD data
    buf.position(0);
    buf.limit(AAD.length / 2);
    c.updateAAD(buf);

    // process the rest of AAD data
    buf.limit(AAD.length);
    c.updateAAD(buf);

    // prepare buffers to encrypt/decrypt
    ByteBuffer in = ByteBuffer.allocate(plainText.length);
    in.put(plainText);
    in.position(0);
    in.limit(plainText.length);
    ByteBuffer out = ByteBuffer.allocate(c.getOutputSize(in.limit()));
    out.position(0);
    out.limit(c.getOutputSize(in.limit()));

    // process input text
    c.update(in, out);
    c.doFinal(in, out);
    int resultSize = out.position();
    byte[] result14 = new byte[resultSize];
    out.position(0);
    out.limit(resultSize);
    out.get(result14, 0, resultSize);
    results.add(result14);
}
 
Example 14
Project: nh-micro   File: DESUtil.java   View Source Code Vote up 5 votes
public static String decrypt(String data) throws Exception {
    Key deskey = keyGenerator(desKey);
    Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
    //初始化Cipher对象,设置为解密模式
    IvParameterSpec iv = new IvParameterSpec(DES_IV);
    AlgorithmParameterSpec paramSpec = iv;        
    cipher.init(Cipher.DECRYPT_MODE, deskey,iv);
    // 执行解密操作
    return new String(cipher.doFinal(Base64.decodeBase64(data)));
}
 
Example 15
Project: jdk8u-jdk   File: AesDkCrypto.java   View Source Code Vote up 4 votes
/**
 * Encrypt AES in CBC-CTS mode using derived keys.
 */
private byte[] encryptCTS(byte[] baseKey, int usage, byte[] ivec,
    byte[] new_ivec, byte[] plaintext, int start, int len,
    boolean confounder_exists)
    throws GeneralSecurityException, KrbCryptoException {

    byte[] Ke = null;
    byte[] Ki = null;

    if (debug) {
        System.err.println("usage: " + usage);
        if (ivec != null) {
            traceOutput("old_state.ivec", ivec, 0, ivec.length);
        }
        traceOutput("plaintext", plaintext, start, Math.min(len, 32));
        traceOutput("baseKey", baseKey, 0, baseKey.length);
    }

    try {
        // derive Encryption key
        byte[] constant = new byte[5];
        constant[0] = (byte) ((usage>>24)&0xff);
        constant[1] = (byte) ((usage>>16)&0xff);
        constant[2] = (byte) ((usage>>8)&0xff);
        constant[3] = (byte) (usage&0xff);
        constant[4] = (byte) 0xaa;
        Ke = dk(baseKey, constant);  // Encryption key

        byte[] toBeEncrypted = null;
        if (confounder_exists) {
            byte[] confounder = Confounder.bytes(BLOCK_SIZE);
            toBeEncrypted = new byte[confounder.length + len];
            System.arraycopy(confounder, 0, toBeEncrypted,
                                    0, confounder.length);
            System.arraycopy(plaintext, start, toBeEncrypted,
                                    confounder.length, len);
        } else {
            toBeEncrypted = new byte[len];
            System.arraycopy(plaintext, start, toBeEncrypted, 0, len);
        }

        // encryptedData + HMAC
        byte[] output = new byte[toBeEncrypted.length + hashSize];

        // AES in JCE
        Cipher cipher = Cipher.getInstance("AES/CTS/NoPadding");
        SecretKeySpec secretKey = new SecretKeySpec(Ke, "AES");
        IvParameterSpec encIv = new IvParameterSpec(ivec, 0, ivec.length);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, encIv);
        cipher.doFinal(toBeEncrypted, 0, toBeEncrypted.length, output);

        // Derive integrity key
        constant[4] = (byte) 0x55;
        Ki = dk(baseKey, constant);
        if (debug) {
            traceOutput("constant", constant, 0, constant.length);
            traceOutput("Ki", Ki, 0, Ke.length);
        }

        // Generate checksum
        // H1 = HMAC(Ki, conf | plaintext | pad)
        byte[] hmac = getHmac(Ki, toBeEncrypted);

        // encryptedData + HMAC
        System.arraycopy(hmac, 0, output, toBeEncrypted.length,
                            hmac.length);
        return output;
    } finally {
        if (Ke != null) {
            Arrays.fill(Ke, 0, Ke.length, (byte) 0);
        }
        if (Ki != null) {
            Arrays.fill(Ki, 0, Ki.length, (byte) 0);
        }
    }
}
 
Example 16
Project: DnsSec-in-Java   File: Dns_Sec2.java   View Source Code Vote up 4 votes
public static String decryptText(String strTodecrypt, String secret) 
{

      // AES defaults to AES/ECB/PKCS5Padding in Java 7
 try
    { 
  setKey(secret);
  
  Cipher aesCipher = Cipher.getInstance("AES");
  
  aesCipher.init(Cipher.DECRYPT_MODE, secretKey);

  return new String(aesCipher.doFinal(Base64.getDecoder().decode(strTodecrypt)));

     

    }

    catch(Exception e)
    {
  	  System.out.println("Error while decrypting: " + e.toString());
    }
  return null;
  }
 
Example 17
Project: outcomes   File: Main.java   View Source Code Vote up 4 votes
private static byte[] rsaEncrypt(byte[] data) throws java.security.GeneralSecurityException {
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    byte[] cipherData = cipher.doFinal(data);
    return cipherData;
}
 
Example 18
Project: openjdk-jdk10   File: PKCS12SameKeyId.java   View Source Code Vote up 4 votes
public static void main(String[] args) throws Exception {

        // Prepare a JKS keystore with many entries
        new File(JKSFILE).delete();
        for (int i=0; i<SIZE; i++) {
            System.err.print(".");
            String cmd = "-keystore " + JKSFILE
                    + " -storepass changeit -keypass changeit -keyalg rsa "
                    + "-genkeypair -alias p" + i + " -dname CN=" + i;
            sun.security.tools.keytool.Main.main(cmd.split(" "));
        }

        // Prepare EncryptedPrivateKeyInfo parameters, copied from various
        // places in PKCS12KeyStore.java
        AlgorithmParameters algParams =
                AlgorithmParameters.getInstance("PBEWithSHA1AndDESede");
        algParams.init(new PBEParameterSpec("12345678".getBytes(), 1024));
        AlgorithmId algid = new AlgorithmId(
                new ObjectIdentifier("1.2.840.113549.1.12.1.3"), algParams);

        PBEKeySpec keySpec = new PBEKeySpec(PASSWORD);
        SecretKeyFactory skFac = SecretKeyFactory.getInstance("PBE");
        SecretKey skey = skFac.generateSecret(keySpec);

        Cipher cipher = Cipher.getInstance("PBEWithSHA1AndDESede");
        cipher.init(Cipher.ENCRYPT_MODE, skey, algParams);

        // Pre-calculated keys and certs and aliases
        byte[][] keys = new byte[SIZE][];
        Certificate[][] certChains = new Certificate[SIZE][];
        String[] aliases = new String[SIZE];

        // Reads from JKS keystore and pre-calculate
        KeyStore ks = KeyStore.getInstance("jks");
        try (FileInputStream fis = new FileInputStream(JKSFILE)) {
            ks.load(fis, PASSWORD);
        }
        for (int i=0; i<SIZE; i++) {
            aliases[i] = "p" + i;
            byte[] enckey = cipher.doFinal(
                    ks.getKey(aliases[i], PASSWORD).getEncoded());
            keys[i] = new EncryptedPrivateKeyInfo(algid, enckey).getEncoded();
            certChains[i] = ks.getCertificateChain(aliases[i]);
        }

        // Write into PKCS12 keystore. Use this overloaded version of
        // setKeyEntry() to be as fast as possible, so that they would
        // have same localKeyId.
        KeyStore p12 = KeyStore.getInstance("pkcs12");
        p12.load(null, PASSWORD);
        for (int i=0; i<SIZE; i++) {
            p12.setKeyEntry(aliases[i], keys[i], certChains[i]);
        }
        try (FileOutputStream fos = new FileOutputStream(P12FILE)) {
            p12.store(fos, PASSWORD);
        }

        // Check private keys still match certs
        p12 = KeyStore.getInstance("pkcs12");
        try (FileInputStream fis = new FileInputStream(P12FILE)) {
            p12.load(fis, PASSWORD);
        }
        for (int i=0; i<SIZE; i++) {
            String a = "p" + i;
            X509Certificate x = (X509Certificate)p12.getCertificate(a);
            X500Name name = (X500Name)x.getSubjectDN();
            if (!name.getCommonName().equals(""+i)) {
                throw new Exception(a + "'s cert is " + name);
            }
        }
    }
 
Example 19
Project: automat   File: DESCoder.java   View Source Code Vote up 3 votes
/**
 * 解密
 * 
 * @param data 待解密数据
 * @param key 密钥
 * @return byte[] 解密数据
 * @throws InvalidKeySpecException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws NoSuchPaddingException
 * @throws BadPaddingException
 * @throws IllegalBlockSizeException
 * @throws Exception
 */
public static byte[] decrypt(byte[] data, byte[] key) throws InvalidKeyException, NoSuchAlgorithmException,
		InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
	// 还原密钥
	Key k = toKey(key);
	// 实例化
	Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
	// 初始化,设置为解密模式
	cipher.init(Cipher.DECRYPT_MODE, k);
	// 执行操作
	return cipher.doFinal(data);
}
 
Example 20
Project: PasswordNotebook   File: EncryptUtil.java   View Source Code Vote up 3 votes
/**
 * <li>
 * 方法名称:TripleDES_CBC_Decrypt</li> <li>
 * 功能描述:
 * <p>
 * <pre>
 * 经过封装的三重DES / CBC解密算法
 * </pre>
 * <p>
 * </li>
 *
 * @param sourceBuf 需要解密内容的字节数组
 * @param deskey    KEY 由24位字节数组通过SecretKeySpec类转换而成。
 * @param ivParam   IV偏转向量,由6位字节数组通过IvParameterSpec类转换而成。
 * @return 解密后的字节数组
 * @throws Exception
 */
public static byte[] TripleDES_CBC_Decrypt(byte[] sourceBuf,
                                           SecretKeySpec deskey, IvParameterSpec ivParam) throws Exception {

    byte[] cipherByte;
    // 获得Cipher实例,使用CBC模式。
    Cipher decrypt = Cipher.getInstance("TripleDES/CBC/PKCS5Padding");
    // 初始化加密实例,定义为解密功能,并传入密钥,偏转向量
    decrypt.init(Cipher.DECRYPT_MODE, deskey, ivParam);

    cipherByte = decrypt.doFinal(sourceBuf, 0, sourceBuf.length);
    // 返回解密后的字节数组
    return cipherByte;
}