Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,990 questions

51,935 answers

573 users

How to encrypt and decrypt a string in Java

1 Answer

0 votes
import java.security.KeyPair;
import java.security.Signature;
import java.security.PublicKey;
import java.security.KeyPairGenerator;

import javax.crypto.Cipher;

public class MyClass {
    public static void main(String args[]) throws Exception{
        Signature signature = Signature.getInstance("SHA256withRSA");
      
        KeyPairGenerator keypairgenerator = KeyPairGenerator.getInstance("RSA");
      
        keypairgenerator.initialize(2048);
      
        KeyPair keypair = keypairgenerator.generateKeyPair();   
      
        PublicKey publicKey = keypair.getPublic();  

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
	  
        byte[] strarr = "Java programming".getBytes();
        cipher.update(strarr);
	  
        byte[] encrypt  = cipher.doFinal();	 
        System.out.println(new String(encrypt , "UTF8"));


        cipher.init(Cipher.DECRYPT_MODE, keypair.getPrivate());
      
        byte[] decrypt  = cipher.doFinal(encrypt);
        System.out.println("\n" + new String(decrypt));
    }
}



/*
run:

TA�J�������&]�� �	����v1�5F,��ݽ���ж<s;��vg���5�Q@ ���&�0?�s�T
s��7/�	L����u[��`��3��o�=I��4Ay�XO

Java programming

*/

 



answered Feb 19, 2022 by avibootz
...