I'm trying to use RSA encryption in Java.
I'm generating a public key and using it to encrypt text. My problem is that when I pass in the same text and the same key two time, the encrypted results are different. This means I can't use my encryption to test if entered text is equal to a stored result of a previous encryption.
This is my encryption class:
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.util.Arrays;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
/**
* The class encrypts text using an RSA algorithm.
*
*/
public class RSAEncryption {
//RSA algorithm
private final String ALGORITHM = "RSA";
/**
* The generateKey method generates a public key for use in RSA encryption.
* #return key a PublicKey for use in RSA encryption.
*/
public PublicKey generateKey(){
KeyPair key = null;
KeyPairGenerator keyGen;
try {
keyGen = KeyPairGenerator.getInstance(ALGORITHM); //gets instance of the alogrithm
keyGen.initialize(1024); //a 1021 bit key
key = keyGen.generateKeyPair(); //makes a pair
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return key.getPublic(); //returns the public key. Private key never stored.
}
/**
* The encrypt method takes in text and a key and encrypts the text using the RSA encryption algorithm.
* #params text a String, the text to encrypt.
* #params key a PublicKey to use in encryption.
* #returns encryptedText a byte array representing the result of the encryption.
public byte[] encrypt(String text, PublicKey key){
byte[] encryptedText = null;
Cipher cipher;
try {
cipher = Cipher.getInstance(ALGORITHM); //gets instance of RSA
cipher.init(Cipher.ENCRYPT_MODE, key); //in encryption mode with the key
encryptedText = cipher.doFinal(text.getBytes()); //carry out the encryption
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
return encryptedText; //return encrypted result
}
/**
* The authenticate method checks if entered text, once encrypted, matches the stored byte[].
* #param text a String, the text to encrypt.
* #param stored a byte[], the result of a prior encryption.
* #param key a PublicKey, a result of the generateKey method.
* #return boolean, true if the text is valid, false otherwise.
*/
public boolean authenticate(String text, byte[] stored, PublicKey key){
byte[] encryptText = encrypt(text,key); //encrypt the entered text
return Arrays.equals(stored, encryptText); //check if the stored and entered byte[] are the same.
}
}
I've written JUnit tests for this:
import static org.junit.Assert.*;
import java.security.PublicKey;
import java.util.Arrays;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class RSAEncryptionTest {
RSAEncryption cipher;
String text;
#Before
public void setUp(){
cipher = new RSAEncryption();
text = "text";
}
#Test
public void testEncryptionGenerateKeyGeneratesANewKeyWhenCalled(){
PublicKey key = cipher.generateKey();
assertEquals(false,key.equals(cipher.generateKey()));
}
#Test
public void testEncryptionEncryptMethodRepeatablyEncrypts(){
PublicKey key = cipher.generateKey();
byte[] encrypted = cipher.encrypt(text,key);
Assert.assertArrayEquals(encrypted, cipher.encrypt(text,key));
//test fails
}
#Test
public void testEncryptionAuthenticateMethodReturnsTrueWhenValidTextPassedIn(){
PublicKey key = cipher.generateKey();
byte[] encrypted = cipher.encrypt(text,key);
assertEquals(true,cipher.authenticate(text,encrypted,key));
//test fails
}
#Test
public void testEncryptionAuthenticateMethodReturnsFalseWhenInvalidTextPassedIn(){
PublicKey key = cipher.generateKey();
byte[] encrypted = cipher.encrypt(text,key);
assertEquals(false,cipher.authenticate("text1",encrypted,key));
}
}
The second and third tests fail.
Any ideas how to repeatably encrypt text using RSA?
RSA is a public-key encryption scheme. It sounds like you actually want to use a hashing algorithm (e.g. SHA-256 or SHA-512). I say this because you say:
This means I can't use my encryption to test if entered text is equal
to a stored result of a previous encryption.
If this is your goal, you should use a hashing algorithm. By design, RSA encryption should include a padding step to ensure that the ciphertext differs:
To avoid these problems, practical RSA implementations typically embed some form of structured, randomized padding into the value m before encrypting it. This padding ensures that m does not fall into the range of insecure plaintexts, and that a given message, once padded, will encrypt to one of a large number of different possible ciphertexts.
-- http://en.wikipedia.org/wiki/RSA_%28algorithm%29
The output of an RSA cipher is not the same each time for a given plaintext when using an appropriate padding scheme (generally PKCS#1 or OAEP padding). Encrypting a given plaintext will result in different ciphertext each time. If the cipher generated the same output for a given input every time it would be a security vulnerability.
That being said you can force Java to use a non padded RSA cipher by using the spec "RSA/ECB/NOPADDING" for Cipher.getInstance(String). Doing so will result in your tests passing, but as I said earlier this is not very secure.
Related
I have a situation where I have to store the encrypted from of a text in an excel sheet and my java code should read that encrypted text from a excel sheet and convert it back to original text and hit the server with original plain text.
I'm trying to achieve this with AES encryption/decryption logic but I'm not able to achieve it as every time I convert the plain text into encrypted format for it to be stored in the excel sheet it results in a different encrypted string each time so I'm not able to decrypt it back to original, what I want is for a same static string/text my AES encrypted text should also be static.
I know even if my encrypted string is dynamic I can convert it back to decrypted format but for my case what I want is my encrypted text should also remain static.
How can I achieve this?
Ex. If my plain text is "This is a question" my encrypted string is different each time like below
Enter
This is a question
Encrypted Data : mFsue8JGwLcJQTiBzM0HLVvdDXKPNGsG/O7N60joH+Ozgg==
Decrypted Data : This is a question
Enter
This is a question
Encrypted Data : FdBz3cGS4NphK14Fw8Me4daM4lVzdrK47WUMSRiUVe+juQ==
Decrypted Data : This is a question
See the encrypted data's are different each time. I want that to be static
The classes which I'm using are as below (please note these are not my exact classes but they implement the same logic which I have used. These example classes may have some non used variables and methods, I have mentioned just for reference)
Method.java
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class Method {
private static SecretKey key;
private final int KEY_SIZE = 128;
private final int DATA_LENGTH = 128;
private Cipher encryptionCipher;
/*
* public void init() throws Exception { KeyGenerator keyGenerator =
* KeyGenerator.getInstance("AES"); keyGenerator.init(KEY_SIZE); key =
* keyGenerator.generateKey();
*
*
* }
*/
// String to Key
public static void getKeyFromPassword(String toEnc, String salt) throws
NoSuchAlgorithmException, InvalidKeySpecException { SecretKeyFactory factory
= SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); KeySpec spec = new
PBEKeySpec(toEnc.toCharArray(), salt.getBytes(), 65536, 128); SecretKey
originalKey = new SecretKeySpec(factory.generateSecret(spec).getEncoded(),"AES");
key= originalKey; }
/*
* public static void convertStringToSecretKeyto(String string) {
*
*
* byte[] bytesEncoded = Base64.getEncoder().encode(string.getBytes()); byte[]
* decodedKey = Base64.getDecoder().decode(string); key = new
* SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
* System.out.println(bytesEncoded); System.out.println(decodedKey);
*
* }
*/
public String encrypt(String data) throws Exception {
byte[] dataInBytes = data.getBytes();
encryptionCipher = Cipher.getInstance("AES/GCM/NoPadding");
encryptionCipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedBytes = encryptionCipher.doFinal(dataInBytes);
return encode(encryptedBytes);
}
public String decrypt(String encryptedData) throws Exception {
byte[] dataInBytes = decode(encryptedData);
Cipher decryptionCipher = Cipher.getInstance("AES/GCM/NoPadding");
GCMParameterSpec spec = new GCMParameterSpec(DATA_LENGTH,
encryptionCipher.getIV());
decryptionCipher.init(Cipher.DECRYPT_MODE, key, spec);
byte[] decryptedBytes = decryptionCipher.doFinal(dataInBytes);
return new String(decryptedBytes);
}
private String encode(byte[] data) {
return Base64.getEncoder().encodeToString(data);
}
private byte[] decode(String data) {
return Base64.getDecoder().decode(data);
}
}
Main.class
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import java.util.Base64;
import java.util.Scanner;
public class Cypher {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Method aes_encryption = new Method();
// aes_encryption.init();
Method.getKeyFromPassword("Texty text","Salty salt");
System.out.println("Enter");
Scanner sc= new Scanner(System.in);
String s= sc.nextLine();
String encryptedData = aes_encryption.encrypt(s);
String decryptedData = aes_encryption.decrypt(encryptedData);
System.out.println("Encrypted Data : " + encryptedData);
System.out.println("Decrypted Data : " + decryptedData);
} catch (Exception ignored) {
}
}
}
This is not really an implementation issue; your issue is with the used encryption scheme.
The nonce or IV are used to randomize your ciphertext. This gives you an important property: identical plaintext will encrypt to randomized ciphertext. This is required for a cipher to be secure, as you could otherwise identify identical plaintext messages.
Now you could just fix the IV or nonce, but that means that you will leak information early: if the first blocks of plaintext are identical then those blocks will result in identical ciphertext. Instead you can use an encryption scheme where each of the ciphertext bits depend on all of the plaintext bits.
There are several schemes that offer this kind of property:
biIGE mode: the bi-directional infinite garble extension mode is an encryption mode that runs both forward and then backwards. It is an odd mode that isn't used or implemented much;
FPE modes: format preserving encryption can be used to encrypt X plaintext bits into exactly X ciphertext bits, it is mainly used for smaller plaintext messages such as credit cards (so that there aren't any additional storage requirements for encrypted credit card numbers);
AES-SIV mode: synthetic IV mode is probably the best option, it can encrypt large(r) messages, and offers authenticity as well as the MAC / authentication tag doubles as IV. It has the drawback that it does require additional room for the synthetic IV / authentication tag. It is also a two-pass mode (all plaintext bytes are visited twice), which means that it won't be as performant as other generic modes.
There is AES-GCM-SIV for a performant option of the latter.
Of course, as indicated by others, you really want to make sure that you need this kind of functionality: not having messages encrypt to the same ciphertext is a rather fundamental security property of a cipher.
I am trying to achieve encryption using PGP and my encrypt method successfully encrypts the input string but when I try to decrypt it to verify if the encryption is properly done, the string doesn't get decrypted.
I tried 2 approaches:
1st approach uses FileOutputStream to write encrypted string & 2nd approach uses ByteArrayOutputStream.
FileOutputStream creates a file and I am able to decrypt it using Kleopatra. However my requirement is to just get an encrypted string (not written in a file). So when I try to decrypt the encrypted string (received after using ByteArrayOutputStream) its not working. I tried copying the string and decrypting it through tools>>clipboard in Kleopatra, but the decrypt/verify option is disabled. I tried writing the string on a file manually & through FileWriter class, but decryption fails with the error that File contains certificate & cannot be decrypted or verified.
I assume only files created directly by OutputStream gets decrypted successfully.
But I have to really check the encrypted string.
Any help would be highly appreciated.
The following full example is taken from the source code of the book "Java Cryptography: Tools and Techniques by David Hook & Jon Eaves".
The complete source code with all examples is available here: https://www.bouncycastle.org/java-crypto-tools-src.zip
The examples are showing a private-/public key creation with El Gamal or Elliptic Curves and encryption with AES-256.
In the ecExample-method I added two lines to save the encrypted string to the file "pgp-encrypted-string.dat" and then
reload the data to decypt the file and show the decrypted string.
import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openpgp.*;
import org.bouncycastle.openpgp.jcajce.JcaPGPObjectFactory;
import org.bouncycastle.openpgp.operator.PublicKeyDataDecryptorFactory;
import org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyPair;
import org.bouncycastle.openpgp.operator.jcajce.JcePGPDataEncryptorBuilder;
import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyDataDecryptorFactoryBuilder;
import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyKeyEncryptionMethodGenerator;
import org.bouncycastle.util.Strings;
import org.bouncycastle.util.io.Streams;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.Security;
import java.security.spec.ECGenParameterSpec;
import java.util.Date;
public class PGPEncryptionExampleForSO
{
/**
* Create an encrypted data blob using an AES-256 session key and the
* passed in public key.
*
* #param encryptionKey the public key to use.
* #param data the data to be encrypted.
* #return a PGP binary encoded version of the encrypted data.
*/
public static byte[] createEncryptedData(
PGPPublicKey encryptionKey,
byte[] data)
throws PGPException, IOException
{
PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(
new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.AES_256)
.setWithIntegrityPacket(true)
.setSecureRandom(new SecureRandom()).setProvider("BC"));
encGen.addMethod(
new JcePublicKeyKeyEncryptionMethodGenerator(encryptionKey)
.setProvider("BC"));
ByteArrayOutputStream encOut = new ByteArrayOutputStream();
// create an indefinite length encrypted stream
OutputStream cOut = encGen.open(encOut, new byte[4096]);
// write out the literal data
PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator();
OutputStream pOut = lData.open(
cOut, PGPLiteralData.BINARY,
PGPLiteralData.CONSOLE, data.length, new Date());
pOut.write(data);
pOut.close();
// finish the encryption
cOut.close();
return encOut.toByteArray();
}
/**
* Extract the plain text data from the passed in encoding of PGP
* encrypted data. The routine assumes the passed in private key
* is the one that matches the first encrypted data object in the
* encoding.
*
* #param privateKey the private key to decrypt the session key with.
* #param pgpEncryptedData the encoding of the PGP encrypted data.
* #return a byte array containing the decrypted data.
*/
public static byte[] extractPlainTextData(
PGPPrivateKey privateKey,
byte[] pgpEncryptedData)
throws PGPException, IOException
{
PGPObjectFactory pgpFact = new JcaPGPObjectFactory(pgpEncryptedData);
PGPEncryptedDataList encList = (PGPEncryptedDataList)pgpFact.nextObject();
// find the matching public key encrypted data packet.
PGPPublicKeyEncryptedData encData = null;
for (PGPEncryptedData pgpEnc: encList)
{
PGPPublicKeyEncryptedData pkEnc
= (PGPPublicKeyEncryptedData)pgpEnc;
if (pkEnc.getKeyID() == privateKey.getKeyID())
{
encData = pkEnc;
break;
}
}
if (encData == null)
{
throw new IllegalStateException("matching encrypted data not found");
}
// build decryptor factory
PublicKeyDataDecryptorFactory dataDecryptorFactory =
new JcePublicKeyDataDecryptorFactoryBuilder()
.setProvider("BC")
.build(privateKey);
InputStream clear = encData.getDataStream(dataDecryptorFactory);
byte[] literalData = Streams.readAll(clear);
clear.close();
// check data decrypts okay
if (encData.verify())
{
// parse out literal data
PGPObjectFactory litFact = new JcaPGPObjectFactory(literalData);
PGPLiteralData litData = (PGPLiteralData)litFact.nextObject();
byte[] data = Streams.readAll(litData.getInputStream());
return data;
}
throw new IllegalStateException("modification check failed");
}
private static void elgamalExample()
throws Exception
{
byte[] msg = Strings.toByteArray("Hello, world!");
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("DH", "BC");
kpGen.initialize(2048);
KeyPair kp = kpGen.generateKeyPair();
PGPKeyPair elgKp = new JcaPGPKeyPair(
PGPPublicKey.ELGAMAL_ENCRYPT, kp, new Date());
byte[] encData = createEncryptedData(elgKp.getPublicKey(), msg);
byte[] decData = extractPlainTextData(elgKp.getPrivateKey(), encData);
System.out.println("elgamal encryption msg length: " + msg.length + " enc.length: " + encData.length + " dec.length: " + decData.length);
System.out.println(Strings.fromByteArray(decData));
}
private static void ecExample()
throws Exception
{
byte[] msg = Strings.toByteArray("Hello, world!");
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("EC", "BC");
kpGen.initialize(new ECGenParameterSpec("P-256"));
KeyPair kp = kpGen.generateKeyPair();
PGPKeyPair ecdhKp = new JcaPGPKeyPair(PGPPublicKey.ECDH, kp, new Date());
byte[] encData = createEncryptedData(ecdhKp.getPublicKey(), msg);
// save encrypted string
Files.write(Paths.get("pgp-encrypted-string.dat"), encData);
// load encrypted string
byte[] encDataLoad = Files.readAllBytes(Paths.get("pgp-encrypted-string.dat"));
byte[] decData = extractPlainTextData(ecdhKp.getPrivateKey(), encDataLoad);
System.out.println("ec encryption msg length: " + msg.length + " enc.length: " + encData.length + " dec.length: " + decData.length);
System.out.println(Strings.fromByteArray(decData));
}
public static void main(String[] args)
throws Exception
{
Security.addProvider(new BouncyCastleProvider());
// you need the two files bcpg-jdk15on-165.jar and bcprov-jdk15to18-165.jar to run the example
System.out.println("Example from Java Cryptography: Tools and Techniques by David Hook & Jon Eaves");
System.out.println("get source files: https://www.bouncycastle.org/java-crypto-tools-src.zip");
elgamalExample();
ecExample();
}
}
This is the short output:
Example from Java Cryptography: Tools and Techniques by David Hook & Jon Eaves
get source files: https://www.bouncycastle.org/java-crypto-tools-src.zip
elgamal encryption msg length: 13 enc.length: 601 dec.length: 13
Hello, world!
ec encryption msg length: 13 enc.length: 200 dec.length: 13
Hello, world!
Added: As I now understand you're having a String like
This string needs an encryption
and you want to encrypt it with a rsa pgp public key:
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: BCPG v1.65
mI0EXr/nDgEEAKhB6ufAB954aBIlNjPCsryzUVLu0qkC/1RtnFHf+J6IVegV8Wi7
28V074inQcw6o6FTLtFTaLRP4+3eXNATdjGSjrvcP7k+nu50vydugHv43fPuCiZ7
6gbbMTE9gPiLPA2pS+SmQJnr9hOrD5rzwYP1yNNIsRJ9qmU5NeZyu+szABEBAAG0
DHRlc3RpZGVudGl0eYicBBABAgAGBQJev+cOAAoJEPBDuyqTbz/gY0YD/R+gDkfe
qPgNuk6iI2wLSGEeZRXr6Ru1cyG73CRvz7BjCpwWx039AdQzP9gkeo6MEj8Z0c73
obqEP8NtvvOcwC7+/QiGLTR2mgCsNhk54+iCGsvNbkpkr/rRoYZGyvb+rxui0A61
DCB1w5hdnyMg2OglFNrkaPfpNjMsTebfF5eS
=h1+m
-----END PGP PUBLIC KEY BLOCK-----
and get the encrypted string
-----BEGIN PGP MESSAGE-----
Version: BCPG v1.65
hIwD8EO7KpNvP+ABA/9JkOE9PDyS/kr/lZ1Uz+NCSe1JiNcKCXjbsUbvP8CT7Tf1
cKlgzIz1mQjdpkBtVpVhEnEjmUzFy2UCRKr4b4Wx7/1UL+370CICW5HgMoi5TgTg
MYRy5I9Uba/+JxcusjWB1JJHP4ofULziXRKLWAoSPLlglZDzSmV88hNo19rl39JZ
AbMhIS2edM9hHICefL/Yaiq90hGjKMRReVopu2tPUjNLGYP7QABAvWb3WQJMZoYT
HEsyjHxeyYQylAdYB7pWQA0++Z803iclvM3skN8FBt64ebDkqfxgbhs=
=je0r
-----END PGP MESSAGE-----
Now you'd like to decrypt this message with Kleoptatra, online (e.g. https://sela.io/pgp-en/) or in Java with the RSA pgp private key and the password 123456:
-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: BCPG v1.65
lQH+BF6/5w4BBACoQernwAfeeGgSJTYzwrK8s1FS7tKpAv9UbZxR3/ieiFXoFfFo
u9vFdO+Ip0HMOqOhUy7RU2i0T+Pt3lzQE3Yxko673D+5Pp7udL8nboB7+N3z7gom
e+oG2zExPYD4izwNqUvkpkCZ6/YTqw+a88GD9cjTSLESfaplOTXmcrvrMwARAQAB
/gMDAhhcE1oF/u8YYExKGLgriK5JpUUSsMFU0AOHP9/zZQr09437V0f/F4J87+9s
G30lDRikGwynEGRnAvIVwqq2F+iarKGGHCZCRgbyufXS7VK6wE/43lR0kSwA2VIM
ll/KbQKP1cSZv0rqtJ1tGL7cDHFEwq10gM4Bn75HOKyBzE9oERRKz37noAECsAZn
xuXGlEB5noqTT00RxsHjBA5Os04CtEz9N+OMrg47IR7AzSQUe90lG2F6W71dhJ6V
jQaf7D6JFU3dOWPW1eBb5FQhgYF92CFRizJ42lDCiTfl2FQU49MlwLd2ofNneuPo
aVuPoYUNKwbasyx4fo2vh6rrMyxmncCizMExvh6GIVgYd7EK9s6Gxq/duuOvly4O
ZAyIY2MOon0bDXxAYR2q/wdQLamnP7rAR4uMu24m/iOuBj6wwTR8v8hhsFFTp/4u
tebwWzLnPyyBYStnTF5IZ9ZJeVl5S3zdzNcrP9g8yXtItAx0ZXN0aWRlbnRpdHmI
nAQQAQIABgUCXr/nDgAKCRDwQ7sqk28/4GNGA/0foA5H3qj4DbpOoiNsC0hhHmUV
6+kbtXMhu9wkb8+wYwqcFsdN/QHUMz/YJHqOjBI/GdHO96G6hD/Dbb7znMAu/v0I
hi00dpoArDYZOePoghrLzW5KZK/60aGGRsr2/q8botAOtQwgdcOYXZ8jINjoJRTa
5Gj36TYzLE3m3xeXkg==
=y/tQ
-----END PGP PRIVATE KEY BLOCK-----
and get the decrypted string:
This string needs an encryption
To encrypt/decrypt in Java fortunately there are sample files available in the BouncyCastle Github-Repo: https://github.com/bcgit/bc-java/blob/master/pg/src/main/java/org/bouncycastle/openpgp/examples/. You may need to create a new PGP-keypair using RSA (RSAKeyPairGenerator.java) or ElGamal
(DSAElGamalKeyRingGenerator.java). With the generated keys you can encrypt or decrypt using KeyBasedFileProcessor.java and neccessary PGPExampleUtil.java.
I created the RSA key files with "-a testidentity 123456" as arguments, the encryption is done with "-e -ai plaintext.txt rsa_pub.asc" and the decryption goes with "-d plaintext.txt.asc rsa_secret.asc 123456".
I want to ask you some question about security on key in java. My code using RSA and AES for encrypt and decrypt a plainText. And I want to use my own password as a private key(AES) for verifies key(RSA). Because RSA are generate public and private key random. (In real case: private key is input by user and public key store in database for verification.)
This code is work find, but I want to know this code is correct or not? Please advice! Thank you.
My process:
1. generate a symmetric key
2. Encrypt the data with the symmetric key
3. Encrypt the symmetric key with rsa
4. send the encrypted key and the data
5. Decrypt the encrypted symmetric key with rsa
6. decrypt the data with the symmetric key
7. done
import java.io.UnsupportedEncodingException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class AES_RSA {
private static byte[] key;
private static SecretKeySpec secretKey;
public static void main(String[] args){
try {
//1. Generate Symmetric Key (AES with 128 bits)
String password = "123456";
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(128); // The AES key size in number of bits
setKey(password);
//2. Encrypt plain text using AES
String plainText = "Please encrypt me urgently...";
Cipher aesCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
aesCipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] byteCipherText = aesCipher.doFinal(plainText.getBytes());
//3. Encrypt the key using RSA public key
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair keyPair = kpg.generateKeyPair();
PublicKey puKey = keyPair.getPublic();
PrivateKey prKey = keyPair.getPrivate();
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.PUBLIC_KEY, puKey);
byte[] encryptedKey = cipher.doFinal(secretKey.getEncoded()/*Seceret Key From Step 1*/);
//4. Send encrypted data (byteCipherText) + encrypted AES Key (encryptedKey)
//5. On the client side, decrypt symmetric key using RSA private key
cipher.init(Cipher.PRIVATE_KEY, prKey);
byte[] decryptedKey = cipher.doFinal(encryptedKey);
//6. Decrypt the cipher using decrypted symmetric key
SecretKey originalKey = new SecretKeySpec(decryptedKey , 0, decryptedKey.length, "AES");
Cipher aesCipher1 = Cipher.getInstance("AES/ECB/PKCS5PADDING");
aesCipher1.init(Cipher.DECRYPT_MODE, originalKey);
byte[] bytePlainText = aesCipher1.doFinal(byteCipherText);
String plainText1 = new String(bytePlainText);
//7. Done! 'Please encrypt me urgently...'
System.out.println(plainText1);
}catch (Exception e) {}
}
public static void setKey(String myKey)
{
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-256");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
You pseudo-steps are correct, but your description not. For example, you normally keep RSA private key and distribute RSA public key.
But a few suggestions for creating better code.
I suggest to use PKCS5 for creating password-based secret keys rather than a simple hash. Java's PBEKeySpec is a class for generating such secret keys. Here is a small sample code which you can use for your setKey() routine (adjust it as you prefer):
SecretKeyFactory skf = SecretKeyFactory.getInstance("AES");
SecretKey key = skf.generateSecret(new PBEKeySpec(password.getBytes("UTF-8"), salt, 10000));
Never use ECB mode of operation for encrypting data. In worse case, use CBC with randomized IV.
You got something wrong. RSA private key is kept private on server, but RSA public key is distributed freely between clients(normally). You are doing this in the other way.
This is just a suggestion, but I think it is better to use RSA/ECB/OAEPWithSHA-256AndMGF1Padding rather than RSA/ECB/PKCS1Padding for RSA padding. But I think it is not necessary.
In general, you must add a hash or HMAC for authenticating your encrypted data too. But you don't have any authenticating mechanism right now.
Update: Based on design of your mechanism, you cannot securely add an authentication method for detecting active attacks(such as man-in-the-middle). Check comments from Maarten too.
These are the problems that I found. The most important one is just using RSA key-pair in an incorrect way.
Im having trouble with my attempt to create a small programme using hybrid encryption with AES and RSA. It works just fine using only symmetric encryption AES which i have tried, but when i try to implement RSA to wrap the AES encrypted message and key i just cant get it to work.
I have understood that a programme like this can be done using outputstreams or cipherstreams but I´d like to solve it this way if it is possible. In other words id like a user to enter any string into the JOptionInputDialog and get it encrypted with AES key and then the AES key encrpyted with RSA public key and then decrypted with a private RSA key.
I want the answer to display in the same JOptionPane window. In example :
The encrypted text : jfjfjh
The decrypted text : Hello
I have issues right now understanding how to get that string decrypted with the private RSA key. I dont know what i am missing or doing wrong. From any examples ive been googling for the past week and a half i think it looks fine. I must be missing something that is right infront of my eyes but i cant see it since i sit up for too many hours trying to find a different approach ( i think ive changed it a million times but i cant show you all my approaches so this is the one i share with you. Id be really thankful for any kind of help. So here is my code: (Hope you can understand as some words are in my language)
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.swing.JOptionPane;
/**
*
* #author Patricia
*/
public class EncryptionDecryption {
/**
* #param args the command line arguments
* #throws java.lang.Exception
*/
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
//Creating assymmetric keys RSA ( A public Key and Private Key )
KeyPairGenerator gen2 = KeyPairGenerator.getInstance("RSA");
gen2.initialize(1024);
KeyPair keyPair = gen2.genKeyPair();
PrivateKey privatnyckel = keyPair.getPrivate();
PublicKey publiknyckel = keyPair.getPublic();
//Create assymmetric key AES //Create key generator
KeyGenerator gen = KeyGenerator.getInstance("AES"); //Returns keygenerator object that generates key for specified algorithm in this case AES
SecureRandom random = new SecureRandom();
gen.init(random);
// create a key
SecretKey AES = gen.generateKey();
//get the raw key bytes
byte[] symmetriskNyckel =AES.getEncoded(); //Returns copy of the key bytes
//Create cipher based upon AES, encrypt the message with AES key
Cipher cipher = Cipher.getInstance("AES");
//Initialize cipher with secret key AES
cipher.init(Cipher.ENCRYPT_MODE, AES);
// get the text to encrypt with AES key
String inputText1 = JOptionPane.showInputDialog(" Enter the secret message");
//Encrypt the plaintext message you wanna send with the symmetric key AES;
byte[] kryptera = cipher.doFinal(inputText1.getBytes());
//encrypt AES key with RSA
Cipher pipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
pipher.init(Cipher.WRAP_MODE, publiknyckel);
byte[] krypteradAESNyckel = cipher.wrap(AES);
JOptionPane.showMessageDialog(null, "AES key encrypted with RSA public key " + krypteradAESNyckel);
// re-initialise the cipher to be in decrypt mode
Cipher flipher = Cipher.getInstance("RSA");
flipher.init(Cipher.UNWRAP_MODE, privatnyckel );
// decrypt message
byte [] dekryptera = flipher.unwrap(kryptera);
JOptionPane.showMessageDialog
(null, "AES symmetrisk nyckel " +symmetriskNyckel );
// and display the results //
JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
"Texten krypterad " + new String(kryptera) + "\n"
+ "Text dekrypterat: " + new String(dekryptera));
JOptionPane.showMessageDialog(null, "\n RSA assymmetrisk privat nyckel " + privatnyckel
+ "RSA assymmetrisk publik nyckel" + publiknyckel);
// end example
System.exit(0);
}
}
I think your variable names and comments are fine to start with. When working with something new, write notes to yourself in the code. You can come back later once it works and refactor with rich, meaningful names, and trim the comments for clarity, so that they speak to you six months or a year from now to remind you of what you were thinking of at the time that you wrote this. (And I think Swedish names are just as good as English.)
As JB Nizet points out, you are unwrapping kryptera when you should be unwrapping the symmetric key contained in krypteradAESNyckel. Next, you would decrypt kryptera with the recovered symmetric key. (Your code justs outputs the earlier symmetriskNyckel without having actually unwrapped it freshly from krypteradAESNyckel.)
I also notice that in one case you
Cipher.getInstance("RSA/ECB/PKCS1Padding");
but later you
Cipher.getInstance("RSA");
I would make them consistent, both "RSA/ECB/PKCS1Padding". This attention to detail is just as important as clear variable names and meaningful comments.
Following this discussion it's a simple tutorial how to sign a string by using ECDSA algorithm in java without using any third-party libraries. But the question is:
How can i convert the public and the private key into a string ? (Because i want to send them into a database).
Can somebody help me create a simple tutorial of how to verify the message by using ECDSA algorithm in java ? at this point i need to include the signature and public key as the verification method.
Here's my scenario in my java code, assume that there's a sender side and the recipient side:
Sender side
package sender;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
public class Sign {
public static void main(String[] args) throws Exception {
/*
* Generate a key pair
*/
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
keyGen.initialize(256, random);
KeyPair pair = keyGen.generateKeyPair();
/*
Generate the private and the public key
*/
PrivateKey priv = pair.getPrivate();
/*
*and then Convert the priv key into a String;
*HOW can i do that ? this what i'm asking
*/
PublicKey pub = pair.getPublic();
/*
Convert the pub key into a String;
HOW can i do that ? this what i'm asking
*/
/*
-------Encrypt the pub and the priv key, i do with my own code
-------Store the enrypted pub & priv key into the database
-------I'm doing this with my own code
*/
/*
* Create a Signature object and initialize it with the private key
*/
Signature dsa = Signature.getInstance("SHA1withECDSA");
dsa.initSign(priv);
String str = "This is string to sign";
byte[] strByte = str.getBytes("UTF-8");
dsa.update(strByte);
/*
* Now that all the data to be signed has been read in, generate a
* signature for it
*/
byte[] realSig = dsa.sign();
System.out.println("Signature: " +
new BigInteger(1, realSig).toString(16));
/*
and Then i'm storing this signature into my database.
i have done with this
*/
}
}
Recipient side
package recipient;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
public class Verify {
public static void main(String[] args) throws Exception {
/*
Step one, taking public key from the database.
Step two, receive the message + signature.
Step three, split the message and signature into an "array[0]" for message,
and "array[1] for the signature"
Verify the signature <--- Here's what im asking to anybody,
how can i do, i mean the sample code ?
*/
}
}
Sorry for my bad English :D
You're asking a lot of different questions about dealing with ECDSA. I will address your first question about database storage here. I recommend you do some additional research on the mechanics of ECDSA if you want to learn about how to properly use it. Examples given here would be hard to follow out of context anyway.
To store keys as a string, you must first retrieve the byte array representing the key in its encoded format (note: encoded not encrypted). This can be done by using the getEncoded() method from class Key which is the superinterface of both PublicKey and PrivateKey.
Example:
PrivateKey key = // ...
byte[] enc_key = key.getEncoded();
// Byte array to string
StringBuilder key_builder = new StringBuilder();
for(byte b : enc_key){
key_builder.append(String.format("%02x", b));
}
String serialized_key = key_builder.toString();
To load the key again from a database you parse the string to a byte array, pass it into the appropriate key specification and then retrieve it by using a key factory.
Example:
String serialzed_key = // ...
byte[] encoded_key = // serialzed_key -> byte array conversion
// If key is private, use PKCS #8
PKCS8EncodedKeySpec formatted_private = new PKCS8EncodedKeySpec(encoded_key);
// or, if key is public, use X.509
X509EncodedKeySpec formatted_public = new X509EncodedKeySpec(encoded_key);
// Retrieve key using KeyFactory
KeyFactory kf = KeyFactory.getInstance("EC");
PublicKey pub = kf.generatePublic(formatted_public);
PrivateKey priv = kf.generatePrivate(formatted_private);
If all you mean to do is to use ECDSA as a signature algorithm, verification is identical to signing using using the verify methods instead of the sign methods, as follows:
byte[] message_hash = // ...
byte[] candidate_message = // ...
PublicKey pub = // ...
Signature dsa = Signature.getInstance("SHA1withECDSA");
dsa.initVerify(pub);
dsa.update(candidate_message);
boolean success = dsa.verify(message_hash);