I am working on a hybrid encryption mechanism in java that involves encrypting message using 3DES encryption algorithm and then encrypt its key using RSA encryption mechanism at the sender side. Once delivered to the receiver side, the encrypted 3DES key is decrypted using RSA decryption mechanism and then is used to decrypt the cipher text.
Once I obtain the decrypted 3DES key its string value is the same but byte [] is not the same instead returns a 2's complement of the original key.
How can I get the decrypted 3DES to be the same as the originally generated 3DES in byte [] form at the receiver side?
Below is the code I am using for my hybrid encryption mechanism:
package hybrid_implementation;
import java.security.Key;
import java.security.InvalidKeyException;
import java.security.spec.InvalidKeySpecException;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.IllegalBlockSizeException;
public class Hybrid_Implementation {
//RSA_Encryption Algorithm Required Variables
private static final BigInteger one = new BigInteger("1");
private static final SecureRandom random = new SecureRandom();
private BigInteger privatekey;
private BigInteger publickey;
private BigInteger modulus;
//3DES_Encryption Algorithm Required Variables
private byte[] DES_Key;
private SecretKeyFactory keyfactory;
private DESedeKeySpec spec;
private Key deskey;
private int DES_Key_Length;
private byte[] data;
private Cipher cipher;
private String CipherText;
private byte [] CIPHERText;
Hybrid_Implementation() throws InvalidKeyException,
NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException
{
DES_Key_Generator();
RSA_Key_Generator(999);
}
//3DES Encryption-Decryption Algorithm with 2 differnt keys
private String DES_Encryption(String plaintext) throws InvalidKeyException,
IllegalBlockSizeException, BadPaddingException
{
data = plaintext.getBytes();
cipher.init(Cipher.ENCRYPT_MODE, deskey);
CIPHERText = cipher.doFinal(data);
StringBuilder hexCiphertext = new StringBuilder();
for(int i=0; i<CIPHERText.length; i++)
{
int v = CIPHERText[i] & 0xff;
v+=0x100;
String temp = Integer.toString(v,16);
hexCiphertext.append(temp).substring(1);
}
return hexCiphertext.toString();
}
private String DES_Decryption(byte [] key, byte [] encrypted_text) throws
InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
InvalidKeySpecException
{
spec = new DESedeKeySpec(key);
deskey = keyfactory.generateSecret(spec);
byte[] plaintext = cipher.doFinal(encrypted_text);
StringBuilder decrypttext= new StringBuilder();
for (int i = 0; i < plaintext.length; i++)
decrypttext.append((char) plaintext[i]);
String decrypted_plaintext = decrypttext.toString();
return decrypted_plaintext;
}
private void DES_Key_Generator() throws InvalidKeyException,
NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException
{
Random rnd = new Random();
String key = rnd.toString();
DES_Key = key.getBytes();
spec = new DESedeKeySpec(DES_Key);
keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
cipher = Cipher.getInstance("desede");
}
//RSA Encryption-Decryption Algorithm
private BigInteger RSA_Encryption(BigInteger des_Key ) //RSA Encryption of
3DES Key
{
BigInteger encrypted_DES_Key = des_Key.modPow(publickey, modulus);
return encrypted_DES_Key;
}
private BigInteger RSA_Decryption(BigInteger encrypted_DES_Key) //RSA
Decryption of 3DES Key
{
BigInteger des_Key = encrypted_DES_Key.modPow(privatekey, modulus);
return des_Key;
}
private void RSA_Key_Generator(int number) //RSA Public - Private Key
Generation
{
BigInteger p = BigInteger.probablePrime(number/2,random);
BigInteger q = BigInteger.probablePrime(number/2, random);
BigInteger phi = (p.subtract(one)).multiply(q.subtract(one));
modulus = p.multiply(q);
publickey = new BigInteger("65537");
privatekey = publickey.modInverse(phi);
}
private String encryption(String plaintext) throws InvalidKeyException,
IllegalBlockSizeException, BadPaddingException
{
String cipher_text = DES_Encryption(plaintext);
BigInteger RSA_DESKey = RSA_Encryption(new BigInteger(DES_Key));
String temp_key = RSA_DESKey.toString();
DES_Key_Length = temp_key.length();
CipherText ="";
CipherText = new
StringBuilder().append(temp_key).append(cipher_text).toString();
return CipherText;
}
private String decryption(String encrypted_text) throws InvalidKeyException,
InvalidKeySpecException, IllegalBlockSizeException, BadPaddingException
{
StringBuilder encryptedkey = new StringBuilder();
for(int i = 0 ; i < DES_Key_Length; i++)
encryptedkey.append (encrypted_text.charAt(i));
StringBuilder cipheredtext = new StringBuilder();
for(int j = DES_Key_Length ; j< encrypted_text.length() ; j++)
cipheredtext.append (encrypted_text.charAt(j));
BigInteger DES_Encrypted_Key = new BigInteger(encryptedkey.toString());
BigInteger DES_KEY = RSA_Decryption(DES_Encrypted_Key);
byte[] decrypt_key = DES_KEY.toByteArray();
String plaintext =
DES_Decryption(decrypt_key,cipheredtext.toString().getBytes());
return plaintext;
}
/**
*
* #param args
* #throws InvalidKeyException
* #throws IllegalBlockSizeException
* #throws BadPaddingException
* #throws java.security.NoSuchAlgorithmException
* #throws java.security.spec.InvalidKeySpecException
* #throws javax.crypto.NoSuchPaddingException
*/
public static void main(String[] args) throws InvalidKeyException,
IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException,
InvalidKeySpecException, NoSuchPaddingException {
String plaintext;
Hybrid_Implementation hi = new Hybrid_Implementation ();
Scanner sc = new Scanner(System.in);
System.out.print("Enter Text = ");
plaintext = sc.nextLine();
String encrypted_text = hi.encryption(plaintext);
String decrypted_text = hi.decryption(encrypted_text);
System.out.println("Plain Text Entered = "+plaintext);
System.out.println("Encrypted Text = "+encrypted_text);
System.out.println("Decrypted Text = "+decrypted_text);
}
}
The output I receive is:
enter image description here
Whereas the decrypted text is not the same as the entered plain text
There are multiple (many) issues with your code
The main issue (why you get incorrect decrypted text) is in the ciphertext encoding. The ciphertext you are decrypting with 3DES is different than the one you got from the encryption (your "hex encoding" is simply buggy). Just debug you program (and print the values after encryption and before decryption) and you should find it. I'd advice using something standard, such as working hexadecimal or base64 encoding.
Other issues:
you are using "textbook RSA" which is not really secure, so I hope you are doing that for learning / assignment purposes, not real life encryption application. As already commented, using RSA should be always with padding (e.g. RSA/ECB/PKCS1Padding or OAEP)
Generating random keys - you should use SecureRandom instead of Random (which is not really random) or - much better - a KeyGenerator
DESede without providing any IV is using ECB mode, which has its weaknesses. So using symmetric encryption you should provide random IV and specify the encryption mode explicitly (e.g. DESede/CBC/PKCS5Padding)
for each operation after doFinal() you should use a new Cipher instance with initialized decrpytion mode
I have a blog about encryption with a few examples, you may take inspiration from.
Related
This question already has an answer here:
RSA encyrption - converting between bytes array and String [duplicate]
(1 answer)
Closed 2 years ago.
we are trying RSA Encryption & Decryption and the issue happens while decrypting. This is our decryption code
Cipher oaepFromInit = Cipher.getInstance("RSA/ECB/OAEPPadding");
OAEPParameterSpec oaepParams = new OAEPParameterSpec("SHA-1", "MGF1", new MGF1ParameterSpec("SHA-1"), PSpecified.DEFAULT);
oaepFromInit.init(Cipher.DECRYPT_MODE, rsaPrivateKey, oaepParams);
byte[] dec = oaepFromInit.doFinal(encrytpedData.getBytes());
The encrytpedData is like this
s11Pyj5rrVOfOiWtxpGq+K5D+pYi16CyyX/EwKfMErBkHJ4aVlTmnhrfeCS7LEeXgTs3gkFp96I/oTedG/rXxF2hTAmMH40k0joKJbRtzO858/0dcaaE1uNzr/rI0Jj3ebXPLGhefCMNNpyFH5V4ukVo6vtev5Z9U8oNkUQolbX/r5jJJomkKCCnzGoHMdQg5dafj9Sw/qakO13501YBrkxS0i9ca0GZ8Ll42NwkOZuInh+MAu+gYW4vAr284eJsqgLgTp0+MS1tmfwR6EXgspk1nYR/U84P3MBZAdpmD3nxsVV3iVOCUeoqVyd4kw7M2pvXev6hMbMN4P1nnomo8g==
An error exception was thrown saying javax.crypto.IllegalBlockSizeException: Data must not be longer than 256 bytes
We looked into this link getting a IllegalBlockSizeException: Data must not be longer than 256 bytes when using rsa, but the issue was with the way we were feeding the encrytpedData.
This is a code we got online
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair kp = kpg.generateKeyPair();
RSAPublicKey pubkey = (RSAPublicKey) kp.getPublic();
RSAPrivateKey privkey = (RSAPrivateKey) kp.getPrivate();
// --- encrypt given algorithm string
Cipher oaepFromAlgo = Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding");
oaepFromAlgo.init(Cipher.ENCRYPT_MODE, pubkey);
byte[] ct = oaepFromAlgo.doFinal("chakka".getBytes(StandardCharsets.UTF_8));
// --- decrypt given OAEPParameterSpec
Cipher oaepFromInit = Cipher.getInstance("RSA/ECB/OAEPPadding");
OAEPParameterSpec oaepParams = new OAEPParameterSpec("SHA-1", "MGF1", new MGF1ParameterSpec("SHA-1"), PSpecified.DEFAULT);
oaepFromInit.init(Cipher.DECRYPT_MODE, privkey, oaepParams);
byte[] pt = oaepFromInit.doFinal(ct);
System.out.println("Printing decoded string");
System.out.println(new String(pt, StandardCharsets.UTF_8));
Here they are supplying the encrypted array directly and works fine, but in our case we are getting encrytpedData as String. Both the codes are same but the supply of encrypted data differs.
byte[] dec = oaepFromInit.doFinal(encrytpedData.getBytes());
This is where we are getting the exception, so we tried converting the encrytpedData to byte[] in a different way via these two links
RSA encyrption - converting between bytes array and String [duplicate]
IllegalBlockSizeException when trying to encrypt and decrypt a string with AES
So we tried like this
byte[] dec = oaepFromInit.doFinal(Base64.getDecoder().decode(encrytpedData)); which resulted in this javax.crypto.BadPaddingException: Message is larger than modulus.
byte[] dec = oaepFromInit.doFinal(encrytpedData.getBytes(StandardCharsets.UTF_8)); which gave the same old exception javax.crypto.IllegalBlockSizeException: Data must not be longer than 256 bytes.
Any help would be appreciated
The below full example code is taken from my private cross-platform project and should work. It encrypts a string using RSA encryption with a 2048 key pair and uses OAEP padding with SHA-1 as hash.
The encrypted data are in base64 encoding. For demonstration purpose I'm using static (hardcoded) keys in PEM-format - never ever do this in production.
You can run the code online here: https://repl.it/#javacrypto/CpcJavaRsaEncryptionOaepSha1String
this is the output:
RSA 2048 encryption OAEP SHA-1 string
plaintext: The quick brown fox jumps over the lazy dog
* * * encrypt the plaintext with the RSA public key * * *
ciphertextBase64: pSPayOK79NMPLpaQOp8L7dOTdLeS+jVU5cKPF5mDOvuKtnOjf/NYfgsf1JWa5Ud/fzsXrSN8I/8KAs/freagOYflv6PGUHZ7cYk1iX6sO5cmdD0Mfglj39NxczbqCK3FG20hQfa01ZaOu/dV8+QvVx851ph1nEl8arNML5ohhjIdZTxR3olGouGzDJmuJkDlv2fJICP7sdMnvl7t21QI701I2xR01eatD5src5fY//EIOEjSoTesCBZwEUz1S3UpclNqGONAqaYqlscdTyAlY3Hg8smJRqKWk7ZWKSTYsocBbFeTvcNy75LG/xyILM0l4U+NnwGUypkjR2vJRGVQtw==
* * * decrypt the ciphertext with the RSA private key * * *
ciphertextReceivedBase64: pSPayOK79NMPLpaQOp8L7dOTdLeS+jVU5cKPF5mDOvuKtnOjf/NYfgsf1JWa5Ud/fzsXrSN8I/8KAs/freagOYflv6PGUHZ7cYk1iX6sO5cmdD0Mfglj39NxczbqCK3FG20hQfa01ZaOu/dV8+QvVx851ph1nEl8arNML5ohhjIdZTxR3olGouGzDJmuJkDlv2fJICP7sdMnvl7t21QI701I2xR01eatD5src5fY//EIOEjSoTesCBZwEUz1S3UpclNqGONAqaYqlscdTyAlY3Hg8smJRqKWk7ZWKSTYsocBbFeTvcNy75LG/xyILM0l4U+NnwGUypkjR2vJRGVQtw==
decryptedtext: The quick brown fox jumps over the lazy dog
Security warning: the code does not have any exception handling, uses static (hardcoded) keys and is for educational purpose only.
code:
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.PSource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.*;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class Main {
public static void main(String[] args) throws GeneralSecurityException, IOException {
System.out.println("RSA 2048 encryption OAEP SHA-1 string");
String dataToEncryptString = "The quick brown fox jumps over the lazy dog";
byte[] dataToEncrypt = dataToEncryptString.getBytes(StandardCharsets.UTF_8);
System.out.println("plaintext: " + dataToEncryptString);
// # # # usually we would load the private and public key from a file or keystore # # #
// # # # here we use hardcoded keys for demonstration - don't do this in real programs # # #
String filenamePrivateKeyPem = "privatekey2048.pem";
String filenamePublicKeyPem = "publickey2048.pem";
// encryption
System.out.println("\n* * * encrypt the plaintext with the RSA public key * * *");
PublicKey publicKeyLoad = getPublicKeyFromString(loadRsaPublicKeyPem());
// use this in production
//PublicKey publicKeyLoad = getPublicKeyFromString(loadRsaKeyPemFile(filenamePublicKeyPem));
String ciphertextBase64 = base64Encoding(rsaEncryptionOaepSha1(publicKeyLoad, dataToEncrypt));
System.out.println("ciphertextBase64: " + ciphertextBase64);
// transport the encrypted data to recipient
// receiving the encrypted data, decryption
System.out.println("\n* * * decrypt the ciphertext with the RSA private key * * *");
String ciphertextReceivedBase64 = ciphertextBase64;
//String ciphertextReceivedBase64 = "l4G3O42LtjI9KkzvcF7SQcpqrkOMJw1sWVuI3FCZ1g+Sp/t05E3ZEXyVV/FnadkKVgmpWBifaYPEdKNBTbuts2F1DfrDz1v14lKlMOcqkJB8OmJUAiKJ1ic414R7M5fECKruqkzOdKlTtdb3MI49Ygrzd/cJxOGEvONo3DAOq1kZvZdmyW+K8m807g2qoy833EHyj9NjVZHuDzXi8fMxbIAI5MrN8ykXZBxkFOAGiITEFbGPxu6gBOPJKsPWJ0SVU53CiI1YwGc76/ov4c7FIA1ZeVsJXKo8CEfYuUc7PKIJ3e5Z7CbiNgr4Z5720Xbi0drUBk/LlYq6m8s/zEIMaQ==";
System.out.println("ciphertextReceivedBase64: " + ciphertextReceivedBase64);
PrivateKey privateKeyLoad = getPrivateKeyFromString(loadRsaPrivateKeyPem());
// use this in production
//PrivateKey privateKeyLoad = getPrivateKeyFromString(loadRsaKeyPemFile(filenamePrivateKeyPem));
byte[] ciphertextReceived = base64Decoding(ciphertextReceivedBase64);
byte[] decryptedtextByte = rsaDecryptionOaepSha1(privateKeyLoad, ciphertextReceived);
System.out.println("decryptedtext: " + new String(decryptedtextByte, StandardCharsets.UTF_8));
}
public static byte[] rsaEncryptionOaepSha1 (PublicKey publicKey, byte[] plaintextByte) throws NoSuchAlgorithmException,
InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException, InvalidAlgorithmParameterException {
byte[] ciphertextByte = null;
Cipher encryptCipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING");
//OAEPParameterSpec oaepParameterSpecJCE = new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT);
// note: SHA1 is the default for Java
OAEPParameterSpec oaepParameterSpecJCE = new OAEPParameterSpec("SHA1", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT);
encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey, oaepParameterSpecJCE);
ciphertextByte = encryptCipher.doFinal(plaintextByte);
return ciphertextByte;
}
public static byte[] rsaDecryptionOaepSha1 (PrivateKey privateKey, byte[] ciphertextByte) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException {
byte[] decryptedtextByte = null;
Cipher decryptCipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING");
//OAEPParameterSpec oaepParameterSpecJCE = new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT);
OAEPParameterSpec oaepParameterSpecJCE = new OAEPParameterSpec("SHA1", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT);
decryptCipher.init(Cipher.DECRYPT_MODE, privateKey, oaepParameterSpecJCE);
decryptedtextByte = decryptCipher.doFinal(ciphertextByte);
return decryptedtextByte;
}
private static String base64Encoding(byte[] input) {
return Base64.getEncoder().encodeToString(input);
}
private static byte[] base64Decoding(String input) {
return Base64.getDecoder().decode(input);
}
private static String loadRsaPrivateKeyPem() {
// this is a sample key - don't worry !
return "-----BEGIN PRIVATE KEY-----\n" +
"MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDwSZYlRn86zPi9\n" +
"e1RTZL7QzgE/36zjbeCMyOhf6o/WIKeVxFwVbG2FAY3YJZIxnBH+9j1XS6f+ewjG\n" +
"FlJY4f2IrOpS1kPiO3fmOo5N4nc8JKvjwmKtUM0t63uFFPfs69+7mKJ4w3tk2mSN\n" +
"4gb8J9P9BCXtH6Q78SdOYvdCMspA1X8eERsdLb/jjHs8+gepKqQ6+XwZbSq0vf2B\n" +
"MtaAB7zTX/Dk+ZxDfwIobShPaB0mYmojE2YAQeRq1gYdwwO1dEGk6E5J2toWPpKY\n" +
"/IcSYsGKyFqrsmbw0880r1BwRDer4RFrkzp4zvY+kX3eDanlyMqDLPN+ghXT1lv8\n" +
"snZpbaBDAgMBAAECggEBAIVxmHzjBc11/73bPB2EGaSEg5UhdzZm0wncmZCLB453\n" +
"XBqEjk8nhDsVfdzIIMSEVEowHijYz1c4pMq9osXR26eHwCp47AI73H5zjowadPVl\n" +
"uEAot/xgn1IdMN/boURmSj44qiI/DcwYrTdOi2qGA+jD4PwrUl4nsxiJRZ/x7PjL\n" +
"hMzRbvDxQ4/Q4ThYXwoEGiIBBK/iB3Z5eR7lFa8E5yAaxM2QP9PENBr/OqkGXLWV\n" +
"qA/YTxs3gAvkUjMhlScOi7PMwRX9HsrAeLKbLuC1KJv1p2THUtZbOHqrAF/uwHaj\n" +
"ygUblFaa/BTckTN7PKSVIhp7OihbD04bSRrh+nOilcECgYEA/8atV5DmNxFrxF1P\n" +
"ODDjdJPNb9pzNrDF03TiFBZWS4Q+2JazyLGjZzhg5Vv9RJ7VcIjPAbMy2Cy5BUff\n" +
"EFE+8ryKVWfdpPxpPYOwHCJSw4Bqqdj0Pmp/xw928ebrnUoCzdkUqYYpRWx0T7YV\n" +
"RoA9RiBfQiVHhuJBSDPYJPoP34kCgYEA8H9wLE5L8raUn4NYYRuUVMa+1k4Q1N3X\n" +
"Bixm5cccc/Ja4LVvrnWqmFOmfFgpVd8BcTGaPSsqfA4j/oEQp7tmjZqggVFqiM2m\n" +
"J2YEv18cY/5kiDUVYR7VWSkpqVOkgiX3lK3UkIngnVMGGFnoIBlfBFF9uo02rZpC\n" +
"5o5zebaDImsCgYAE9d5wv0+nq7/STBj4NwKCRUeLrsnjOqRriG3GA/TifAsX+jw8\n" +
"XS2VF+PRLuqHhSkQiKazGr2Wsa9Y6d7qmxjEbmGkbGJBC+AioEYvFX9TaU8oQhvi\n" +
"hgA6ZRNid58EKuZJBbe/3ek4/nR3A0oAVwZZMNGIH972P7cSZmb/uJXMOQKBgQCs\n" +
"FaQAL+4sN/TUxrkAkylqF+QJmEZ26l2nrzHZjMWROYNJcsn8/XkaEhD4vGSnazCu\n" +
"/B0vU6nMppmezF9Mhc112YSrw8QFK5GOc3NGNBoueqMYy1MG8Xcbm1aSMKVv8xba\n" +
"rh+BZQbxy6x61CpCfaT9hAoA6HaNdeoU6y05lBz1DQKBgAbYiIk56QZHeoZKiZxy\n" +
"4eicQS0sVKKRb24ZUd+04cNSTfeIuuXZrYJ48Jbr0fzjIM3EfHvLgh9rAZ+aHe/L\n" +
"84Ig17KiExe+qyYHjut/SC0wODDtzM/jtrpqyYa5JoEpPIaUSgPuTH/WhO3cDsx6\n" +
"3PIW4/CddNs8mCSBOqTnoaxh\n" +
"-----END PRIVATE KEY-----";
}
private static String loadRsaPublicKeyPem() {
// this is a sample key - don't worry !
return "-----BEGIN PUBLIC KEY-----\n" +
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA8EmWJUZ/Osz4vXtUU2S+\n" +
"0M4BP9+s423gjMjoX+qP1iCnlcRcFWxthQGN2CWSMZwR/vY9V0un/nsIxhZSWOH9\n" +
"iKzqUtZD4jt35jqOTeJ3PCSr48JirVDNLet7hRT37Ovfu5iieMN7ZNpkjeIG/CfT\n" +
"/QQl7R+kO/EnTmL3QjLKQNV/HhEbHS2/44x7PPoHqSqkOvl8GW0qtL39gTLWgAe8\n" +
"01/w5PmcQ38CKG0oT2gdJmJqIxNmAEHkatYGHcMDtXRBpOhOSdraFj6SmPyHEmLB\n" +
"ishaq7Jm8NPPNK9QcEQ3q+ERa5M6eM72PpF93g2p5cjKgyzzfoIV09Zb/LJ2aW2g\n" +
"QwIDAQAB\n" +
"-----END PUBLIC KEY-----";
}
public static PrivateKey getPrivateKeyFromString(String key) throws GeneralSecurityException {
String privateKeyPEM = key;
privateKeyPEM = privateKeyPEM.replace("-----BEGIN PRIVATE KEY-----", "");
privateKeyPEM = privateKeyPEM.replace("-----END PRIVATE KEY-----", "");
privateKeyPEM = privateKeyPEM.replaceAll("[\\r\\n]+", "");
byte[] encoded = Base64.getDecoder().decode(privateKeyPEM);
KeyFactory kf = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
PrivateKey privKey = (PrivateKey) kf.generatePrivate(keySpec);
return privKey;
}
public static PublicKey getPublicKeyFromString(String key) throws GeneralSecurityException {
String publicKeyPEM = key;
publicKeyPEM = publicKeyPEM.replace("-----BEGIN PUBLIC KEY-----", "");
publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");
publicKeyPEM = publicKeyPEM.replaceAll("[\\r\\n]+", "");
byte[] encoded = Base64.getDecoder().decode(publicKeyPEM);
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey pubKey = (PublicKey) kf.generatePublic(new X509EncodedKeySpec(encoded));
return pubKey;
}
private static String loadRsaKeyPemFile(String filename) throws IOException {
return new String(Files.readAllBytes(Paths.get(filename)), StandardCharsets.UTF_8);
}
}
Generating a Keypair, encoding and decoding with byte array works fine.
I would like to store both the private and public keys as Strings. This is for experimenting purposes. I would like to investigate how I can store a password that has to be decoded before used.
I used string.getBytes() and new String( bytes) to convert the byte array to a String and vv.
When I try to store & retrieve these byte arrays with Strings, use them encoding a secret text, then I get this exception:
Exception in thread "main" java.security.spec.InvalidKeySpecException:
java.security.InvalidKeyException: IOException: ObjectIdentifier() --
Invalid DER encoding, not ended
The solution, thanks to James K Polk, is in the answer.
Thank you #James K Polk!! This really helped me in finishing my experiments! When you post an answer I will "V" and "+1" that answer!
Using the answer of James K Polk, I rewrote the experimental example:
import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class KeyPairToString {
private static final String ALGORITHM = "RSA";
private static byte[] encrypt(byte[] publicKey, byte[] inputData) throws Exception {
PublicKey key = KeyFactory.getInstance(ALGORITHM) /* ExceptionL Invalid DER encoding */
.generatePublic(new X509EncodedKeySpec(publicKey));
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(inputData);
}
private 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);
return cipher.doFinal(inputData);
}
private static KeyPair generateKeyPair()
throws NoSuchAlgorithmException, NoSuchProviderException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
keyGen.initialize(512, random);
return keyGen.generateKeyPair();
}
private static String bytesToString(byte[] bytes) {
return new String(bytes);
}
private static byte[] stringToBytes(String astring) {
return astring.getBytes();
}
private static String bytesToEncodedString(byte[] bytes) {
return Base64.getEncoder().encodeToString(bytes);
}
private static byte[] encodedStringToBytes(String encodedString) {
return Base64.getDecoder().decode(encodedString);
}
public static void main(String[] args) throws Exception {
KeyPair generateKeyPair = generateKeyPair();
byte[] publicKey = generateKeyPair.getPublic().getEncoded();
byte[] privateKey = generateKeyPair.getPrivate().getEncoded();
// Byte array
String secretText = "hi this is secret johan here";
byte[] encryptedData = encrypt(publicKey, secretText.getBytes());
byte[] decryptedData = decrypt(privateKey, encryptedData);
System.out.println(new String(decryptedData));
// Now with Strings
String encodedPublicKeyString = bytesToEncodedString(publicKey);
String encodedPrivateKeyString = bytesToEncodedString(privateKey);
String encryptedDataString = bytesToEncodedString(
encrypt(encodedStringToBytes(encodedPublicKeyString), stringToBytes(secretText)));
String decryptedDataString = bytesToString(
decrypt(
encodedStringToBytes(encodedPrivateKeyString),
encodedStringToBytes(encryptedDataString)));
System.out.println(new String(decryptedDataString));
}
}
I am using the code in below mentioned post to encrypt and decrypt values between Java and Java script module of my application.
Compatible AES algorithm for Java and Javascript
In a above post they are using 128 bit key value. I want to use my own key instead of hard coding the 128 bit key value.
My question is that can I convert any random string into 128 bit key value.
Please post some examples if it is possible to convert any string into 128 bit value.
Characters are represented with 8 bits. hence to form 128 bit key, create a string having 16 chars (16*8=128), e.g. "abcdefgh12345678".
to mask this key as base64, you may use Apache commons-codec Base64.encodeBase64... #see http://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/binary/Base64.html
Something I fount by google, and use in my project:
private final static String algorithm = "PBKDF2WithHmacSHA1";
private final static String HEX = "0123456789ABCDEF";
private static final String CP_ALGORITH = "AES";
private static final String CP_KEY = "PUTsomeKEYinHere";
public static String cipher(String cipherKey, String data) throws NoSuchAlgorithmException,
InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
SecretKeyFactory skf = SecretKeyFactory.getInstance(algorithm);
KeySpec spec = new PBEKeySpec(cipherKey.toCharArray(), cipherKey.getBytes(), 128, 256);
SecretKey tmp = skf.generateSecret(spec);
SecretKey key = new SecretKeySpec(tmp.getEncoded(), CP_ALGORITH);
Cipher cipher = Cipher.getInstance(CP_ALGORITH);
cipher.init(Cipher.ENCRYPT_MODE, key);
return toHex(cipher.doFinal(data.getBytes()));
}
public static String decipher(String cipherKey, String data) throws NoSuchAlgorithmException,
InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
SecretKeyFactory skf = SecretKeyFactory.getInstance(algorithm);
KeySpec spec = new PBEKeySpec(cipherKey.toCharArray(), cipherKey.getBytes(), 128, 256);
SecretKey tmp = skf.generateSecret(spec);
SecretKey key = new SecretKeySpec(tmp.getEncoded(), CP_ALGORITH);
Cipher cipher = Cipher.getInstance(CP_ALGORITH);
cipher.init(Cipher.DECRYPT_MODE, key);
return new String(cipher.doFinal(toByte(data)));
}
private static byte[] toByte(String data) throws NullPointerException{
int len = data.length()/2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(data.substring(2*i, 2*i+2), 16).byteValue();
return result;
}
private static String toHex(byte[] doFinal) {
StringBuffer result = new StringBuffer(2*doFinal.length);
for (int i = 0; i < doFinal.length; i++) {
result.append(HEX.charAt((doFinal[i]>>4)&0x0f)).append(HEX.charAt(doFinal[i]&0x0f));
}
return result.toString();
}
usage:
cipher(CP_KEY, STRINGtoCIPHER);
decipher(CP_KEY, YOURcipheredSTRING)
I put that all in a shared class with static fields and methods, so i can use it everywhere in my app. I use it to store SessionID i shared preferences, and it works nice.
This question already has answers here:
Java 256-bit AES Password-Based Encryption
(9 answers)
Closed 2 years ago.
I want to encrypt a string and then put it on a file. Also want to decrypt it when I want. I don’t need very strong security. I just want to make it harder to get my data others.
I tried several ways. Here are these.
Md5 Encryption:
How to hash a string in Android?
public static final String md5(final String toEncrypt) {
try {
final MessageDigest digest = MessageDigest.getInstance("md5");
digest.update(toEncrypt.getBytes());
final byte[] bytes = digest.digest();
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
sb.append(String.format("%02X", bytes[i]));
}
return sb.toString().toLowerCase();
} catch (Exception exc) {
return ""; // Impossibru!
}
}
I tried this function and able to encrypt a string but I can’t decrypt data from it. So it is not the solution.
DES Encryption:
Encrypt and decrypt a String in java
Here passphrase is Auto generated. Is always passphrase will same on all time? Then where is my security. So it is not my solution too.
AES Encryption:
How do I encrypt/decrypt a string with another string as a password?
I also tried Aes from this link. Here key is also auto generated?
Is there any other way?
package com.example;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class StrongAES
{
public void run()
{
try
{
String text = "Hello World";
String key = "Bar12345Bar12345"; // 128 bit key
// 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());
System.err.println(new String(encrypted));
// decrypt the text
cipher.init(Cipher.DECRYPT_MODE, aesKey);
String decrypted = new String(cipher.doFinal(encrypted));
System.err.println(decrypted);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
StrongAES app = new StrongAES();
app.run();
}
}
package com.ezeon.util.gen;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.*;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
/*** Encryption and Decryption of String data; PBE(Password Based Encryption and Decryption)
* #author Vikram
*/
public class CryptoUtil
{
Cipher ecipher;
Cipher dcipher;
// 8-byte Salt
byte[] salt = {
(byte) 0xA9, (byte) 0x9B, (byte) 0xC8, (byte) 0x32,
(byte) 0x56, (byte) 0x35, (byte) 0xE3, (byte) 0x03
};
// Iteration count
int iterationCount = 19;
public CryptoUtil() {
}
/**
*
* #param secretKey Key used to encrypt data
* #param plainText Text input to be encrypted
* #return Returns encrypted text
* #throws java.security.NoSuchAlgorithmException
* #throws java.security.spec.InvalidKeySpecException
* #throws javax.crypto.NoSuchPaddingException
* #throws java.security.InvalidKeyException
* #throws java.security.InvalidAlgorithmParameterException
* #throws java.io.UnsupportedEncodingException
* #throws javax.crypto.IllegalBlockSizeException
* #throws javax.crypto.BadPaddingException
*
*/
public String encrypt(String secretKey, String plainText)
throws NoSuchAlgorithmException,
InvalidKeySpecException,
NoSuchPaddingException,
InvalidKeyException,
InvalidAlgorithmParameterException,
UnsupportedEncodingException,
IllegalBlockSizeException,
BadPaddingException {
//Key generation for enc and desc
KeySpec keySpec = new PBEKeySpec(secretKey.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
// Prepare the parameter to the ciphers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
//Enc process
ecipher = Cipher.getInstance(key.getAlgorithm());
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
String charSet = "UTF-8";
byte[] in = plainText.getBytes(charSet);
byte[] out = ecipher.doFinal(in);
String encStr = new String(Base64.getEncoder().encode(out));
return encStr;
}
/**
* #param secretKey Key used to decrypt data
* #param encryptedText encrypted text input to decrypt
* #return Returns plain text after decryption
* #throws java.security.NoSuchAlgorithmException
* #throws java.security.spec.InvalidKeySpecException
* #throws javax.crypto.NoSuchPaddingException
* #throws java.security.InvalidKeyException
* #throws java.security.InvalidAlgorithmParameterException
* #throws java.io.UnsupportedEncodingException
* #throws javax.crypto.IllegalBlockSizeException
* #throws javax.crypto.BadPaddingException
*/
public String decrypt(String secretKey, String encryptedText)
throws NoSuchAlgorithmException,
InvalidKeySpecException,
NoSuchPaddingException,
InvalidKeyException,
InvalidAlgorithmParameterException,
UnsupportedEncodingException,
IllegalBlockSizeException,
BadPaddingException,
IOException {
//Key generation for enc and desc
KeySpec keySpec = new PBEKeySpec(secretKey.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
// Prepare the parameter to the ciphers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
//Decryption process; same key will be used for decr
dcipher = Cipher.getInstance(key.getAlgorithm());
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
byte[] enc = Base64.getDecoder().decode(encryptedText);
byte[] utf8 = dcipher.doFinal(enc);
String charSet = "UTF-8";
String plainStr = new String(utf8, charSet);
return plainStr;
}
public static void main(String[] args) throws Exception {
CryptoUtil cryptoUtil=new CryptoUtil();
String key="ezeon8547";
String plain="This is an important message";
String enc=cryptoUtil.encrypt(key, plain);
System.out.println("Original text: "+plain);
System.out.println("Encrypted text: "+enc);
String plainAfter=cryptoUtil.decrypt(key, enc);
System.out.println("Original text after decryption: "+plainAfter);
}
}
I just want to add that if you want to somehow store the encrypted byte array as String and then retrieve it and decrypt it (often for obfuscation of database values) you can use this approach:
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class StrongAES
{
public void run()
{
try
{
String text = "Hello World";
String key = "Bar12345Bar12345"; // 128 bit key
// 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());
StringBuilder sb = new StringBuilder();
for (byte b: encrypted) {
sb.append((char)b);
}
// the encrypted String
String enc = sb.toString();
System.out.println("encrypted:" + enc);
// now convert the string to byte array
// for decryption
byte[] bb = new byte[enc.length()];
for (int i=0; i<enc.length(); i++) {
bb[i] = (byte) enc.charAt(i);
}
// decrypt the text
cipher.init(Cipher.DECRYPT_MODE, aesKey);
String decrypted = new String(cipher.doFinal(bb));
System.err.println("decrypted:" + decrypted);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
StrongAES app = new StrongAES();
app.run();
}
}
My requirement was to keep the password in a config file in encrypted form and decrypt when the program runs. For this I used the jasypt library (jasypt-1.9.3.jar). This is a very good library and we can accomplish the task with just 4 lines of code.
First, after adding jar to my project I imported the below library.
import org.jasypt.util.text.AES256TextEncryptor;
Then I created the below method. I then called this method by passing the text which I need to encrypt in password parameter. Using aesEncryptor.encrypt method, I encrypted the password which is stored to the myEncryptedPassword variable.
public void EncryptPassword(String password)
{
AES256TextEncryptor aesEncryptor = new AES256TextEncryptor();
aesEncryptor.setPassword("mypassword");
String myEncryptedPassword = aesEncryptor.encrypt(password);
System.out.println(myEncryptedPassword );
}
You might have noticed the method setPassword method and the value mypassword is used in the above code. This is to make sure that no one can decrypt the password even if they use the encrypted password using the same library.
Now I can see the value in the myEncryptedPassword variable something like h9oJ4P5P8ToRy38wvK11PUQCBrT1oH/zbMWuMrbOlI0rfZrj+qSg6f/u0jctOs/ZUf9t3shiwnEt05/nq8bnag==. This is the encrypted password. Keep this value in the config file.
I then created the below method to decrypt the password to be used in my program. The value of passwordFromConfigFile is the encrypted text which I got from the EncryptPassword method. Note that you have to use the same password in the aesEncryptor.setPassword method that you used to encrypt the password.
public String DecryptPassword(String passwordFromConfigFile)
{
AES256TextEncryptor aesEncryptor = new AES256TextEncryptor();
aesEncryptor.setPassword("mypassword");
String decryptedPassword = aesEncryptor.decrypt(passwordFromConfigFile);
return decryptedPassword;
}
The variable decryptedPassword will now have the decrypted password value.
The code marked as the solution did not work for me. This was my solution.
/*
* http://www.java2s.com/Code/Java/Security/EncryptingaStringwithDES.htm
* https://stackoverflow.com/questions/23561104/how-to-encrypt-and-decrypt-string-with-my-passphrase-in-java-pc-not-mobile-plat
*/
package encryptiondemo;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
*
* #author zchumager
*/
public class EncryptionDemo {
Cipher ecipher;
Cipher dcipher;
EncryptionDemo(SecretKey key) throws Exception {
ecipher = Cipher.getInstance("AES");
dcipher = Cipher.getInstance("AES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
}
public String encrypt(String str) throws Exception {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
}
public String decrypt(String str) throws Exception {
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] utf8 = dcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
}
public static void main(String args []) throws Exception
{
String data = "Don't tell anybody!";
String k = "Bar12345Bar12345";
//SecretKey key = KeyGenerator.getInstance("AES").generateKey();
SecretKey key = new SecretKeySpec(k.getBytes(), "AES");
EncryptionDemo encrypter = new EncryptionDemo(key);
System.out.println("Original String: " + data);
String encrypted = encrypter.encrypt(data);
System.out.println("Encrypted String: " + encrypted);
String decrypted = encrypter.decrypt(encrypted);
System.out.println("Decrypted String: " + decrypted);
}
}
Use This This Will work For sure
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class ProtectedConfigFile {
private static final char[] PASSWORD = "enfldsgbnlsngdlksdsgm".toCharArray();
private static final byte[] SALT = { (byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12, (byte) 0xde, (byte) 0x33,
(byte) 0x10, (byte) 0x12, };
public static void main(String[] args) throws Exception {
String originalPassword = "Aman";
System.out.println("Original password: " + originalPassword);
String encryptedPassword = encrypt(originalPassword);
System.out.println("Encrypted password: " + encryptedPassword);
String decryptedPassword = decrypt(encryptedPassword);
System.out.println("Decrypted password: " + decryptedPassword);
}
private static String encrypt(String property) throws GeneralSecurityException, UnsupportedEncodingException {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
return base64Encode(pbeCipher.doFinal(property.getBytes("UTF-8")));
}
private static String base64Encode(byte[] bytes) {
// NB: This class is internal, and you probably should use another impl
return new BASE64Encoder().encode(bytes);
}
private static String decrypt(String property) throws GeneralSecurityException, IOException {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
return new String(pbeCipher.doFinal(base64Decode(property)), "UTF-8");
}
private static byte[] base64Decode(String property) throws IOException {
// NB: This class is internal, and you probably should use another impl
return new BASE64Decoder().decodeBuffer(property);
}
}
Both Encrypt and Decrypt with AES and DES Algoritham ,This worked for me perfectly
GithubLink: Java Code For Encryption and Decryption
package decrypt;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/* Decrypt encrypted string into plain string with aes and Des algoritham*/
public class Decrypt {
public String decrypt(String str,String k) throws Exception {
// Decode base64 to get bytes
Cipher dcipher = Cipher.getInstance("AES");
Key aesKey = new SecretKeySpec(k.getBytes(), "AES");
dcipher.init(dcipher.DECRYPT_MODE, aesKey);
//System.out.println(aesKey);
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] utf8 = dcipher.doFinal(dec);
//System.out.println(utf8);
// Decode using utf-8
return new String(utf8, "UTF8");
}
public String encrypt(String str,String k) throws Exception {
Cipher ecipher = Cipher.getInstance("AES");
Key aeskey = new SecretKeySpec(k.getBytes(),"AES");
byte[] utf8 = str.getBytes("UTF8");
ecipher.init(ecipher.ENCRYPT_MODE, aeskey );
byte[] enc = ecipher.doFinal(utf8);
return new sun.misc.BASE64Encoder().encode(enc);
}
public String encrypt(String str,String k,String Algo) throws Exception {
Cipher ecipher = Cipher.getInstance(Algo);
Key aeskey = new SecretKeySpec(k.getBytes(),Algo);
byte[] utf8 = str.getBytes("UTF8");
ecipher.init(ecipher.ENCRYPT_MODE, aeskey );
byte[] enc = ecipher.doFinal(utf8);
return new sun.misc.BASE64Encoder().encode(enc);
}
public String decrypt(String str,String k,String Algo) throws Exception {
// Decode base64 to get bytes
Cipher dcipher = Cipher.getInstance(Algo);
Key aesKey = new SecretKeySpec(k.getBytes(), Algo);
dcipher.init(dcipher.DECRYPT_MODE, aesKey);
//System.out.println(aesKey);
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] utf8 = dcipher.doFinal(dec);
//System.out.println(utf8);
// Decode using utf-8
return new String(utf8, "UTF8");
}
public static void main(String args []) throws Exception
{
String original = "rakesh";
String data = "CfPcX0G+e7TLKKMyyvrvrQ==";
String k = "qertyuiopasdfghw"; //AES key length must be 16
String k1 = "qertyuio"; // DES key length must be 8
String data1 = "rakesh";
String data2 = "nAtvNq7uHKE=";
String Algo= "DES";
String Algo1= "AES";
Decrypt decrypter = new Decrypt();
System.out.println("Original String: " + original);
System.out.println("encrypted String in DES: " + decrypter.encrypt(data1,
k1,Algo));
System.out.println("Decrypted String in DES: " + decrypter.decrypt(data2,
k1,Algo));
System.out.println("encrypted String in AES: " + decrypter.encrypt(data1,
k,Algo1));
System.out.println("Decrypted String in AES: " + decrypter.decrypt(data,
k,Algo1));
}
}
I use encryption AES algorithm, when i encrypt 16 byte(one block) the result is 32 byte.
Is this ok?
My source code that i used is:
package net.sf.andhsli.hotspotlogin;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* Usage:
* <pre>
* String crypto = SimpleCrypto.encrypt(masterpassword, cleartext)
* ...
* String cleartext = SimpleCrypto.decrypt(masterpassword, crypto)
* </pre>
* #author ferenc.hechler
*/
public class SimpleCrypto {
public static String encrypt(String seed, String cleartext) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] result = encrypt(rawKey, cleartext.getBytes());
return toHex(result);
}
public static String decrypt(String seed, String encrypted) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] enc = toByte(encrypted);
byte[] result = decrypt(rawKey, enc);
return new String(result);
}
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
public static String toHex(String txt) {
return toHex(txt.getBytes());
}
public static String fromHex(String hex) {
return new String(toByte(hex));
}
public static byte[] toByte(String hexString) {
int len = hexString.length()/2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
return result;
}
public static String toHex(byte[] buf) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2*buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
private final static String HEX = "0123456789ABCDEF";
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
}
}
If you look at the specification section 5 then you can see that the input, output and state are all 128 bit. The only thing that varies is the size of the key: 128, 196 or 256 bits. So encrypting a 16 byte input state will yield a 16 byte output state.
Are you sure you aren't mixing it up with the length in hexadecimal notation or similar? If it is in hexadecimal notation then it's correct because for each byte two characters are needed to represent it: 00-FF (for the range 0-255). So, for example, 16 bytes would be encoded as 32 characters in hexadecimal notation.
Another way you can test if the encryption is correct is by doing the equivalent decryption, see if it matches the plaintext input string.
Anyway, it does the correct thing. Here's a test:
public static void main(String[] args) {
try {
String plaintext = "Hello world", key = "test";
String ciphertext = encrypt(key, plaintext);
String plaintext2 = decrypt(key, ciphertext);
System.out.println("Encrypting '" + plaintext +
"' yields: (" + ciphertext.length() + ") " + ciphertext);
System.out.println("Decrypting it yields: " + plaintext2);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
Which yields:
Encrypting 'Hello world' yields: (32)
5B68978D821FCA6022D4B90081F76B4F
Decrypting it yields: Hello world
AES defaults to ECB mode encryption with PKCS#7 compatible padding mode (for all providers observed so far). ECB and CBC mode encryption require padding if the input is not precisely a multiple of the blocksize in size, with 16 being the block size of AES in bytes.
Unfortunately there might be no way for the unpadding mechanism to distinguish between padding and data; the data itself may represent valid padding. So for 16 bytes of input you will get another 16 bytes of padding. Padding modes that are deterministic such as PKCS#7 always pad with 1 up to [blocksize] bytes.
If you look at int output = cipher.getOutputSize(16); you will get back 32 bytes. Use "AES/ECB/NoPadding" during decipher to see the padding bytes (e.g. 4D61617274656E20426F64657765732110101010101010101010101010101010).
You are better off when you fully specify the algorithm. Previously most developers would go for "AES/CBC/PKCS5Padding" but nowadays "AES/GCM/NoPadding" should probably be used because it offers message authentication and integrity. Otherwise you will keep guessing which mode is actually used.
Note that using ECB mode is not safe as an attacker can retrieve information from the cipher text; identical blocks of plain text encode to identical blocks of cipher text.
package com.cipher;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
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.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class Encrypt {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
// TODO Auto-generated method stub
String s="You are doing encryption at deep level";
SecureRandom sr=SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(s.getBytes());
byte[] k=new byte[128/8];
sr.nextBytes(k);
SecretKeySpec spec=new SecretKeySpec(k,"AES");
byte[] iv={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
IvParameterSpec ivs=new IvParameterSpec(iv);
Cipher cps=Cipher.getInstance("AES/CBC/PKCS5Padding");
cps.init(Cipher.ENCRYPT_MODE,spec,ivs);
byte[] iv2=cps.doFinal(s.getBytes());
System.out.println("En"+iv2);
Cipher cpr=Cipher.getInstance("AES/CBC/PKCS5Padding");
cpr.init(Cipher.DECRYPT_MODE, spec,ivs);
byte[] iv3=cpr.doFinal(iv2);
String ds=new String(iv3);
System.out.println(ds);
}
}