简单的Java AES加密/解密示例 [英] Simple Java AES encrypt/decrypt example

查看:78
本文介绍了简单的Java AES加密/解密示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下示例有什么问题?



问题是解密字符串的第一部分是废话。但是,其余的都是罚款,我得到...


 结果:£eB6O geS妳是吗祝你今天愉快。 




  @Test 
public void testEncrypt(){
try {
String s =你好,你好吗?有一个美好的一天。

//生成键
KeyGenerator kgen = KeyGenerator.getInstance(AES);
kgen.init(128);
SecretKey aesKey = kgen.generateKey();

//加密密码
密码encryptionCipher = Cipher.getInstance(AES / CBC / PKCS5Padding);
encryptCipher.init(Cipher.ENCRYPT_MODE,aesKey);

//加密
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream,encryptCipher);
cipherOutputStream.write(s.getBytes());
cipherOutputStream.flush();
cipherOutputStream.close();
byte [] encryptedBytes = outputStream.toByteArray();

//解密密码
密码解密Cipher = Cipher.getInstance(AES / CBC / PKCS5Padding);
IvParameterSpec ivParameterSpec = new IvParameterSpec(aesKey.getEncoded());
decryptCipher.init(Cipher.DECRYPT_MODE,aesKey,ivParameterSpec);

//解密
outputStream = new ByteArrayOutputStream();
ByteArrayInputStream inStream = new ByteArrayInputStream(encryptedBytes);
CipherInputStream cipherInputStream = new CipherInputStream(inStream,decryptCipher);
byte [] buf = new byte [1024];
int bytesRead;
while((bytesRead = cipherInputStream.read(buf))> = 0){
outputStream.write(buf,0,bytesRead);
}

System.out.println(Result:+ new String(outputStream.toByteArray()));

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


解决方案

包括我自己在内的很多问题都是因为丢失了一些信息,如遗忘转换为Base64,初始化向量,字符集等等,所以我想到了一个功能完整的代码。



希望这将对你有用:
要编译需要额外的Apache Commons Codec jar,可以在这里找到:
http://commons.apache.org/proper/commons-codec/download_codec.cgi

  import javax.crypto.Cipher; 
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class Encryptor {
public static String encrypt(String key,String initVector,String value){
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes ( UTF-8));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(UTF-8),AES);

密码密码= Cipher.getInstance(AES / CBC / PKCS5PADDING);
cipher.init(Cipher.ENCRYPT_MODE,skeySpec,iv);

byte [] encrypted = cipher.doFinal(value.getBytes());
System.out.println(encrypted string:
+ Base64.encodeBase64String(encrypted));

返回Base64.encodeBase64String(加密);
} catch(Exception ex){
ex.printStackTrace();
}

返回null;


public static String decrypt(String key,String initVector,String encrypted){
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes(UTF -8\" ));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(UTF-8),AES);

密码密码= Cipher.getInstance(AES / CBC / PKCS5PADDING);
cipher.init(Cipher.DECRYPT_MODE,skeySpec,iv);

byte [] original = cipher.doFinal(Base64.decodeBase64(encrypted));

return new String(original);
} catch(Exception ex){
ex.printStackTrace();
}

返回null;
}

public static void main(String [] args){
String key =Bar12345Bar12345; // 128位键
String initVector =RandomInitVector; // 16 bytes IV

System.out.println(decrypt(key,initVector,
encrypt(key,initVector,Hello World)));
}
}


What's wrong with the following example?

The problem is that the first part of the decrypted string is nonsense. However, the rest is fine, I get...

Result: `£eB6O�geS��i are you? Have a nice day.

@Test
public void testEncrypt() {
  try {
    String s = "Hello there. How are you? Have a nice day.";

    // Generate key
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(128);
    SecretKey aesKey = kgen.generateKey();

    // Encrypt cipher
    Cipher encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    encryptCipher.init(Cipher.ENCRYPT_MODE, aesKey);

    // Encrypt
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, encryptCipher);
    cipherOutputStream.write(s.getBytes());
    cipherOutputStream.flush();
    cipherOutputStream.close();
    byte[] encryptedBytes = outputStream.toByteArray();

    // Decrypt cipher
    Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    IvParameterSpec ivParameterSpec = new IvParameterSpec(aesKey.getEncoded());
    decryptCipher.init(Cipher.DECRYPT_MODE, aesKey, ivParameterSpec);

    // Decrypt
    outputStream = new ByteArrayOutputStream();
    ByteArrayInputStream inStream = new ByteArrayInputStream(encryptedBytes);
    CipherInputStream cipherInputStream = new CipherInputStream(inStream, decryptCipher);
    byte[] buf = new byte[1024];
    int bytesRead;
    while ((bytesRead = cipherInputStream.read(buf)) >= 0) {
        outputStream.write(buf, 0, bytesRead);
    }

    System.out.println("Result: " + new String(outputStream.toByteArray()));

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

解决方案

Lot of people including myself face lot of issues in making this work due to missing some information like, forgetting to convert to Base64, initialization vectors, character set, etc. So I thought of making a fully functional code.

Hope this will be useful to you all: To compile you need additional Apache Commons Codec jar, which is available here: http://commons.apache.org/proper/commons-codec/download_codec.cgi

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class Encryptor {
    public static String encrypt(String key, String initVector, String value) {
        try {
            IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

            byte[] encrypted = cipher.doFinal(value.getBytes());
            System.out.println("encrypted string: "
                    + Base64.encodeBase64String(encrypted));

            return Base64.encodeBase64String(encrypted);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    public static String decrypt(String key, String initVector, String encrypted) {
        try {
            IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

            byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));

            return new String(original);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    public static void main(String[] args) {
        String key = "Bar12345Bar12345"; // 128 bit key
        String initVector = "RandomInitVector"; // 16 bytes IV

        System.out.println(decrypt(key, initVector,
                encrypt(key, initVector, "Hello World")));
    }
}

这篇关于简单的Java AES加密/解密示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆