[JS]java加密封装和php加密封装
[JS]java加密封装和php加密封装
java代码
- import java.io.IOException;
- import java.security.SecureRandom;
- import javax.crypto.Cipher;
- import javax.crypto.SecretKey;
- import javax.crypto.SecretKeyFactory;
- import javax.crypto.spec.DESKeySpec;
- import sun.misc.BASE64Decoder;
- import sun.misc.BASE64Encoder;
- public class DES {
- private byte[] desKey;
- public DES(String desKey) {
- this.desKey = desKey.getBytes();
- }
- public byte[] desEncrypt(byte[] plainText) throws Exception {
- SecureRandom sr = new SecureRandom();
- byte rawKeyData[] = desKey;
- DESKeySpec dks = new DESKeySpec(rawKeyData);
- SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
- SecretKey key = keyFactory.generateSecret(dks);
- Cipher cipher = Cipher.getInstance("DES");
- cipher.init(Cipher.ENCRYPT_MODE, key, sr);
- byte data[] = plainText;
- byte encryptedData[] = cipher.doFinal(data);
- return encryptedData;
- }
- public byte[] desDecrypt(byte[] encryptText) throws Exception {
- SecureRandom sr = new SecureRandom();
- byte rawKeyData[] = desKey;
- DESKeySpec dks = new DESKeySpec(rawKeyData);
- SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
- SecretKey key = keyFactory.generateSecret(dks);
- Cipher cipher = Cipher.getInstance("DES");
- cipher.init(Cipher.DECRYPT_MODE, key, sr);
- byte encryptedData[] = encryptText;
- byte decryptedData[] = cipher.doFinal(encryptedData);
- return decryptedData;
- }
- public String encrypt(String input) throws Exception {
- return base64Encode(desEncrypt(input.getBytes()));
- }
- public String decrypt(String input) throws Exception {
- byte[] result = base64Decode(input);
- return new String(desDecrypt(result));
- }
- public static String base64Encode(byte[] s) {
- if (s == null)
- return null;
- BASE64Encoder b = new sun.misc.BASE64Encoder();
- return b.encode(s);
- }
- public static byte[] base64Decode(String s) throws IOException {
- if (s == null)
- return null;
- BASE64Decoder decoder = new BASE64Decoder();
- byte[] b = decoder.decodeBuffer(s);
- return b;
- }
- public static void main(String[] args) throws Exception {
- String key = "abcdefgh";
- String input = "a";
- DES crypt = new DES(key);
- System.out.println("Encode:" + crypt.encrypt(input));
- System.out.println("Decode:" + crypt.decrypt(crypt.encrypt(input)));
- }
- }
热门文章推荐
- [JS]window.location获取url各项参数详解
- [JS]jQuery,javascript获得网页的高度和宽度
- [JS]视频弹窗视频弹出层videoLightBox(含三种播放器的用法)
- [JS]JS提交中文encodeURI两次转码
- [JS]js版方面encodeURI转码和decodeURI解码的用法实例
- [JS]js取当前机子的时间戳实例
- [JS]AES加密(基于crypto-js)PHP后端解密
- [JS]data:image/png;base64写法的用途及说明
请稍候...