Crypt Decrypt密码失败

时间:2014-02-20 16:27:50

标签: java encryption password-encryption

我无法理解为什么此代码无法使用输入 bnlbnl18 引发异常,而不是其他值:

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
/**
 * 
 * @param password
 * @return
 * @throws AuthException 
 */
public static String encryptPassword(String password) throws AuthException{
    byte[] textEncrypted = "".getBytes();
    try{

        DESKeySpec keySpec = new DESKeySpec(Constants.DESkey);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey myDesKey = keyFactory.generateSecret(keySpec);

        Cipher desCipher;

        // Create the cipher 
        //desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        desCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

        AlgorithmParameterSpec alogrithm_specs = new IvParameterSpec(Constants.DESkey);

        // Initialize the cipher for encryption
        desCipher.init(Cipher.ENCRYPT_MODE, myDesKey, alogrithm_specs);

        //sensitive information
        byte[] text = password.getBytes();

        // Encrypt the text
        textEncrypted = desCipher.doFinal(text);

    }catch(NoSuchAlgorithmException e){
        e.printStackTrace();
        logger.error("[AUTH] Auth Exception...there is something wrong at the encryption phase\n" + e.getMessage());
        throw new AuthException("Auth Exception...there is something wrong at the encryption phase");
    }catch(NoSuchPaddingException e){
        e.printStackTrace();
        logger.error("[AUTH] Auth Exception...there is something wrong at the encryption phase\n" + e.getMessage());
        throw new AuthException("Auth Exception...there is something wrong at the encryption phase");
    }catch(InvalidKeyException e){
        e.printStackTrace();
        logger.error("[AUTH] Auth Exception...there is something wrong at the encryption phase\n" + e.getMessage());
        throw new AuthException("Auth Exception...there is something wrong at the encryption phase");
    }catch(IllegalBlockSizeException e){
        e.printStackTrace();
        logger.error("[AUTH] Auth Exception...there is something wrong at the encryption phase\n" + e.getMessage());
        throw new AuthException("Auth Exception...there is something wrong at the encryption phase");
    }catch(BadPaddingException e){
        e.printStackTrace();
        logger.error("[AUTH] Auth Exception...there is something wrong at the encryption phase\n" + e.getMessage());
        throw new AuthException("Auth Exception...there is something wrong at the encryption phase");
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
        logger.error("[AUTH] Auth Exception...there is something wrong at the encryption phase\n" + e.getMessage());
        throw new AuthException("Auth Exception...there is something wrong at the encryption phase");
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
        logger.error("[AUTH] Auth Exception...there is something wrong at the encryption phase\n" + e.getMessage());
        throw new AuthException("Auth Exception...there is something wrong at the encryption phase");
    } 

    return new String(textEncrypted);

}   
public static String decryptPassword(String passwordToDecrypt) throws AuthException{

    DESKeySpec keySpec;
    byte[] textDecrypted = "".getBytes();
    try {
        keySpec = new DESKeySpec(Constants.DESkey);

        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey myDesKey = keyFactory.generateSecret(keySpec);

        Cipher desCipher;

        AlgorithmParameterSpec alogrithm_specs = new IvParameterSpec(Constants.DESkey);

        // Create the cipher 
        //desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        desCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

        // Initialize the same cipher for decryption
        desCipher.init(Cipher.DECRYPT_MODE, myDesKey, alogrithm_specs);

        // Decrypt the text
        byte[] passwordToDecryptByte = passwordToDecrypt.getBytes();



       textDecrypted = desCipher.doFinal(passwordToDecryptByte);

    } catch (InvalidKeyException e) {
        e.printStackTrace();
        logger.error("[AUTH] Auth Exception...there is something wrong at the encryption phase\n" + e.getMessage());
        throw new AuthException("Auth Exception...there is something wrong at the decryption phase");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        logger.error("[AUTH] Auth Exception...there is something wrong at the encryption phase\n" + e.getMessage());
        throw new AuthException("Auth Exception...there is something wrong at the decryption phase");
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
        logger.error("[AUTH] Auth Exception...there is something wrong at the encryption phase\n" + e.getMessage());
        throw new AuthException("Auth Exception...there is something wrong at the decryption phase");
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
        logger.error("[AUTH] Auth Exception...there is something wrong at the encryption phase\n" + e.getMessage());
        throw new AuthException("Auth Exception...there is something wrong at the decryption phase");
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
        logger.error("[AUTH] Auth Exception...there is something wrong at the encryption phase\n" + e.getMessage());
        throw new AuthException("Auth Exception...there is something wrong at the decryption phase");
    } catch (BadPaddingException e) {
        e.printStackTrace();
        logger.error("Auth Exception...there is something wrong at the encryption phase\n" + e.getMessage());
        throw new AuthException("Auth Exception...there is something wrong at the decryption phase");
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
        logger.error("[AUTH] Auth Exception...there is something wrong at the encryption phase\n" + e.getMessage());
        throw new AuthException("Auth Exception...there is something wrong at the decryption phase");
    }

    return new String(textDecrypted);

}


public static void main(String[] args) throws AuthException, UnsupportedEncodingException{
    String password = URLEncoder.encode(encryptPassword("bnlbnl18"), "UTF-8");

    System.out.println("\"" + URLDecoder.decode(password, "UTF-8") + "\"" + decryptPassword(URLDecoder.decode(password,"UTF-8")));

}

这是例外

javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:811)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:676)
at com.sun.crypto.provider.DESCipher.engineDoFinal(DESCipher.java:314)
at javax.crypto.Cipher.doFinal(Cipher.java:2087)
    ...

我想我错过了什么。行为很奇怪。你有什么想法? “DES”解决方案是错误的吗?

提前致谢。

2 个答案:

答案 0 :(得分:0)

您正在使用

将包含任何类型字节的字节数组转换为字符串
new String(bytes);

此构造函数要求字节表示使用默认平台编码转换为字节的字符,并且很有可能不是这种情况。不要使用String来表示二进制数据?将其保留为字节数组。或者使用Hex或Base64编码对字节数组进行编码。

答案 1 :(得分:0)

@JB Nizet:按照您的指示,这里是代码

/**
 * 
 * @param password
 * @return
 * @throws AuthException 
 * @throws UnsupportedEncodingException 
 */
public static String encryptPassword(String password) throws AuthException, UnsupportedEncodingException{
    byte[] textEncrypted = "".getBytes();
    try{

        DESKeySpec keySpec = new DESKeySpec(Constants.DESkey);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey myDesKey = keyFactory.generateSecret(keySpec);

        Cipher desCipher;

        // Create the cipher 
        desCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

        AlgorithmParameterSpec alogrithm_specs = new IvParameterSpec(Constants.DESkey);

        // Initialize the cipher for encryption
        desCipher.init(Cipher.ENCRYPT_MODE, myDesKey, alogrithm_specs);

        //sensitive information
        byte[] text = password.getBytes("UTF-8");

        // Encrypt the text
        textEncrypted = desCipher.doFinal(text);

    }catch(NoSuchAlgorithmException e){
        e.printStackTrace();
        logger.error("[AUTH] Auth Exception...there is something wrong at the encryption phase\n" + e.getMessage());
        throw new AuthException("Auth Exception...there is something wrong at the encryption phase");
    }catch(NoSuchPaddingException e){
        e.printStackTrace();
        logger.error("[AUTH] Auth Exception...there is something wrong at the encryption phase\n" + e.getMessage());
        throw new AuthException("Auth Exception...there is something wrong at the encryption phase");
    }catch(InvalidKeyException e){
        e.printStackTrace();
        logger.error("[AUTH] Auth Exception...there is something wrong at the encryption phase\n" + e.getMessage());
        throw new AuthException("Auth Exception...there is something wrong at the encryption phase");
    }catch(IllegalBlockSizeException e){
        e.printStackTrace();
        logger.error("[AUTH] Auth Exception...there is something wrong at the encryption phase\n" + e.getMessage());
        throw new AuthException("Auth Exception...there is something wrong at the encryption phase");
    }catch(BadPaddingException e){
        e.printStackTrace();
        logger.error("[AUTH] Auth Exception...there is something wrong at the encryption phase\n" + e.getMessage());
        throw new AuthException("Auth Exception...there is something wrong at the encryption phase");
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
        logger.error("[AUTH] Auth Exception...there is something wrong at the encryption phase\n" + e.getMessage());
        throw new AuthException("Auth Exception...there is something wrong at the encryption phase");
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
        logger.error("[AUTH] Auth Exception...there is something wrong at the encryption phase\n" + e.getMessage());
        throw new AuthException("Auth Exception...there is something wrong at the encryption phase");
    } 

    return BaseEncoding.base64().encode(textEncrypted);

}   

/**
 * 
 * @param passwordDecrypted
 * @return
 * @throws AuthException 
 * @throws UnsupportedEncodingException 
 */

public static String decryptPassword(String passwordToDecrypt) throws AuthException, UnsupportedEncodingException{

    DESKeySpec keySpec;
    byte[] textDecrypted = "".getBytes();
    try {
        keySpec = new DESKeySpec(Constants.DESkey);

        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey myDesKey = keyFactory.generateSecret(keySpec);

        Cipher desCipher;

        AlgorithmParameterSpec alogrithm_specs = new IvParameterSpec(Constants.DESkey);

        // Create the cipher 
        //desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        desCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

        // Initialize the same cipher for decryption
        desCipher.init(Cipher.DECRYPT_MODE, myDesKey, alogrithm_specs);

        // Decrypt the text
        byte[] passwordToDecryptByte = BaseEncoding.base64().decode(passwordToDecrypt);

       textDecrypted = desCipher.doFinal(passwordToDecryptByte);

    } catch (InvalidKeyException e) {
        e.printStackTrace();
        logger.error("[AUTH] Auth Exception...there is something wrong at the encryption phase\n" + e.getMessage());
        throw new AuthException("Auth Exception...there is something wrong at the decryption phase");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        logger.error("[AUTH] Auth Exception...there is something wrong at the encryption phase\n" + e.getMessage());
        throw new AuthException("Auth Exception...there is something wrong at the decryption phase");
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
        logger.error("[AUTH] Auth Exception...there is something wrong at the encryption phase\n" + e.getMessage());
        throw new AuthException("Auth Exception...there is something wrong at the decryption phase");
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
        logger.error("[AUTH] Auth Exception...there is something wrong at the encryption phase\n" + e.getMessage());
        throw new AuthException("Auth Exception...there is something wrong at the decryption phase");
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
        logger.error("[AUTH] Auth Exception...there is something wrong at the encryption phase\n" + e.getMessage());
        throw new AuthException("Auth Exception...there is something wrong at the decryption phase");
    } catch (BadPaddingException e) {
        e.printStackTrace();
        logger.error("Auth Exception...there is something wrong at the encryption phase\n" + e.getMessage());
        throw new AuthException("Auth Exception...there is something wrong at the decryption phase");
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
        logger.error("[AUTH] Auth Exception...there is something wrong at the encryption phase\n" + e.getMessage());
        throw new AuthException("Auth Exception...there is something wrong at the decryption phase");
    }

    return new String(textDecrypted);


}


public static void main(String[] args) throws AuthException, UnsupportedEncodingException{
    String password = encryptPassword("testtest19");

    System.out.println(password + " --> " + "\"" + decryptPassword(password)+ "\"");

}