Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Encrypt String With Public Key and Decrypt with Private key ?

i want to encrypt a password with a key from server and decrypt the encrypted password in serverside. this is the code i have used in my application

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package publicprivatekey;

import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.crypto.*;

/**
 *
 * @author Rajorshi
 */
public class PublicPrivateKey {

    public static String getEncrypted(String data, String Key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidKeySpecException, IllegalBlockSizeException, BadPaddingException {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(Key.getBytes())));
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedbytes = cipher.doFinal(data.getBytes());
        return new String(Base64.getEncoder().encode(encryptedbytes));
    }

    public static String getDecrypted(String data, String Key) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        PrivateKey pk = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(Key.getBytes())));
        cipher.init(Cipher.DECRYPT_MODE, pk);
        byte[] encryptedbytes = cipher.doFinal(Base64.getDecoder().decode(data.getBytes()));
        return new String(encryptedbytes);
    }

    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        // TODO code application logic here
        KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
        keyGenerator.init(448);
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.genKeyPair();

        String pubKey = new String(Base64.getEncoder().encode(keyPair.getPublic().getEncoded()));
        String priKey = new String(Base64.getEncoder().encode(keyPair.getPrivate().getEncoded()));
        System.out.println("Public Key:" + pubKey);
        System.out.println("Private Key:" + priKey);
        String cipherText = getEncrypted("hi this is a string", pubKey);

        System.out.println("CHIPHER:" + cipherText);
        String decryptedText = getDecrypted(cipherText, priKey);
        System.out.println("DECRYPTED STRING:" + decryptedText);

    }

}

i want to encrypt a password with a key from server and decrypt the encrypted password in serverside. this is the code i have used in my application.

like image 264
Rajorshi Biswas Avatar asked Aug 10 '15 09:08

Rajorshi Biswas


People also ask

Can you encrypt with private key and decrypt with public key?

Asymmetric encryption uses a mathematically related pair of keys for encryption and decryption: a public key and a private key. If the public key is used for encryption, then the related private key is used for decryption. If the private key is used for encryption, then the related public key is used for decryption.

Can public key be used for both encryption and decryption?

Public Key (or asymmetric encryption) In a public key system, two keys are used, one for encrypting and one for decrypting.


1 Answers

you can do with Scala or Spark + scala as:

object App {
  def main(args: Array[String]): Unit = {


    println("************hello*******************\n")


    val generator = KeyPairGenerator.getInstance("RSA")

    generator.initialize(2048)
    val pair = generator.generateKeyPair
    val privateKey = pair.getPrivate
    val publicKey = pair.getPublic
    //println("private key: ",privateKey)
    println("public Key: ", publicKey)

    //Convert the keys to string using encodeToString()
    val publicKeyString = getEncoder.encodeToString(publicKey.getEncoded());

    println("publicKeyString :", publicKeyString)

    val privateKeyString = getEncoder.encodeToString(privateKey.getEncoded());

    println("privateKeyString :", privateKeyString)

    val spark = SparkSession.builder()
      .master("local")
      .appName("rsa_test")
      .enableHiveSupport()
      .config("spark.sql.parquet.compression.codec", "snappy")
      .config("parquet.block.size", 268435456)
      .config("hive.exec.dynamic.partition.mode", "nonstrict")
      .getOrCreate()

    def RsaEncryption(inParm: String): Array[Byte] = {

      //Create a Cipher object.The Cipher will provide the functionality of a
      // cryptographic cipher for encryption and decryption.
      val encryptionCipher = Cipher.getInstance("RSA")
      //init() method initializes the cipher with a key for encryption, decryption, key wrapping,
      // or key unwrapping depending on the value of opmode
      encryptionCipher.init(Cipher.ENCRYPT_MODE, privateKey)
      //The doFinal() method performs the encryption operation depending on how the cipher was initialized
      // and resets once it finishes allowing encrypting more data.

      val encryptedMessage = encryptionCipher.doFinal(inParm.getBytes)

      return encryptedMessage
      //return encryption
    }

    def RsaDecryption(inParm: Array[Byte]): String = {
      val decryptionCipher = Cipher.getInstance("RSA")
      decryptionCipher.init(Cipher.DECRYPT_MODE, publicKey)
      val decryptedMessage = decryptionCipher.doFinal(inParm)
      val decryption = new String(decryptedMessage)
      return decryption
    }

    val secretMessage = "Test string for encryption"
    val encryptedMessage = RsaEncryption(secretMessage)
    println("encryptedMessage is :"+encryptedMessage)
    //The method returns an array of bites which is simply our message, and we can convert it to a string
    // and log it to the console to verify our text is similar to the decrypted text.

    System.out.println("Encrypted Message = " + getEncoder.encodeToString(RsaEncryption(secretMessage)))

    // register udf below
    val clearTxt = "It will be done through spark 2.12"
    spark.udf.register("rsa_encrypt", (clearTxt: String) => getEncoder.encodeToString(RsaEncryption(clearTxt)))
    val text = s"""select rsa_encrypt(\"$clearTxt\") as enc_string"""
    println(text)
    val df1 = spark.sql(text)
    val encString = df1.select(col("enc_string")).collectAsList().get(0)(0).toString().getBytes()
    //val encString1 = df1.withColumn("enc2",col("enc_string").cast(Array[Byte]()))

    println("Showing string : " + encString)
    println("Decoder call "+ getDecoder.decode(encString))
    val decodedString = getDecoder.decode(encString)

    def manOf[T: Manifest](t: T): Manifest[T] = manifest[T]

    println("Data type of df value " + manOf(getEncoder.encodeToString(RsaEncryption(secretMessage))))

    df1.show(truncate=false)
    //Decrypt message

    val decryptionCipher = Cipher.getInstance("RSA")
    decryptionCipher.init(Cipher.DECRYPT_MODE, publicKey)


    val decryptedMessage = decryptionCipher.doFinal(encryptedMessage)
    val decryption = new String(decryptedMessage)
    println("=>"+decryption)
    //System.out.println("decrypted message = " + RsaDecryption(encryptedMessage))

    System.out.println("decrypted message2 = " +RsaDecryption(decodedString))
  }
}
like image 142
Nilay Bhardwaj Avatar answered Oct 28 '22 11:10

Nilay Bhardwaj