Home | 简体中文 | 繁体中文 | 杂文 | Search | ITEYE 博客 | OSChina 博客 | Facebook | Linkedin | 作品与服务 | Email

Chapter 5. AES

Table of Contents

5.1. Java
5.1.1. AES/ECB/PKCS5Padding
5.1.1.1.
5.2. PHP
5.2.1. AES/ECB/PKCS5Padding
5.2.1.1.

5.1. Java

5.1.1. AES/ECB/PKCS5Padding

import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.util.Base64.*; //import org.apache.commons.codec.binary.Base64; /** * @author netkiller * */ public class aes { public static String encrypt(String input, String key) { byte[] crypted = null; try { SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, skey); crypted = cipher.doFinal(input.getBytes()); } catch (Exception e) { System.out.println(e.toString()); } java.util.Base64.Encoder encoder = java.util.Base64.getEncoder(); return new String(encoder.encodeToString(crypted)); } public static String decrypt(String input, String key) { byte[] output = null; try { java.util.Base64.Decoder decoder = java.util.Base64.getDecoder(); SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, skey); output = cipher.doFinal(decoder.decode(input)); } catch (Exception e) { System.out.println(e.toString()); } return new String(output); } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String key = "mvLBiZsiTbGwrfJB"; String data = "ABC"; System.out.println(aes.encrypt(data, key)); System.out.println(aes.decrypt(aes.encrypt(data, key), key)); } }
comments powered by Disqus