Android之RAS加密算法测试实例
程序员文章站
2023-11-22 08:01:33
复制代码 代码如下:import java.security.key; import java.security.keyfactory; ...
复制代码 代码如下:
import java.security.key;
import java.security.keyfactory;
import java.security.keypair;
import java.security.keypairgenerator;
import java.security.privatekey;
import java.security.publickey;
import java.security.interfaces.rsaprivatekey;
import java.security.interfaces.rsapublickey;
import java.security.spec.pkcs8encodedkeyspec;
import java.security.spec.x509encodedkeyspec;
import javax.crypto.cipher;
import sun.misc.base64decoder;
import sun.misc.base64encoder;
public class rsahelper {
public static publickey getpublickey(string key) throws exception {
byte[] keybytes;
keybytes = (new base64decoder()).decodebuffer(key);
x509encodedkeyspec keyspec = new x509encodedkeyspec(keybytes);
keyfactory keyfactory = keyfactory.getinstance("rsa");
publickey publickey = keyfactory.generatepublic(keyspec);
return publickey;
}
public static privatekey getprivatekey(string key) throws exception {
byte[] keybytes;
keybytes = (new base64decoder()).decodebuffer(key);
pkcs8encodedkeyspec keyspec = new pkcs8encodedkeyspec(keybytes);
keyfactory keyfactory = keyfactory.getinstance("rsa");
privatekey privatekey = keyfactory.generateprivate(keyspec);
return privatekey;
}
public static string getkeystring(key key) throws exception {
byte[] keybytes = key.getencoded();
string s = (new base64encoder()).encode(keybytes);
return s;
}
public static void main(string[] args) throws exception {
keypairgenerator keypairgen = keypairgenerator.getinstance("rsa");
//密钥位数
keypairgen.initialize(1024);
//密钥对
keypair keypair = keypairgen.generatekeypair();
// 公钥
publickey publickey = (rsapublickey) keypair.getpublic();
// 私钥
privatekey privatekey = (rsaprivatekey) keypair.getprivate();
string publickeystring = getkeystring(publickey);
system.out.println("public:\n" + publickeystring);
string privatekeystring = getkeystring(privatekey);
system.out.println("private:\n" + privatekeystring);
//加解密类
cipher cipher = cipher.getinstance("rsa");//cipher.getinstance("rsa/ecb/pkcs1padding");
//明文
byte[] plaintext = "我们都很好!邮件:@sina.com".getbytes();
//加密
cipher.init(cipher.encrypt_mode, publickey);
byte[] enbytes = cipher.dofinal(plaintext);
//通过密钥字符串得到密钥
publickey = getpublickey(publickeystring);
privatekey = getprivatekey(privatekeystring);
//解密
cipher.init(cipher.decrypt_mode, privatekey);
byte[]debytes = cipher.dofinal(enbytes);
publickeystring = getkeystring(publickey);
system.out.println("public:\n" +publickeystring);
privatekeystring = getkeystring(privatekey);
system.out.println("private:\n" + privatekeystring);
string s = new string(debytes);
system.out.println(s);
}
}