AES 256 in Blackberry

风格不统一 提交于 2019-12-04 22:55:41

This gave me "wQVge+rn7HGVs17a82GKTw==". Enjoy:

private static byte[] encrypt(byte[] keyData, byte[] data)
        throws CryptoException, IOException {
    // Create the AES key to use for encrypting the data.
    // This will create an AES key using as much of the keyData
    // as possible.
    AESKey key = new AESKey(keyData);

    // Now, we want to encrypt the data.
    // First, create the encryptor engine that we use for the actual
    // encrypting of the data.
    AESEncryptorEngine engine = new AESEncryptorEngine(key);

    // Since we cannot guarantee that the data will be of an equal block
    // length we want to use a padding engine (PKCS5 in this case).
    PKCS5FormatterEngine fengine = new PKCS5FormatterEngine(engine);

    // Create a BlockEncryptor to hide the engine details away.
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    BlockEncryptor encryptor = new BlockEncryptor(fengine, output);

    encryptor.write(data);
    encryptor.close();
    output.close();

    // Now, the encrypted data is sitting in the ByteArrayOutputStream.
    // We simply want to retrieve it.
    return output.toByteArray();
}

.... somewhere else

byte[] keyData = "@mbe0RcM$@mbe0RcM$@mbe0RcM$@mbe0".getBytes(); 
byte[] data = "S2526".getBytes();
byte[] encryptedInAES;
try {
    encryptedInAES = encrypt(keyData, data);
} catch (Exception e) {
    Dialog.alert("Failed to AES: " + e);
    return;
}

byte[] encodedInBase64 = null;
try {
    encodedInBase64 = Base64OutputStream.encode(
        encryptedInAES, 0, encryptedInAES.length, false, false
    );
} catch (IOException e) {
    Dialog.alert("Failed to Base64: " + e);
    return;
}

try {
    String encodedStr = new String(encodedInBase64, "UTF-8");
    Dialog.alert("Result: " + encodedStr);
} catch (UnsupportedEncodingException ignored) {}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!