자바 jce 대칭 암호 화 알고리즘 인 스 턴 스 (jdk 1.6)

1825 단어
[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]

좋은 웹페이지 즐겨찾기