public class securitykeygenerator{ public static void main(string[] args) throws ioexception, nosuchalgorithmexception, classnotfoundexception, nosuchpaddingexception, invalidkeyexception, illegalblocksizeexception, badpaddingexception { // inputstream in = system.in; // inputstreamreader isr = new inputstreamreader(in); // bufferedreader br = new bufferedreader(isr); // string[] para = br.readline().split(" "); // string s = para[0];// 明文 // int key = integer.parseint(para[1]); // 移动位数 // 创建对称密钥生成器 keygenerator kg = keygenerator.getinstance("desede"); // 指定密钥长度 kg.init(168); // 生成密钥,用于加密和解密 secretkey k = kg.generatekey(); // 将密钥保存到文件中(以对象方式存储) fileoutputstream f = new fileoutputstream("key1.dat"); objectoutputstream b = new objectoutputstream(f); b.writeobject(k); // 获取密钥编码格式(以字节方式存储) byte[] kb = k.getencoded(); // 将编码格式存入文件中 fileoutputstream f2 = new fileoutputstream("keykb1.dat"); f2.write(kb); system.out.println("密钥:"); // 打印密钥编码中的内容 for (int i = 0; i < kb.length; i++) { system.out.print(kb[i] + ","); } // /用密钥加密字符串 // 得到密钥 fileinputstream f22 = new fileinputstream("key1.dat"); objectinputstream b2 = new objectinputstream(f22); key k2 = (key)b2.readobject(); // 初始化密码器,使用desede加密算法,密钥要是使用desede计算出来的密钥 cipher cp = cipher.getinstance("desede"); cp.init(cipher.encrypt_mode, k2); // 将将要加密的明文转换成字节,进行加密 string minwen = "hello world!"; byte ptext[] = minwen.getbytes("utf8"); byte ctext[] = cp.dofinal(ptext); system.out.println(); system.out.println("密文:"); for (int i = 0; i < ctext.length; i++) { system.out.print(ctext[i] + ","); } fileoutputstream fmiwen = new fileoutputstream("senc.dat"); fmiwen.write(ctext); // // /用密钥解密刚才加密的字符串 // 获取密文 fileinputstream fin = new fileinputstream("senc.dat"); int num = fin.available(); byte[] ctextin = new byte[num]; fin.read(ctextin); system.out.println(); system.out.println("读取到的密文是:"); for (int i = 0; i < ctextin.length; i++) { system.out.print(ctextin[i] + ","); } // 获取密钥 fileinputstream f222 = new fileinputstream("keykb1.dat"); int num2 = f222.available(); byte[] keykb = new byte[num2]; f222.read(keykb); secretkeyspec kjiemi = new secretkeyspec(keykb, "desede"); // 对密文进行解密 cipher cpjiemi = cipher.getinstance("desede"); cpjiemi.init(cipher.decrypt_mode, kjiemi); byte[] ptextjiemi = cpjiemi.dofinal(ctextin); string jiemi = new string(ptextjiemi, "utf-8"); system.out.println(); system.out.println("解密后明文:"); system.out.println(jiemi); }}
密钥生成
最新推荐文章于 2024-06-05 09:47:08 发布