首页 > IT职业 > IT图书 > Java 3DES 加解/密程序
package trades.lib.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
public class Des3Crypt {
private static final String Algorithm = "DESede/ECB/PKCS5Padding";
// private static final String Algorithm = "DES";
// 3DES加密法方法
public static String encrypt(byte[] cipherTextByte) {
SecretKey scKey = null;// 获取密钥key
Cipher cipher = null;// 加解密器
byte[] outputBytes = null;// 加密/解密后的数据包
byte[] inputBytes = cipherTextByte;// 加密/解密前的数据包
try {
DESedeKeySpec desKeySpec = new DESedeKeySpec(
"zhaochenghuitanfangpinga".getBytes("UTF-8"));
SecretKeyFactory keyFactory = SecretKeyFactory
.getInstance("DESede");
scKey = keyFactory.generateSecret(desKeySpec);
cipher = Cipher.getInstance(Algorithm);// 生成解密器
} catch (Exception e) {
e.printStackTrace();
}
String plainTextStr = null;
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(inputBytes);
int opmode = Cipher.ENCRYPT_MODE;
cipher.init(opmode, scKey);
int blockSize = cipher.getBlockSize();
int outputSize = cipher.getOutputSize(blockSize);
byte[] inBytes = new byte[blockSize];
byte[] outBytes = new byte[outputSize];
byte[] appendBytes = new byte[blockSize];
int realLength = 0;
boolean fit = true;
while (fit) {
realLength = in.read(inBytes);
if (realLength == blockSize) {
int ol = cipher.update(inBytes, 0, blockSize, outBytes);
out.write(outBytes, 0, ol);
} else {
fit = false;
}
}
// int outputLength = cipher.doFinal(appendBytes, 0,
// blockSize,outBytes);
if (realLength > 0 && realLength 0) {
outBytes = cipher.doFinal(inBytes, 0, realLength);
} else {
outBytes = cipher.doFinal();
}
// byte[] outBytes=cipher.doFinal(plainTextByte);
out.write(outBytes);
outputBytes = out.toByteArray();
retTextByte = outputBytes;
// System.out.println("3des明文的长度:"+retTextByte.length+"t3des明文:" + new String(retTextByte));
out.flush();
if (in != null)
in.close();
if (out != null)
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return new String(retTextByte);
}
public void init(String key) {
}
public static void main(String[] args) {
String pin1 = "888888";
String pinVlaue = encrypt(pin1.getBytes());
System.out.println(pinVlaue);
String c=decrypt(pinVlaue);
System.out.print(c);
}
} 来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/818/viewspace-2798815/ ,如需转载,请注明出处,否则将追究法律责任。