比较常见的是RSA(适用于对少量数据加密)和DSA(一般用于数字签名中)。
Java使用RSA加密解密:
package com.security.example.example4;
import java.security.InvalidKeyException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey;
import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException;
public class RSA { // 完成加密/解密工作 private Cipher cipher = null; // 公钥 private RSAPublicKey rsaPublicKey = null; // 私钥 private RSAPrivateKey rsaPrivateKey = null;
public RSA() { try { cipher = Cipher.getInstance("rsa"); KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"); KeyPair keypair = keyPairGen.genKeyPair(); rsaPrivateKey = (RSAPrivateKey) keypair.getPrivate(); rsaPublicKey = (RSAPublicKey) keypair.getPublic(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * 使用私钥加密。 * @param msg:要加密的消息。 * @return加密后的密文 */ public byte[] encryp(String msg) { try { cipher.init(Cipher.ENCRYPT_MODE, rsaPrivateKey); byte[] encrypMsg = cipher.doFinal(msg.getBytes()); return encrypMsg; } catch (InvalidKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalBlockSizeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (BadPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
/** * 使用公钥解密。 * @param msg:密文 * @return解密后的原文 */ public byte[] decryp(byte[] msg) { try { cipher.init(Cipher.DECRYPT_MODE, rsaPublicKey); byte[] decrypMsg = cipher.doFinal(msg); return decrypMsg; } catch (InvalidKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalBlockSizeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (BadPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /** * @param args */ public static void main(String[] args) { String msg = "java安全编程——RSA"; System.out.println("原文是:" + msg); RSA rsa = new RSA(); byte[] enMsg = rsa.encryp(msg); System.out.println("加密后是:" + new String(enMsg)); byte[] deMsg = rsa.decryp(enMsg); System.out.println("解密后是:" + new String(deMsg));
}
}
输出: 原文是:java安全编程——RSA 加密后是:_c_3乿e3岥赾悤_�_Q敊怦i�_f�儠B橱狎�_駸1=脖X揖�_p�!\x7BJ�_�-nZ臑�摁_UB厕瓀犆}~S_宜腒馾�=_ 解密后是:java安全编程——RSA |