最近需要实现一个数据加密,要求aes算法cbc模式进行补码,之后进行hex输出,因为整体数据是用perl来出的,perl算法不好实现,于是用java实现,以下为样例代码(初学java,代码只为实现功能,仅供参考,勿喷):
package aes1;
import java.io.UnsupportedEncodingException;
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.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class aes {
public static void main(String[] args) throws InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
// TODO Auto-generated method stub
// 需要加密的字串
String cSrc = "6229760080104365243";
//String cSrc = args[0];
// 加密需要的key
String cKey = "ALLINPAYRISKERR0";
// 初始向量IV
String cIv = "0000000000000000";
// 加密
String enString = aes.Encrypt(cSrc, cKey, cIv);
System.out.println(enString);
}
private static String Encrypt(String sSrc, String sKey, String sIv) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
// TODO Auto-generated method stub
String result;//返回值
if (sKey == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = sKey.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"算法/模式/补码方式"
IvParameterSpec iv = new IvParameterSpec(sIv.getBytes());//使用CBC模式,需要一个向量iv,可增加加密算法的强度
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(sSrc.getBytes());
//return new Base64().encode(encrypted);//此处使用BASE64做转码功能,同时能起到2次加密的作用。
result = byteToHex(encrypted);//byte 转换成16进制输出
return result;
}
private static String byteToHex(byte[] bytes) {
// TODO Auto-generated method stub
StringBuffer sb = new StringBuffer();
for(int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(bytes[i] & 0xFF);
if(hex.length() < 2){
sb.append(0);
}
sb.append(hex);
}
return sb.toString();
}
}
测试后代码通过,打成jar包,上传到服务器,在perl脚本中通过系统命令运行jar包,输出加密结果,搞定 。