哈哈鬼
2016-05-21 14:09
如何实现:提示用户输入字符串,并将字符串加密解密?
可以简单的这样实现:
import java.security.Key; import java.util.Scanner; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import org.apache.commons.codec.binary.Hex; public class TestDES { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("请输入需要加密的内容:"); String src = input.nextLine(); jdkDES(src); input.close(); } public static void jdkDES(String src) { try { //生成key KeyGenerator keyGenerator = KeyGenerator.getInstance("DES"); SecretKey secretKey = keyGenerator.generateKey(); byte[] byteKey = secretKey.getEncoded(); //转换Key DESKeySpec desKeySpec = new DESKeySpec(byteKey); SecretKeyFactory factory = SecretKeyFactory.getInstance("DES"); Key convertSecretKey = factory.generateSecret(desKeySpec); //加密 Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey); byte[] result = cipher.doFinal(src.getBytes()); System.out.println("jdk des encrypt: " + Hex.encodeHexString(result)); //解密 cipher.init(Cipher.DECRYPT_MODE, convertSecretKey); result = cipher.doFinal(result); System.out.println("jdk des decrypt: " + new String(result)); } catch (Exception e) { e.printStackTrace(); } } }
JAVA实现对称加密
31950 学习 · 51 问题