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

时间:2015-02-19 08:39:53

标签: encryption java-me cryptography aes sha256

我必须使用加密/解密机制来进行j2me应用程序和大量搜索我发现Bouncy Castle最适合j2me应用程序。

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

  1. 使用sha256算法获取创建哈希键所需的字符串;
  2. 使用该哈希密钥对纯文本执行AES-128加密。
  3. 以下是示例代码。它使用密钥和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();
        }
    
    }
    

1 个答案:

答案 0 :(得分:0)

我搞定了!!我使用 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;

}