对称密钥
EncryptDecryptData.java:
package com.cjq.save;import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import javax.crypto.SecretKey;//对称密钥public class EncryptDecryptData { static String plaintext = "12345678123456781234567812345678"; public static void main(String[] args) throws Exception { System.out.println("明文"); System.out.println(plaintext); //转换为字节数组,指定字符串特征为UTF8,以使不同平台加、解密时不引起错误 byte[] plaintext1 = plaintext.getBytes("UTF8"); //创建一个密钥生成器对象,加密算法为DESede KeyGenerator keygen = KeyGenerator.getInstance("DESede"); keygen.init(168); //获得密钥 SecretKey secretkey = keygen.generateKey(); byte[] kb = secretkey.getEncoded();// int i=0; System.out.println("密钥:"); for(int i=0;i
非对称密钥
RSAEncryptData.java
package com.cjq.save;import java.io.FileOutputStream;import java.io.ObjectOutputStream;import java.math.BigInteger;import java.security.KeyPair;import java.security.KeyPairGenerator;import java.security.PrivateKey;import java.security.PublicKey;import java.security.interfaces.RSAPrivateKey;import java.security.interfaces.RSAPublicKey;//非对称密钥public class RSAEncryptData { public static void main(String[] args) throws Exception{ //创建一个密钥生成器对象,选择加密算法RSA KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA"); //初始化对象生成器,RSA密钥长度510-2048 keygen.initialize(1024); //生成密钥对 KeyPair kp = keygen.genKeyPair(); //获得公钥 PublicKey pbk = kp.getPublic(); //获得私钥 PrivateKey pvk = kp.getPrivate(); //建立文件rsapbkey.dat输出流,保存公钥 FileOutputStream fout = new FileOutputStream("rsapbkey.dat"); //建立文件对象输出流 ObjectOutputStream oout = new ObjectOutputStream(fout); //向文件rsapbkey.dat输出对象obj oout.writeObject(pbk); oout.close(); //建立文件rsapykey.dat输出流,保存私钥 FileOutputStream foutv= new FileOutputStream("rsapykey.dat"); //建立文件对象输出流 ObjectOutputStream ooutb = new ObjectOutputStream(foutv); //向文件rsapykey.dat输出对象 ooutb.writeObject(pvk); ooutb.close(); //获得公钥,计算指数e和模数n RSAPublicKey rsapbk = (RSAPublicKey)kp.getPublic(); BigInteger e = rsapbk.getPublicExponent(); BigInteger n = rsapbk.getModulus(); String ptext="I have a friend!"; byte[] pb = ptext.getBytes("UTF8"); BigInteger m =new BigInteger(pb); //执行计算,返回密文 BigInteger bi = m.modPow(e, n); System.out.println("bi="+bi); //获得私钥参数及解密 RSAPrivateKey rsapvk = (RSAPrivateKey)kp.getPrivate(); BigInteger dv = rsapvk.getPrivateExponent(); BigInteger mv = rsapvk.getModulus(); //执行计算,即解密 BigInteger mm = bi.modPow(dv, mv); byte[] mt = mm.toByteArray(); for(int i=0;i