Java examples for Security:Key
encode ECB As Base String
//package com.java2s; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import sun.misc.BASE64Encoder; public class Main { private final static String xform = "DES/ECB/NoPadding"; public static String encodeECBAsBase64String(String key, String plainText) throws Exception { return ecodeBase64(encodeECBBytes(key, plainText)); }/*from w ww. j a v a 2 s.c o m*/ public static String ecodeBase64(byte[] buf) { return (new BASE64Encoder()).encode(buf); } public static byte[] encodeECBBytes(String key, String plainText) throws Exception { SecretKey secretkey = new SecretKeySpec(key.getBytes(), "DES"); return encrypt(plainText.getBytes(), secretkey); } static byte[] encrypt(byte[] inpBytes, SecretKey key) throws Exception { Cipher cipher = Cipher.getInstance(xform); cipher.init(Cipher.ENCRYPT_MODE, key); // 2010/6/22 added by peter, must multiple of 8 bytes return cipher.doFinal(padbyte(inpBytes)); } static byte[] padbyte(byte[] b) { int pad = b.length % 8; if (pad > 0) pad = 8 - pad; byte[] newbytes = new byte[b.length + pad]; for (int i = 0; i < b.length; i++) newbytes[i] = b[i]; for (int i = 0; i < pad; i++) newbytes[b.length + i] = 0; return newbytes; } }