使用 sha256 散列的 AES 128 加密的 j2me 应用程序的加密/解密

Encryption / decryption for j2me app with AES 128 encryption using sha256 hashing

我必须为j2me 应用程序使用加密/解密机制,经过大量搜索我发现Bouncy Castle 最适合j2me 应用程序。

以下是我执行加密所遵循的步骤:

  1. 获取使用 sha256 算法创建哈希密钥所需的字符串;
  2. 使用该散列密钥对纯文本执行 AES-128 加密。

下面是示例代码。它使用密钥和 IV(初始化向量)来生成加密密钥。它与 sha256 哈希相同吗?

static String strEnc = "String for encryption";
final static String strPassword = "2345678978787878"; // AES 128 -
String encrypted;
public static String strEncResult;
public static String strDcrResult;
public static String keyStr;
String dcrtpt;
String enc1;

//Key key;

/*public static byte[] getSHA256(String key) {
    SHA256Digest digester = new SHA256Digest();
    byte[] retValue = new byte[digester.getDigestSize()];
    digester.update(key.getBytes(), 0, key.length());
    digester.doFinal(retValue, 0);
    System.out.println("retValue === "+retValue);
    return retValue;
}*/


public static byte[] cipherData(PaddedBufferedBlockCipher cipher,
        byte[] data) throws Exception {
    int minSize = cipher.getOutputSize(data.length);
    byte[] outBuf = new byte[minSize];
    int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0);
    int length2 = cipher.doFinal(outBuf, length1);
    int actualLength = length1 + length2;
    byte[] result = new byte[actualLength];
    System.arraycopy(outBuf, 0, result, 0, result.length);
    return result;
}

public static byte[] decrypt(byte[] cipher, byte[] key, byte[] iv)
        throws Exception {
    PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(
            new CBCBlockCipher(new AESEngine()));
    CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key),
            iv);
    aes.init(false, ivAndKey);
    return cipherData(aes, cipher);
}

public static byte[] encrypt(byte[] plain, byte[] key, byte[] iv)
        throws Exception {
    PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(
            new CBCBlockCipher(new AESEngine()));
    CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key),
            iv);
    aes.init(true, ivAndKey);
    return cipherData(aes, plain);
}

public static String encryptMe(String plain){
    byte[] plainStr = plain.getBytes(); 
    byte[] keyStr   = strPassword.getBytes();//getSHA256(strPassword);
    byte[] ivStr    = strPassword.getBytes();//getSHA256(strPassword); 

    try {
        byte[] encBytes = encrypt(plainStr, keyStr,
                ivStr);

        byte[] encbase = Base64.encode(encBytes);
        strEncResult = new String(encbase, "UTF-8");

    } catch (Exception e) {
        e.printStackTrace();
    }

    return strEncResult;
}

public static String decryptMe(String encrtptedStr){

    try {
        byte[] dcrByte = Base64.decode(encrtptedStr.getBytes());
        byte[] dec = decrypt(dcrByte, strPassword.getBytes()/*getSHA256(strPassword)*/,
        strPassword.getBytes()/*getSHA256(strPassword)*/);
        strDcrResult =  new String(dec, "UTF-8");
    } catch (Exception e) {
        e.printStackTrace();
    }


    return strDcrResult;

}

protected void destroyApp(boolean unconditional)
        throws MIDletStateChangeException {

}

protected void pauseApp() {

}

protected void startApp() throws MIDletStateChangeException {

    byte[] enc;

    try {
        enc = encrypt(strEnc.getBytes(), /*getSHA256(strPassword)*/strPassword.getBytes(),
                /*getSHA256(strPassword)*/strPassword.getBytes());
        byte[] encbase = Base64.encode(enc);
        encrypted = new String(encbase, "UTF-8");
        enc1= encryptMe ("String for encryption");
        System.out.println("Encrypted is:" + encbase + "/// "+enc1);
    } catch (Exception e) {
        e.printStackTrace();
    }

    byte[] decbase = Base64.decode(encrypted.getBytes());
    byte[] dec;

    try {
        dec = decrypt(decbase, /*getSHA256(strPassword)*/strPassword.getBytes(),
                /*getSHA256(strPassword)*/strPassword.getBytes());
        dcrtpt =  decryptMe(enc1);
        System.out.println("Decrypted file is:" + new String(dec, "UTF-8")+"///"+dcrtpt);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

我成功了!!我使用 sha256 生成密钥,并首先使用 16 位 进行 AES 128 加密。当它是 16 或低于 16 字符串时,我得到正确的加密和解密数据。如果它超过 16 个字符的字符串,我将得到 16 个字符和一些不需要的字符。 (例如:abcdefghijklmnop5@�D�!�&M�\~C�)谁能帮我解决这个问题。请参阅下面的代码

public static String getSHA256(String key) {
    SHA256Digest digester = new SHA256Digest();
    byte[] retValue = new byte[digester.getDigestSize()];
    digester.update(key.getBytes(), 0, key.length());
    digester.doFinal(retValue,0);

    byteToStr = new String(Hex.encode(retValue));
    System.out.println("byteToStr === " + byteToStr);
    byteToStr = byteToStr.substring(0, 16);
    System.out.println("byteToStr after subString === " + byteToStr);
    return byteToStr;

}

public static byte[] cipherData(BufferedBlockCipher cipher, byte[] data)
        throws Exception {
    int minSize = cipher.getOutputSize(data.length);
    System.out.println("min Size = "+minSize);
    byte[] outBuf = new byte[minSize];
    int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0);
    int length2 = cipher.doFinal(outBuf, length1);
    System.out.println("length1 = "+length1 +"/ length2 = "+length2);
    int actualLength = length1 + length2;
    System.out.println("actualLength = "+actualLength);
    byte[] result = new byte[actualLength];
    System.arraycopy(outBuf, 0, result, 0, result.length);
    return result;

}

public static byte[] decrypt(byte[] cipher, byte[] key/* , byte[] iv */)
        throws Exception {
    /*
     * PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher( new
     * CBCBlockCipher(new AESEngine())); CipherParameters ivAndKey = new
     * ParametersWithIV(new KeyParameter(key), iv); aes.init(false,
     * ivAndKey); return cipherData(aes, cipher);
     */
    BufferedBlockCipher aes = new PaddedBufferedBlockCipher(
            new CBCBlockCipher(new AESEngine()));

    KeyParameter secretKey = new KeyParameter(key);

    aes.init(false, secretKey);
    return cipherData(aes, cipher);

}

public static byte[] encrypt(byte[] plain, byte[] key/* , byte[] iv */)
        throws Exception {
    /*
     * PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher( new
     * CBCBlockCipher(new AESEngine())); CipherParameters ivAndKey = new
     * ParametersWithIV(new KeyParameter(key), iv);
     */

    BufferedBlockCipher aes = new PaddedBufferedBlockCipher(
            new CBCBlockCipher(new AESEngine()));

    KeyParameter secretKey = new KeyParameter(key);
    aes.init(true, secretKey);
    return cipherData(aes, plain);

}

public static String encryptMe(String plain) {
    byte[] plainStr = plain.getBytes();
    byte[] keyStr = getSHA256(key).getBytes();
    // byte[] ivStr = iv.getBytes();//
    System.out.println("key str = "+Strings.fromByteArray(keyStr));

    try {
        byte[] encBytes = encrypt(plainStr, keyStr/*
                                                 * , ivStr
                                                 */);
        strEncResult= Base64.toBase64String(encBytes);
        //strEncResult = new String(encbase);

    } catch (Exception e) {
        e.printStackTrace();
    }

    return strEncResult;
}

public static String decryptMe(String cipherText) {

    try {
        byte[] dcrByte = Base64.decode(cipherText);
        byte[] dec = decrypt(dcrByte, getSHA256(key).getBytes()/*
                                                                 * ,iv.getBytes
                                                                 * ()
                                                                 */);
        strDcrResult = Strings.fromByteArray(dec);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return strDcrResult;

}