1. Generate key
public static map<string, Object> Initkey () throws exception{keypairgenerator
= Keypairgenerator.getinstance ("RSA");
Keypairgenerator.initialize (1024);
KeyPair KeyPair = Keypairgenerator.generatekeypair ();
Rsapublickey Rsapublickey = (rsapublickey) keypair.getpublic ();
Rsaprivatekey Rsaprivatekey = (rsaprivatekey) keypair.getprivate ();
map<string, object> map = new hashmap<> ();
Map.put (Public_key, rsapublickey);
Map.put (Private_key, rsaprivatekey);
return map;
}
2. Use public key for encryption
public static byte[] Encryptrsa (byte[] data, Rsapublickey key) throws exception{Cipher Cipher
= cipher.getinstance ( "RSA");
Cipher.init (Cipher.encrypt_mode, key);
byte[] Resultbytes = cipher.dofinal (data);
return resultbytes;
}
3. Decrypting with the private key
public static byte[] Decryptrsa (byte[] src, Rsaprivatekey key) throws exception{Cipher Cipher
= Cipher.getinstance (" RSA ");
Cipher.init (Cipher.decrypt_mode, key);
byte[] plainbytes = cipher.dofinal (src);
return plainbytes;
}
4. Test
public class Client {public
static final String DATA = "HelloWorld";
public static void Main (string[] args) throws Exception {
map<string, object> Map = Rsautil.initkey ();
Rsaprivatekey Rsaprivatekey = Rsautil.getprivatekey (map);
Rsapublickey Rsapublickey = Rsautil.getpublickey (map);
byte[] resultbytes = Rsautil.encryptrsa (Data.getbytes (), rsapublickey);
System.out.println ("RSA Encrypt:" + helper.frombytetohex (resultbytes));
byte[] plainbytes = Rsautil.decryptrsa (resultbytes, rsaprivatekey);
System.out.println ("RES Plain:" + new String (plainbytes));
}
5. Results
rsa Encrypt: 50005af95cc6d79f22c4baf9c289926ef2afb48c0c1760eecbe2bacc22e989349af66cea1f12be343629f8889a6d06679924df445e4c59012753529c7 dffb563c783a2e45a20a8ca8ec0ee0fa74625cfce0a4f77cf4fea96c0d1c944ce2f4433aecc941fdd213f1186e8e71668e842acbc4c630a7befdbf20a 901af2da1718e4 RSA Plain:helloworld