62,616
社区成员
发帖
与我相关
我的任务
分享
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class EncryptSample {
public static void main(String[] args) throws Exception {
String key = "aaaaaaaaaabbbbbb"; // <-128bit key
byte[] keyBytes = key.getBytes(); //
byte[] enBytes = EncryptSample.encryptECB("abcdefg hijklmn".getBytes(),
keyBytes); // "abcdefg hijklmn" key
// System.out.println(new String(enBytes));
byte[] deBytes = EncryptSample.decryptECB(enBytes, keyBytes);
//
System.out.println(new String(deBytes));
//
byte[] bs = Base64.encodeBase64(enBytes, false);
System.out.println(new String(bs));
}
public static byte[] encryptECB(byte[] data, byte[] secret_key) {
SecretKeySpec sKey = new SecretKeySpec(secret_key, "AES");
try {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, sKey);
return cipher.doFinal(data);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return new byte[0];
}
public static byte[] decryptECB(byte[] encData, byte[] secret_key) {
SecretKeySpec sKey = new SecretKeySpec(secret_key, "AES");
try {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, sKey);
return cipher.doFinal(encData);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return new byte[0];
}
}