`
youyun_2008
  • 浏览: 110173 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

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

阅读更多
[size=medium]
package com.simon.security;

import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;

import javax.crypto.Cipher;

public class JcePairTest {

	public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException, UnsupportedEncodingException{
		KeyPairGenerator kpg = null;
		kpg = KeyPairGenerator.getInstance("RSA");
		kpg.initialize(1024, new SecureRandom());
		KeyPair kp = kpg.generateKeyPair();
		PrivateKey priKey = kp.getPrivate();
		PublicKey pubKey = kp.getPublic(); 
		byte[] encode = getEncCode(new String("hello").getBytes(), pubKey);
		byte[] decode = getDesCode(encode, priKey);
		
		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("RSA");
			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("RSA");
			cipher.init(Cipher.DECRYPT_MODE, key);
			byteFina = cipher.doFinal(byteD);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			cipher = null;
		}
		return byteFina;

	}
}
[/size]
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics