/*1、对称加密3DES秘钥生成*/
KeyGenerator kg = KeyGenerator.getInstance("DESede");
kg.init(112);//must be equal to 112 or 168
System.out.println("SecretKey:");
System.out.println(new BASE64Encoder().encode(kg.generateKey().getEncoded()));
/*2、非对称加密RSA公钥和私钥生成*/
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(512);//RSA keys must be at least 512 bits long
KeyPair key = keyGen.generateKeyPair();
System.out.println("PublicKey:");
System.out.println(new BASE64Encoder().encode(key.getPublic().getEncoded()));
System.out.println("PrivateKey:");
System.out.println(new BASE64Encoder().encode(key.getPrivate().getEncoded()));
执行结果(RSA有换行):
SecretKey:
74zQ5ko3QN/Tx2GG/c4+f++M0OZKN0Df
PublicKey:
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIv38xXk06As11OCWq0IPQoQAmz20ZiE8T5KeaMTUbhz
UkGNTAQygApua71R/INeEDNsyyQS4PT6EaWTjJop2rcCAwEAAQ==
PrivateKey:
MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAi/fzFeTToCzXU4JarQg9ChACbPbR
mITxPkp5oxNRuHNSQY1MBDKACm5rvVH8g14QM2zLJBLg9PoRpZOMminatwIDAQABAkBqDAR7FBJb
C15hgSQecV194D9WO3L18dOt9FNQgPSroGVYIvIizp1/wIHpMTN6uHwSoaZQcOqV33gxLF6fKbwx
AiEAv390Q3X2cBjeScxhNbqPiOspE9rYD3eWSajN6Q7ud7UCIQC7HTUZelHMCpv4xPzg6e1QZkWh
Bfuqkhg9aOeAnIW0OwIgLW5Tat3FhXqg4ek29sQ34UfJCwjUUXcRlJATqcL9GDECIQChqe+JzrxD
bVsrCY9vB83JLEO2hwPUcJtO24dBAHsopwIgEV547YcgZ+pyI1dnQhiLJiiFif+h1aBzaIH5mrks
htw=
java对称加密解密实例:
/**算法名称*/
static String ALGORITHM = "DESede";//Blowfish,DESede
/**秘钥,上面生成的*/
static String KEY = "74zQ5ko3QN/Tx2GG/c4+f++M0OZKN0Df";
/**加密*/
String encode(String pass)
{
String str = "";
try {
Key key = new SecretKeySpec(new BASE64Decoder().decodeBuffer(KEY), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
str = new BASE64Encoder().encode(cipher.doFinal(pass.getBytes()));
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
/**解密*/
String decode(String pass)
{
String str = "";
try {
Key key = new SecretKeySpec(new BASE64Decoder().decodeBuffer(KEY), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
str = new String(cipher.doFinal(new BASE64Decoder().decodeBuffer(pass)));
} catch (Exception e) {
e.printStackTrace();
}
return str;
}