javaRSA实现加密解密

rsa秘钥必须是公钥和私钥一起使用,若用公钥机密,就得用私钥解密;若用私钥加密,就得用公钥解密

创建主函数测试

  public static void main(String[] args) throws Exception {
     String data
= "跳梁小豆tlxd666"; //秘钥(公钥+私钥)生成器 KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(521);//初始化秘钥大小 KeyPair keypair = kpg.generateKeyPair();//生成秘钥对 RSAPublicKey publickey = (RSAPublicKey)keypair.getPublic();//得到公钥 RSAPrivateKey privatekey = (RSAPrivateCrtKey)keypair.getPrivate();//得到私钥 //使用公钥加密,私钥解密 //加密 Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publickey);//初始化,加密模式,公钥 byte[] b = cipher.doFinal(data.getBytes());//加密,返回一个机密后的新字节数组对象 System.out.println("加密后:"+new String(b)); //解密 cipher.init(Cipher.DECRYPT_MODE,privatekey);//初始化,解密模式,私钥 byte[] b2 = cipher.doFinal(b);//解密 System.out.println("解密后:"+new String(b2)); }

 

posted @ 2018-09-26 19:34  跳梁小豆  阅读(540)  评论(0编辑  收藏  举报