java jce 对称加密算法实例(jdk1.6)

[size=medium]
package com.simon.security;

import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class JceTest {
public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException{
KeyGenerator kg = KeyGenerator.getInstance("DES");
// AES 要求密钥长度为128位、192位或256位。
kg.init(56);
// 生成秘密密钥
SecretKey secretKey = kg.generateKey();
byte[] key = secretKey.getEncoded();
System.out.println(secretKey);
System.out.println(key);
byte[] encode = getEncCode(new String("hello").getBytes(), secretKey);
byte[] decode = getDesCode(encode, secretKey);

System.out.println( encode );
System.out.println( new String(decode,"UTF-8") );
}

public static byte[] getEncCode(byte[] byteS, Key key) {
byte[] byteFina = null;
Cipher cipher;
try {
cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byteFina = cipher.doFinal(byteS);
} catch (Exception e) {
e.printStackTrace();
} finally {
cipher = null;
}
return byteFina;
}

public static byte[] getDesCode(byte[] byteD , Key key) {
Cipher cipher;
byte[] byteFina = null;
try {
cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, key);
byteFina = cipher.doFinal(byteD);
} catch (Exception e) {
e.printStackTrace();
} finally {
cipher = null;
}
return byteFina;

}
}
[/size]

你可能感兴趣的:(java jce 对称加密算法实例(jdk1.6))