📄 rsa.java
字号:
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
public class RSA {
private Cipher cipher;
private PublicKey publicKey;
private PrivateKey privateKey;
RSA(){
try{
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(1040);//指定密匙长度(取值范围:512~2048)
KeyPair keyPair = keyPairGen.generateKeyPair();//生成‘密匙对’,其中包含着一个公匙和一个私匙的信息
privateKey = keyPair.getPrivate();//获得私匙
publicKey = keyPair.getPublic();//获得公匙
}
catch(NoSuchAlgorithmException e){e.printStackTrace();}
}
public PublicKey getPublicKey(){
return publicKey;
}
public PrivateKey getprivateKey(){
return privateKey;
}
public void setPublicKey(PublicKey key)
{
publicKey = key;
}
public void setPrivateKey(PrivateKey key)
{
privateKey = key;
}
public byte [] wrapkey(Key key){//用publickey来包装DES,包装的结果是一个byte[]
byte [] wrapedkey = null;
try {
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.WRAP_MODE, publicKey);
wrapedkey = cipher.wrap(key);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return wrapedkey;
}
public Key unwrapkey(byte []wrapedkey){
//将DES的私钥用RSA解密
Key key=null;
try {
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.UNWRAP_MODE, privateKey);
key = cipher.unwrap(wrapedkey, "DES", Cipher.SECRET_KEY);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return key;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -