public class UEncrypt { public static void main(String args[]) throws Exception { String data = encrypt() System.out.println(data); System.out.println(desEncrypt(data)); } public static String encrypt() throws Exception { try { String data = "Hi There"; String key = "AjQ0YQ0MvKKC1uTr"; String iv = "AjQ0YQ0MvKKC1uTr"; Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); int blockSize = cipher.getBlockSize(); byte[] dataBytes = data.getBytes(); int plaintextLength = dataBytes.length; if (plaintextLength % blockSize != 0) { plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize)); } byte[] plaintext = new byte[plaintextLength]; System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length); SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES"); IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes()); cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); byte[] encrypted = cipher.doFinal(plaintext); return new sun.misc.BASE64Encoder().encode(encrypted); } catch (Exception e) { } } public static String desEncrypt( String data ) throws Exception { try { String key = "AjQ0YQ0MvKKC1uTr"; String iv = key; byte[] encrypted1 = new BASE64Decoder().decodeBuffer(data); Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES"); IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes()); cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec); byte[] original = cipher.doFinal(encrypted1); String originalString = new String(original); return originalString; } catch (Exception e) { } } }
总结
本文总结了JavaScript, C#, Java三种平台上的AES加密解密算法实现,完整的实现了跨技术栈的加密解密,可以在NodeJS加密,C#解密,希望对大家有所帮助。