Encrypt Decrypt my own key not generated java - java

I am new to cryptography, so I have a question:
How can I create my own key (let`s say like a string "1234"). Because I need to encrypt a string with a key (defined by me), save the encrypted string in a database and when I want to use it, take it from the database and decrypt it with the key known by me.
I have this code :
import java.security.InvalidKeyException;
import java.security.*;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
public class LocalEncrypter {
private static String algorithm = "PBEWithMD5AndDES";
//private static Key key = null;
private static Cipher cipher = null;
private static SecretKey key;
private static void setUp() throws Exception {
///key = KeyGenerator.getInstance(algorithm).generateKey();
SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);
String pass1 = "thisIsTheSecretKeyProvidedByMe";
byte[] pass = pass1.getBytes();
SecretKey key = factory.generateSecret(new DESedeKeySpec(pass));
cipher = Cipher.getInstance(algorithm);
}
public static void main(String[] args)
throws Exception {
setUp();
byte[] encryptionBytes = null;
String input = "1234";
System.out.println("Entered: " + input);
encryptionBytes = encrypt(input);
System.out.println(
"Recovered: " + decrypt(encryptionBytes));
}
private static byte[] encrypt(String input)
throws InvalidKeyException,
BadPaddingException,
IllegalBlockSizeException {
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] inputBytes = input.getBytes();
return cipher.doFinal(inputBytes);
}
private static String decrypt(byte[] encryptionBytes)
throws InvalidKeyException,
BadPaddingException,
IllegalBlockSizeException {
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] recoveredBytes =
cipher.doFinal(encryptionBytes);
String recovered =
new String(recoveredBytes);
return recovered;
}
}
Exception in thread "main" java.security.spec.InvalidKeySpecException: Invalid key spec
at com.sun.crypto.provider.PBEKeyFactory.engineGenerateSecret(PBEKeyFactory.java:114)
at javax.crypto.SecretKeyFactory.generateSecret(SecretKeyFactory.java:335)
at LocalEncrypter.setUp(LocalEncrypter.java:22)
at LocalEncrypter.main(LocalEncrypter.java:28)

A KeyGenerator generates random keys. Since you know the secret key, what you need is a SecretKeyFactory. Get an instance for your algorithm (DESede), and then call its generateSecret méthode with an instance of DESedeKeySpec as argument:
SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede");
SecretKey key = factory.generateSecret(new DESedeKeySpec(someByteArrayContainingAtLeast24Bytes));
Here is a complete example that works. As I said, DESedeKeySpec must be used with the DESede algorithm. Using a DESede key with PBEWithMD5AndDES makes no sense.
public class EncryptionTest {
public static void main(String[] args) throws Exception {
byte[] keyBytes = "1234567890azertyuiopqsdf".getBytes("ASCII");
DESedeKeySpec keySpec = new DESedeKeySpec(keyBytes);
SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede");
SecretKey key = factory.generateSecret(keySpec);
byte[] text = "Hello world".getBytes("ASCII");
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encrypted = cipher.doFinal(text);
cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decrypted = cipher.doFinal(encrypted);
System.out.println(new String(decrypted, "ASCII"));
}
}

Well, I found the solution after combining from here and there. The encrypted result will be formatted as Base64 String for safe saving as xml file.
package cmdCrypto;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.xml.bind.DatatypeConverter;
public class CmdCrypto {
public static void main(String[] args) {
try{
final String strPassPhrase = "123456789012345678901234"; //min 24 chars
String param = "No body can see me";
System.out.println("Text : " + param);
SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede");
SecretKey key = factory.generateSecret(new DESedeKeySpec(strPassPhrase.getBytes()));
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.ENCRYPT_MODE, key);
String str = DatatypeConverter.printBase64Binary(cipher.doFinal(param.getBytes()));
System.out.println("Text Encryted : " + str);
cipher.init(Cipher.DECRYPT_MODE, key);
String str2 = new String(cipher.doFinal(DatatypeConverter.parseBase64Binary(str)));
System.out.println("Text Decryted : " + str2);
} catch(Exception e) {
e.printStackTrace();
}
}
}

Related

How can I have the java ciper algorithm and ruby cipher algorithm in sync?

I have this code in my rails app:
require 'openssl'
require 'digest/sha1'
require 'base64'
KEY="secret_key"
data = "secret message"
def encrypt_value(data)
cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
cipher.encrypt
cipher.key = Digest::SHA256.digest(KEY)
encrypted = cipher.update(data)+cipher.final
return encrypted
end
def decrypt_value1(data)
cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
cipher.decrypt
cipher.key = Digest::SHA256.digest(KEY)
decrypted = cipher.update(data)+cipher.final
data = Base64.decode64(decrypted)
return data
end
And java code:
import java.security.AlgorithmParameters;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
public class EncryptionDecryption {
private static String salt;
private static int iterations = 65536 ;
private static int keySize = 256;
private static byte[] ivBytes;
// private static SecretKey secretKey;
private static final byte[] secretKey = "secret_key".getBytes();
public static void main(String []args) throws Exception {
salt = getSalt();
char[] message = "secret message".toCharArray();
System.out.println("Message: " + String.valueOf(message));
System.out.println("Encrypted: " + encrypt(message));
System.out.println("Decrypted: " + decrypt(encrypt(message).toCharArray()));
}
public static String encrypt(char[] plaintext) throws Exception {
byte[] saltBytes = salt.getBytes();
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec spec = new PBEKeySpec(plaintext, saltBytes, iterations, keySize);
//secretKey = skf.generateSecret(spec);
SecretKeySpec secretSpec = new SecretKeySpec(secretKey, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretSpec);
AlgorithmParameters params = cipher.getParameters();
ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] encryptedTextBytes = cipher.doFinal(String.valueOf(plaintext).getBytes("UTF-8"));
return DatatypeConverter.printBase64Binary(encryptedTextBytes);
}
public static String decrypt(char[] encryptedText) throws Exception {
System.out.println(encryptedText);
byte[] encryptedTextBytes = DatatypeConverter.parseBase64Binary(new String(encryptedText));
SecretKeySpec secretSpec = new SecretKeySpec(secretKey, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretSpec, new IvParameterSpec(ivBytes));
byte[] decryptedTextBytes = null;
try {
decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return new String(decryptedTextBytes);
}
public static String getSalt() throws Exception {
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[20];
sr.nextBytes(salt);
return new String(salt);
}
}
How can I have both of them work with each other, for example if I send an encrypted data to java app from rails app it should be able to decode it and vice-versa.
As far as you are using the same cypher algorithms and message padding characters, they should work just fine.
Also, it is better to use some key exchange protocol, like Diffie-Hellman. Both Ruby's OpenSSL wrapper and Java's Crypto lib support it. It is a safer way to generate per session keys.
PS. Your code as you have it, seems to be written for a standalone execution. For example, your Java code for decoding assumes that your string was encoded with the same instance's encode method. Because, your decode method is using IV that was initialized in encode method (ivBytes).

Encrypt in Java, Decrypt in Data Power

I am currently working in a solution, where I have encrypt a password in Java (Running in Jboss server), and then send to Data Power and de-crypt in DataPower. I able to encrypt the password in Java. I dont have much knowledge in DataPower. I have got the code to decrypt in datapower, but not sure how to send the key to datapower. Can anyone please help me out. The code is like below,
Encryption Code (Java)
package test;
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.util.ArrayList;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class Test {
private static final String ALGO = "AES";
public static String encrypt(String data,String secretKey) throws Exception {
Key key = generateKey(secretKey);
byte[] ivAES = {(byte)0x22,(byte)0x22,(byte)0x22,(byte)0x22,(byte)0x22,(byte)0x22,(byte)0x22,(byte)0x22,(byte)0x22,(byte)0x22,(byte)0x22,(byte)0x22,(byte)0x22,(byte)0x22,(byte)0x22,(byte)0x22};
IvParameterSpec ivspec = new IvParameterSpec(ivAES);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, ivspec);
byte[] encVal = cipher.doFinal(data.getBytes());
byte[] finalByte=copyBytes(encVal, ivAES);
String encryptedValue = new BASE64Encoder().encode(finalByte);
return encryptedValue;
}
public static String decrypt(String encryptedData,String secretKey) throws Exception {
Key key = generateKey(secretKey);
byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
ArrayList<byte[]> al = retreiveIv(decordedValue);
byte[] data = al.get(0);
byte[] iv = al.get(1);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
byte[] decValue = cipher.doFinal(data);
String decryptedValue = new String(decValue);
return decryptedValue;
}
private static Key generateKey(String secretKey) throws Exception {
Key key = new SecretKeySpec(secretKey.getBytes(), ALGO);
return key;
}
private static byte[] copyBytes(byte[] encVal, byte[] iv) throws Exception {
ByteArrayOutputStream os = new ByteArrayOutputStream();
os.write(iv);
os.write(encVal);
return os.toByteArray();
}
private static ArrayList<byte[]> retreiveIv(byte[] combineByte) {
ByteArrayOutputStream iv = new ByteArrayOutputStream(16);
ByteArrayOutputStream data = new ByteArrayOutputStream();
data.write(combineByte, combineByte.length - 16, 16);
iv.write(combineByte, 0, combineByte.length - 16);
ArrayList<byte[]> al = new ArrayList<byte[]>();
al.add(data.toByteArray());
al.add(iv.toByteArray());
return al;
}
public static void main(String[] args) throws Exception{
System.out.println(AESUtil.decrypt(AESUtil.encrypt("Hello", "AVH4TU8AC99dhL2l"), "AVH4TU8AC99dhL2l"));
}
}
Decryption (DataPower)
<xsl:variable name="algorithm">http://www.w3.org/2001/04/xmlenc#aes128-cbc</xsl:variable>
<xsl:variable name="decryptOut"><xsl:value-of select="dp:decrypt-data($algorithm,'name:danadp',$valueToDecrypt)"/></xsl:variable>
Decrypted Value: <xsl:copy-of select="$decryptOut"/>
But, I am not getting how to share the Key object to DataPower that we generated in Java code for encryption.
It will be great, if anyone can help me.
Create a shared secret key object with name 'danadp' and the key copied into a file and imported into the cert:/ folder in the DataPower domain where this code is running.
P.S Remember to prefix the key with "0x" if key is in hex.

Encryption using AES

I am encrypting the string using AES but it is not decrypting "1234567812345678" character back to plain text from encrypted string. For other text (like "Hello World") it is working fine. Also want to keep the encrypted code to accept only UTF-8 characters. I am using below code
import java.security.*;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
public class StrongAES
{
public static void main(String[] args)
{
//listing all available cryptographic algorithms
/* for (Provider provider: Security.getProviders()) {
System.out.println(provider.getName());
for (String key: provider.stringPropertyNames())
System.out.println("\t" + key + "\t" + provider.getProperty(key));
}*/
StrongAES saes = new StrongAES();
String encrypt = saes.encrypt(new String("Bar12346Bar12346"),new String("1234567812345678"));
//String encrypt = saes.encrypt(new String("Bar12346Bar12346"),new String("Hello world"));
System.out.println(encrypt);
String decrypt = saes.decrypt(new String("Bar12346Bar12346"), new String(encrypt));
System.out.println(decrypt);
}
String encrypt(String key, String text)
{
String encryptedText="";
try{
// Create key and cipher
Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
// encrypt the text
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] encrypted = cipher.doFinal(text.getBytes());
encryptedText = new String(encrypted);
// System.out.println(encryptedText);
}
catch(Exception e)
{
e.printStackTrace();
}
return encryptedText;
}
String decrypt(String key, String encryptedText)
{
String decryptedText="";
try{
// Create key and cipher
Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
// decrypt the text
cipher.init(Cipher.DECRYPT_MODE, aesKey);
decryptedText = new String(cipher.doFinal(encryptedText.getBytes()));
// System.out.println("Decrypted "+decryptedText);
}
catch(Exception e)
{
e.printStackTrace();
}
return decryptedText;
}
}
You must keep bytes, not converting to String.
explanations in this post:
Problems converting byte array to string and back to byte array
If you want a keep a String, think of convert to B64
String my_string=DatatypeConverter.printBase64Binary(byte_array);
and
byte [] byteArray=DatatypeConverter.parseBase64Binary(my_string);
you can also convert to Hexa (it's bigger)
I have chenged my code to below. Used BASE64Encoder to convert incrypted byte to string same converted with BASE64Decoder while decrypting. And UTF-8 for each getByte.
import java.security.*;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class StrongAES
{
public static void main(String[] args)
{
StrongAES saes = new StrongAES();
String encrypt = saes.encrypt(new String("Bar12346Bar12346"),new String("1234567812345678"));
System.out.println(encrypt);
String decrypt = saes.decrypt(new String("Bar12346Bar12346"), new String(encrypt));
System.out.println(decrypt);
}
String encrypt(String key, String text)
{
String encryptedText="";
try{
// Create key and cipher
Key aesKey = new SecretKeySpec(key.getBytes("utf-8"), "AES");
Cipher cipher = Cipher.getInstance("AES");
// encrypt the text
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] encrypted = cipher.doFinal(text.getBytes("utf-8"));
BASE64Encoder encoder = new BASE64Encoder();
encryptedText = encoder.encodeBuffer(encrypted);
}
catch(Exception e)
{
e.printStackTrace();
}
return encryptedText;
}
String decrypt(String key, String encryptedText)
{
String decryptedText="";
try{
// Create key and cipher
Key aesKey = new SecretKeySpec(key.getBytes("utf-8"), "AES");
Cipher cipher = Cipher.getInstance("AES");
// decrypt the text
cipher.init(Cipher.DECRYPT_MODE, aesKey);
BASE64Decoder decoder = new BASE64Decoder();
decryptedText = new String(cipher.doFinal(decoder.decodeBuffer(encryptedText)));
}
catch(Exception e)
{
e.printStackTrace();
}
return decryptedText;
}
}

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.
If you are looking for a java program to encrypt data with public key and decrypt it with private key then here is the code (using RSA algorithm),
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
/**
* #author visruthcv
*
*/
public class CryptographyUtil {
private static final String ALGORITHM = "RSA";
public static byte[] encrypt(byte[] publicKey, byte[] inputData)
throws Exception {
PublicKey key = KeyFactory.getInstance(ALGORITHM)
.generatePublic(new X509EncodedKeySpec(publicKey));
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedBytes = cipher.doFinal(inputData);
return encryptedBytes;
}
public static byte[] decrypt(byte[] privateKey, byte[] inputData)
throws Exception {
PrivateKey key = KeyFactory.getInstance(ALGORITHM)
.generatePrivate(new PKCS8EncodedKeySpec(privateKey));
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptedBytes = cipher.doFinal(inputData);
return decryptedBytes;
}
public static KeyPair generateKeyPair()
throws NoSuchAlgorithmException, NoSuchProviderException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
// 512 is keysize
keyGen.initialize(512, random);
KeyPair generateKeyPair = keyGen.generateKeyPair();
return generateKeyPair;
}
public static void main(String[] args) throws Exception {
KeyPair generateKeyPair = generateKeyPair();
byte[] publicKey = generateKeyPair.getPublic().getEncoded();
byte[] privateKey = generateKeyPair.getPrivate().getEncoded();
byte[] encryptedData = encrypt(publicKey,
"hi this is Visruth here".getBytes());
byte[] decryptedData = decrypt(privateKey, encryptedData);
System.out.println(new String(decryptedData));
}
}
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))
}
}

AES-256 Password Based Encryption/Decryption in Java

I found a guide for implementing AES encryption/decryption in Java and tried to understand each line as I put it into my own solution. However, I don't fully understand it and am having issues as a result. The end goal is to have passphrase based encryption/decryption. I've read other articles/stackoverflow posts about this, but most do not provide enough explanation (I am very new to crypto in Java)
My main issues right now are that even when I set byte[] saltBytes = "Hello".getBytes();
I still get a different Base64 result in the end (char[] password is random each time, but I read that it is safer to leave passwords in char[] form. My other problem is that when the program gets to decrypt(), I get a NullPointerException at
byte[] saltBytes = salt.getBytes("UTF-8");
Thank you in advance for any help/advice you can give me.
The code in question:
import java.security.AlgorithmParameters;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
public class EncryptionDecryption {
private static String salt;
private static int iterations = 65536 ;
private static int keySize = 256;
private static byte[] ivBytes;
public static void main(String []args) throws Exception {
char[] message = "PasswordToEncrypt".toCharArray();
System.out.println("Message: " + message.toString());
System.out.println("Encrypted: " + encrypt(message));
System.out.println("Decrypted: " + decrypt(encrypt(message).toCharArray()));
}
public static String encrypt(char[] plaintext) throws Exception {
salt = getSalt();
byte[] saltBytes = salt.getBytes();
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec spec = new PBEKeySpec(plaintext, saltBytes, iterations, keySize);
SecretKey secretKey = skf.generateSecret(spec);
SecretKeySpec secretSpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretSpec);
AlgorithmParameters params = cipher.getParameters();
ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] encryptedTextBytes = cipher.doFinal(plaintext.toString().getBytes("UTF-8"));
return DatatypeConverter.printBase64Binary(encryptedTextBytes);
}
public static String decrypt(char[] encryptedText) throws Exception {
byte[] saltBytes = salt.getBytes("UTF-8");
byte[] encryptedTextBytes = DatatypeConverter.parseBase64Binary(encryptedText.toString());
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec spec = new PBEKeySpec(encryptedText, saltBytes, iterations, keySize);
SecretKey secretkey = skf.generateSecret(spec);
SecretKeySpec secretSpec = new SecretKeySpec(secretkey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretSpec, new IvParameterSpec(ivBytes));
byte[] decryptedTextBytes = null;
try {
decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return decryptedTextBytes.toString();
}
public static String getSalt() throws Exception {
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[20];
sr.nextBytes(salt);
return salt.toString();
}
}
I think that you are making two mistakes :)
I've corrected your sample code to make it work :
import java.security.AlgorithmParameters;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
public class EncryptionDecryption {
private static String salt;
private static int iterations = 65536 ;
private static int keySize = 256;
private static byte[] ivBytes;
private static SecretKey secretKey;
public static void main(String []args) throws Exception {
salt = getSalt();
char[] message = "PasswordToEncrypt".toCharArray();
System.out.println("Message: " + String.valueOf(message));
System.out.println("Encrypted: " + encrypt(message));
System.out.println("Decrypted: " + decrypt(encrypt(message).toCharArray()));
}
public static String encrypt(char[] plaintext) throws Exception {
byte[] saltBytes = salt.getBytes();
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec spec = new PBEKeySpec(plaintext, saltBytes, iterations, keySize);
secretKey = skf.generateSecret(spec);
SecretKeySpec secretSpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretSpec);
AlgorithmParameters params = cipher.getParameters();
ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] encryptedTextBytes = cipher.doFinal(String.valueOf(plaintext).getBytes("UTF-8"));
return DatatypeConverter.printBase64Binary(encryptedTextBytes);
}
public static String decrypt(char[] encryptedText) throws Exception {
System.out.println(encryptedText);
byte[] encryptedTextBytes = DatatypeConverter.parseBase64Binary(new String(encryptedText));
SecretKeySpec secretSpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretSpec, new IvParameterSpec(ivBytes));
byte[] decryptedTextBytes = null;
try {
decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return new String(decryptedTextBytes);
}
public static String getSalt() throws Exception {
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[20];
sr.nextBytes(salt);
return new String(salt);
}
}
The first mistake is that you generate 2 different salts (when using the encrypt method), so encrypted/decrypted logs were differents (logical, but the decryption would still work because you are calling the decryption directly after encryption).
The second mistake was for the secret key. You need to generate a secret key when you are encrypting, but not decrypting. To put it more simply, it is as if i was encrypting with the password "encrypt" and that you are trying to decrypt it with the password "decrypt".
I would advise you to generate every random stuff (such as private key, salt etc on startup). But beware that when you'll stop your app, you won't be able to decrypt old stuff unless getting the exact same random stuff.
Hope I helped :)
Regards,

Categories