java jce 非对称加密算法范例(jdk1.6)
java jce 非对称加密算法实例(jdk1.6)
[size=medium]
[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]