/* * Copyright 2015 Rocko (http://rocko.xyz) <rocko.zxp@gmail.com>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package xyz.rocko.security.security.util; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; /** * Created by Administrator on 2015/11/11. */ public class DESUtils { /** * 加密 * * @param bytesContent * 待加密内容 * @param key * 加密的密钥 * @return */ public static byte[] encrypt(byte[] bytesContent, String key) { try { SecureRandom random = new SecureRandom(); DESKeySpec desKey = new DESKeySpec(key.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey securekey = keyFactory.generateSecret(desKey); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, securekey, random); byte[] result = cipher.doFinal(bytesContent); return result; } catch (Throwable e) { e.printStackTrace(); } return null; } /** * 解密 * * @param content * 待解密内容 * @param key * 解密的密钥 * @return */ public static byte[] decrypt(byte[] content, String key) { try { SecureRandom random = new SecureRandom(); DESKeySpec desKey = new DESKeySpec(key.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey securekey = keyFactory.generateSecret(desKey); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.DECRYPT_MODE, securekey, random); return cipher.doFinal(content); } catch (Throwable e) { e.printStackTrace(); } return null; } }