将基于Android Java的AES编码移植到Qt Android

时间:2017-11-23 10:30:30

标签: java android c++ qt encryption

我使用Java编写了一个Android应用程序,它使用java类进行加密。以下是java代码的基本要点:

这是我初始化所有内容的方式:

// Constants
private final static String encoding = "UTF-8";
private final static String algorithm = "AES/CBC/PKCS5Padding";
private final static int NCHARS = 16;

// Private variables
private byte[] rawdata;
private byte[] keyBytes;
private String status;
private String fileName;

// AES Variables
private static Cipher cipher;
private static SecretKeySpec secretKeySpec;
private static IvParameterSpec ivParameterSpec;

//====================== AES Engine intialization ======================
public AESCrypt (String passwd,String datafile){

    // Initializing variables.
    rawdata = null;
    status = "";
    fileName = datafile;

    // Transforming the passwd to 16 bytes.
    try {
        MessageDigest digester = MessageDigest.getInstance("MD5");
        InputStream in = new ByteArrayInputStream(Charset.forName(encoding).encode(passwd).array());
        byte[] buffer = new byte[NCHARS];
        int byteCount;
        while ((byteCount = in.read(buffer)) > 0) {
            digester.update(buffer, 0, byteCount);
        }
        keyBytes = digester.digest();
    }
    catch(Exception e){
        status = "Error in key generation: " + e.toString();
    }

    // Initilizing the crypto engine
    try {
        cipher = Cipher.getInstance(algorithm);
    }
    catch(Exception e){
        status = "Error in intialization: " + e.toString();
    }
    secretKeySpec = new SecretKeySpec(keyBytes, "AES");
    ivParameterSpec = new IvParameterSpec(keyBytes);

}

这是我解密的方式:

//====================== AES Decryption ======================
public String decrypt(){
    status = "";
    String data = "";

    // Opening the file for reading
    byte[] eBytes = null;
    try{
        DataInputStream fis = new DataInputStream(new FileInputStream(fileName));

        // Reading the size of the written files
        int size = fis.readInt();

        // Reading the rest of the file
        eBytes = new byte[size];
        fis.readFully(eBytes);
        fis.close();

    }
    catch(Exception e){
        status = "Error reading the file: " + e.toString();
    }

    if (!status.isEmpty()) return data;

    // The data is read and it is now decrypted.
    try{
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
        rawdata = cipher.doFinal(eBytes);
        data = new String(rawdata,encoding);
    }
    catch(Exception e){
        status = "Error decrypting the file: " + e.toString();
    }

    return data;
}

这能够解密由(此处未显示)加密功能加密的文件。问题是我现在想要使用Qt for Android做同样的事情。由于这将是同一App的新版本它需要处理现有的加密文件。所以...我需要使用Qt for Android在C ++中重现这一点。现在AES本身就很容易了。它是一个标准,有很多实现。问题是在它上面使用的所有准备功能/算法,我不知道做什么(例如IvParameterSpec,SecretKeySpec或什么是PKCS5Padding)。

但是我一直在阅读有关QAndroidJniObject的内容。是否可以使用它并按原样从C ++ / Qt调用此代码?如果是这样,任何人都可以举例说明如何?或者也许是关于如何解决这个问题的建议?

0 个答案:

没有答案