非对称型加密非常适合多个客户端和服务器之间的秘密通讯客户端使用同一个公钥将明文加密而这个公钥不能逆向的解密密文发送到服务器后有服务器端用私钥解密这样就做到了明文的加密传送
非对称型加密也有它先天的缺点加密解密速度慢制约了它的发挥如果你有大量的文字需要加密传送建议你通过非对称型加密来把对称型密钥分发到客户端及时更新对称型密钥
import javaio*;
import javasecurity*;
import javaxcrypto*;
import javaxcryptospec*;
/**
* <p>Title: RSA非对称型加密的公钥和私钥</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) </p>
* <p>Company: </p>
* @author not attributable
* @version
*/
public class KeyRSA {
private KeyPairGenerator kpg = null;
private KeyPair kp = null;
private PublicKey public_key = null;
private PrivateKey private_key = null;
private FileOutputStream public_file_out = null;
private ObjectOutputStream public_object_out = null;
private FileOutputStream private_file_out = null;
private ObjectOutputStream private_object_out = null;
/**
* 构造函数
* @param in 指定密匙长度(取值范围~)
* @throws NoSuchAlgorithmException 异常
*/
public KeyRSA(int in String address) throws NoSuchAlgorithmExceptionFileNotFoundException IOException
{
kpg = KeyPairGeneratorgetInstance(RSA); //创建密匙对生成器
kpginitialize(in); //指定密匙长度(取值范围~)
kp = kpggenKeyPair(); //生成密匙对其中包含着一个公匙和一个私匙的信息
public_key = kpgetPublic(); //获得公匙
private_key = kpgetPrivate(); //获得私匙
//保存公匙
public_file_out = new FileOutputStream(address + /public_keydat);
public_object_out = new ObjectOutputStream(public_file_out);
public_object_outwriteObject(public_key);
//保存私匙
private_file_out = new FileOutputStream(address + /private_keydat);
private_object_out = new ObjectOutputStream(private_file_out);
private_object_outwriteObject(private_key);
}
public static void main(String[] args) {
try {
Systemoutprintln(私匙和公匙保存到C盘下的文件中);
new KeyRSA( c:/);
}
catch (IOException ex) {
}
catch (NoSuchAlgorithmException ex) {
}
}
}