Java tutorial
/* * Copyright 2002-2101 SIM group. * * 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 org.demo.show.providers; import java.security.Key; import java.security.Security; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESedeKeySpec; import org.apache.commons.codec.binary.Base64; /** * * @CreateTime 2015424 ?6:03:08 * * @author chao.yu * * @version 1.0 * */ public class ThreeDes2 { /** * * */ public static final String KEY_ALGORITHM = "DESede"; /** * //?/? * */ public static final String CIPHER_ALGORITHM = "DESede/ECB/PKCS5Padding"; /** * * ? * * @return byte[] * */ public static byte[] initkey() throws Exception { // ? KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM); // ?? kg.init(168); // ? SecretKey secretKey = kg.generateKey(); // ??? return secretKey.getEncoded(); } /** * ? * * @param key * * @return Key * */ public static Key toKey(byte[] key) throws Exception { // Des DESedeKeySpec dks = new DESedeKeySpec(key); // SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM); // ? SecretKey secretKey = keyFactory.generateSecret(dks); return secretKey; } /** * ? * * @param data * ? * @param key * * @return byte[] ?? * */ public static byte[] encrypt(byte[] data, byte[] key) throws Exception { // Key k = toKey(key); // Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); // ?? cipher.init(Cipher.ENCRYPT_MODE, k); // ? return cipher.doFinal(data); } /** * ? * * @param data * ? * @param key * * @return byte[] ?? * */ public static byte[] decrypt(byte[] data, byte[] key) throws Exception { // Key k = toKey(key); // Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); // ?? cipher.init(Cipher.DECRYPT_MODE, k); // ? return cipher.doFinal(data); } /** * * * @throws Exception */ public static void main(String[] args) throws Exception { Security.addProvider(new com.sun.crypto.provider.SunJCE()); String str = "DESede"; System.out.println("" + str); // ? byte[] key = ThreeDes2.initkey(); System.out.println("" + new String(Base64.encodeBase64(key))); // ? byte[] data = ThreeDes2.encrypt(str.getBytes(), key); System.out.println("?" + new String(Base64.encodeBase64(data))); // ? data = ThreeDes2.decrypt(data, key); System.out.println("?" + new String(data)); } }