java使用RSA加密算法加密
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
- RSA加密解密功能
- @author wy 2016.9.7
*/
public class RSATest {
public static String secret = “RSA”; //加密算法
public static PublicKey pubKey; //公钥
public static PrivateKey priKey; //私钥
public static void main(String[] args) {
generateKey(); //初始化生产公钥和私钥
String str = “这是一个需要加密的字符串”;
String en = encrypt(str);
System.out.println(“加密后的字符串:”+en);
String de = decrypt(en);
System.out.println(“解密后的字符串:”+de);
}
/**
- 初始化生产公钥和私钥
/
public static void generateKey(){
try {
//创建秘RSA加密算法私钥和公钥成器
KeyPairGenerator gen = KeyPairGenerator.getInstance(secret);
gen.initialize(1024); //初始化
KeyPair keypari = gen.generateKeyPair();
pubKey = keypari.getPublic(); //得到公钥
priKey = keypari.getPrivate(); //得到私钥
} catch (Exception e) {
e.printStackTrace();
}
}
/* - 加密算法
- @param mes
- @return
*/
public static String encrypt(String mes){
try {
//得到加密操作对象
Cipher cipher = Cipher.getInstance(secret);
//初始化加密模式 用公钥
cipher.init(Cipher.ENCRYPT_MODE,pubKey);
byte b[] = mes.getBytes();
byte s [] = cipher.doFinal(b); //加密
//字符串加密
BASE64Encoder en = new BASE64Encoder();
return en.encode(s);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
- 解密方法
- @param sec
- @return
*/
public static String decrypt(String sec){
try {
//得到加密操作对象
Cipher cipher = Cipher.getInstance(secret);
//初始化加密模式 用私钥
cipher.init(Cipher.DECRYPT_MODE, priKey);
//字符串解密
BASE64Decoder de = new BASE64Decoder();
byte b [] = de.decodeBuffer(sec);
//返回解密字符串
return new String(cipher.doFinal(b));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}