使用Java SecretKeySpec解密

时间:2014-09-09 22:47:03

标签: java encryption aes

我不知道出了什么问题,但是我用密钥加密图像,但是当我使用相同的密钥对其进行解密时,它不起作用,我猜问题是在SecretKeySpec()中这些是方法crypt和decrypt

public void crypt() throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IOException{
    Cipher cipher = Cipher.getInstance("AES");
    // Encrypt

    byte [] data = {90, 52, 50, 52, 48, 54, 54, 51, 52, 51, 50, 51, 49, 51, 54, 51};
    System.out.println(Arrays.toString(data));
    SecretKey originalKey = new SecretKeySpec(data, 0, data.length, "AES");
    System.out.println(Arrays.toString(originalKey.getEncoded())+data);
    cipher.init(Cipher.ENCRYPT_MODE, originalKey);
    System.out.println(Arrays.toString(originalKey.getEncoded())+data);
    String cleartextFile = this.lien;
    String ciphertextFile = this.lien;

    FileInputStream fis = new FileInputStream(cleartextFile);
    FileOutputStream fos = new FileOutputStream(ciphertextFile);
    CipherOutputStream cos = new CipherOutputStream(fos, cipher);

    int i;
    while ((i = fis.read()) != -1) {
        cos.write(i);
    }
    cos.close();
}

    // Decrypt
public void decrypt() throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IOException{

        //csetCodeCrypt(result.getBytes(6));
        byte [] data = {90, 52, 50, 52, 48, 54, 54, 51, 52, 51, 50, 51, 49, 51, 54, 51};
    Cipher cipher = Cipher.getInstance("AES");
    SecretKey originalKey = new SecretKeySpec(data, 0, data.length, "AES");
    System.out.println(Arrays.toString(originalKey.getEncoded()));
    cipher.init(Cipher.DECRYPT_MODE, originalKey);
    System.out.println(Arrays.toString(originalKey.getEncoded()));
    String cleartextFile = this.lien;
    String ciphertextFile = this.lien;

    FileInputStream fis = new FileInputStream(ciphertextFile);
    FileOutputStream fos = new FileOutputStream(cleartextFile);
    CipherOutputStream cos = new CipherOutputStream(fos, cipher);

    int i;
    while ((i = fis.read()) != -1) {
        cos.write(i);
    }
    cos.close();
}

}

这是在主

中使用这些方法
image.crypt();
image.decrypt();

结果如下:

[90, 52, 50, 52, 48, 54, 54, 51, 52, 51, 50, 51, 49, 51, 54, 51][B@ed5d9d 

[90, 52, 50, 52, 48, 54, 54, 51, 52, 51, 50, 51, 49, 51, 54, 51][B@ed5d9d

[90, 52, 50, 52, 48, 54, 54, 51, 52, 51, 50, 51, 49, 51, 54, 51]

[90, 52, 50, 52, 48, 54, 54, 51, 52, 51, 50, 51, 49, 51, 54, 51]

我所做的是使用相同的密钥同时加密和解密图像,但图像只是加密,我再也看不懂了。

编译此代码时,我不会遇到错误。

1 个答案:

答案 0 :(得分:0)

无法重现。

注意:如果使用缓冲I / O,则此代码的效率会更高:

int count;
byte[] buffer = new byte[8192; // or more if you like
while ((count = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
}

两端。