I have a request where there is a field "number_token" that I need to encrypt to send to another API to validate. What is the best method to do this?
Example:
"number_token":"123456789"
encrypt:
"number_token":"iIsInN1YieyJpc3MiOiJHZXR3YXk.gcGFnQmFuayBQQI6ImIyYzMxMTlmLWU3ZjktNDZjZS05NTMxLTkyMTNlNWRjNWNiMSIsImlhdCI6MTY1OTgyNjUyOCwiZXhwIjoxNjU5ODI2NzA4fQ.mL-jivitV30N1PLq10CmI4ZWxCcBivGf5QGVus7Vsyw"
There are many factors to be considered but to get started you can use below logic to encrypt. Credits https://www.javaguides.net/2020/02/java-string-encryption-decryption-example.html?m=1
Here is the complete Java program to encrypt and decrypt string or text in Java:
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class AESEncryptionDecryption {
private static SecretKeySpec secretKey;
private static byte[] key;
private static final String ALGORITHM = "AES";
public void prepareSecreteKey(String myKey) {
MessageDigest sha = null;
try {
key = myKey.getBytes(StandardCharsets.UTF_8);
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, ALGORITHM);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
public String encrypt(String strToEncrypt, String secret) {
try {
prepareSecreteKey(secret);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
} catch (Exception e) {
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}
public String decrypt(String strToDecrypt, String secret) {
try {
prepareSecreteKey(secret);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
} catch (Exception e) {
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
public static void main(String[] args) {
final String secretKey = "secrete";
String originalString = "javaguides";
AESEncryptionDecryption aesEncryptionDecryption = new AESEncryptionDecryption();
String encryptedString = aesEncryptionDecryption.encrypt(originalString, secretKey);
String decryptedString = aesEncryptionDecryption.decrypt(encryptedString, secretKey);
System.out.println(originalString);
System.out.println(encryptedString);
System.out.println(decryptedString);
}
}
I am trying to find implementing this Java encryption algorithm in PHP, but I do not have any experience in PHP.
I have this DESede/ECB/PKCS5Padding encryption utils code in Java.
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
public class DESUtil {
private static final String KEY_ALGORITHM = "DESede";
private static final String DEFAULT_CIPHER_ALGORITHM = "DESede/ECB/PKCS5Padding";
public static String encrypt(String content, final String key) {
try {
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
byte[] byteContent = content.getBytes(StandardCharsets.UTF_8.name());
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key));
byte[] result = cipher.doFinal(byteContent);
return Base64.encodeBase64String(result);
} catch (Exception ex) {
System.out.println("error:" + ex.getMessage());
}
return null;
}
public static String decrypt(String content, final String key) {
try {
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key));
byte[] result = cipher.doFinal(Base64.decodeBase64(content));
return new String(result, StandardCharsets.UTF_8.name());
} catch (Exception ex) {
System.out.println("error:" + ex.getMessage());
}
return null;
}
public static SecretKeySpec getSecretKey(final String key) {
KeyGenerator kg = null;
try {
byte[] bytes = key.getBytes(StandardCharsets.UTF_8.name());
kg = KeyGenerator.getInstance(KEY_ALGORITHM);
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(bytes);
kg.init(secureRandom);
SecretKey secretKey = kg.generateKey();
return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
} catch (Exception ex) {
System.out.println("error:" + ex.getMessage());
}
return null;
}
}
Run test, I got this
System.out.println("Result:" + DESUtil.encrypt("abc", "123456"));
// Result:9huQhFxzOmA=
But I use openssl, the result is different
<?php
$key = "123456";
$data = "abc";
$out = openssl_encrypt($data, 'DES-EDE3', $key, OPENSSL_RAW_DATA);
echo base64_encode($out);
// VxvdZgL08kU=
2021-03-29 15:00 update.
How to implementing DESede + SHA1PRNG in php,I try this(Java Aes class convert to php) post's answer(AES + SHA1PRNG),but result is different
<?php
$key = "123456";
$data = "abc";
$key = substr(openssl_digest(openssl_digest($password, 'sha1', true), 'sha1', true), 0, 16);
$out = openssl_encrypt($data, 'DES-EDE3', $key, OPENSSL_RAW_DATA);
echo base64_encode($out);
// rsXHh1tIzSs=
2021-03-29 18:25 update. try again.
<?php
// this key is 123456, generate by java kg.generateKey to base64 encode.
$key = "a7WDf7ZDKRBe5VeM2nzHf9PLKtkfZC9G";
$data = "abc";
$key = base64_decode($key);
$out = openssl_encrypt($data, 'DES-EDE3', $key, OPENSSL_RAW_DATA);
echo base64_encode($out);
// 9huQhFxzOmA=
// this result is correct, but how to implementing DESede + SHA1PRNG in php?
What is the right algorithm? How to implement this?
I'm trying to replicate an encryption method based on another C# method that I found.
The C# Encryption method EncryptText(word, password) call to another method AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes) to encrypt plain text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.IO;
using System.Text;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
var f = EncryptText("763059", "515t3ma5m15B4d35");//(word, password)
Console.WriteLine(f);
}
public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
{
byte[] encryptedBytes = null;
byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CBC;
using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
cs.Close();
}
encryptedBytes = ms.ToArray();
}
}
return encryptedBytes;
}
public static string EncryptText(string input, string password)
{
byte[] bytesToBeEncrypted = Encoding.UTF8.GetBytes(input);
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
byte[] bytesEncrypted = AES_Encrypt(bytesToBeEncrypted, passwordBytes);
string result = Convert.ToBase64String(bytesEncrypted);
return result;
}
}
}
Using word 763059 and password 515t3ma5m15B4d35, the output is the following:
3cHrXxxL1Djv0K2xW4HuCg==
UPDATE:
Now, I created a Java Class main where I'm trying to replicate previous code:
public class main {
final static String PASSWORD = "515t3ma5m15B4d35";
final static byte[] SALT = new byte[]{1, 2, 3, 4, 5, 6, 7, 8};
final static int KEY_SIZE = 256;
final static int BLOCK_SIZE = 128;
final static int ITERATIONS = 1000;
public static void main(String[] args) {
System.out.println(encryptText("763059", PASSWORD));
}
public static String encryptText(String word, String password) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(password.getBytes("UTF-8"));
password = new String(md.digest(), "UTF-8");
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(password.toCharArray(), SALT, ITERATIONS, KEY_SIZE);
SecretKey tmp = factory.generateSecret(spec);
SecretKeySpec skey = new SecretKeySpec(tmp.getEncoded(), "AES");
byte[] iv = new byte[BLOCK_SIZE / 8];
IvParameterSpec ivspec = new IvParameterSpec(iv);
Cipher ci = Cipher.getInstance("AES/CBC/PKCS5Padding");
ci.init(Cipher.ENCRYPT_MODE, skey, ivspec);
byte[] result = ci.doFinal(word.getBytes("UTF-8"));
return DatatypeConverter.printBase64Binary(result);
} catch (NoSuchAlgorithmException | UnsupportedEncodingException | IllegalBlockSizeException | BadPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | NoSuchPaddingException | InvalidKeySpecException ex) {
return null;
}
}
}
UPDATE:
I read about using 256 bits keys in Java, and I found that I need to add Java Cryptography Extensions to allow 256 keys (Because I'm working with JDK7).
Then I added the libreries to the project, also I change the line:
KeySpec spec = new PBEKeySpec(password.toCharArray(), SALT, ITERATIONS, KEY_SIZE);
With the Key Value:
final static int KEY_SIZE = 256;
Now the output is the following:
J1xbKOjIeXbQ9njH+67RNw==
I still can't achieve my goal. Any Suggestion?
Finally I decided to use the BouncyCastle API to use the functionality of RijndaelEngine, as well as to generate the 256-bit key with PKCS5S2ParametersGenerator.
I created the RijndaelEncryption class to be able to perform the encryption as in the C# code:
public class RijndaelEncryption {
public String encryptString(String word, String password, byte[] salt, int iterations, int keySize, int blockSize) {
try {
byte[] pswd = sha256String(password, "UTF-8");
PKCS5S2ParametersGenerator key = keyGeneration(pswd, salt, iterations);
ParametersWithIV iv = generateIV(key, keySize, blockSize);
BufferedBlockCipher cipher = getCipher(true, iv);
byte[] inputText = word.getBytes("UTF-8");
byte[] newData = new byte[cipher.getOutputSize(inputText.length)];
int l = cipher.processBytes(inputText, 0, inputText.length, newData, 0);
cipher.doFinal(newData, l);
return new String(Base64.encode(newData), "UTF-8");
} catch (UnsupportedEncodingException | IllegalStateException | DataLengthException | InvalidCipherTextException e) {
return null;
}
}
public BufferedBlockCipher getCipher(boolean encrypt, ParametersWithIV iv) {
RijndaelEngine rijndael = new RijndaelEngine();
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(rijndael));
cipher.init(encrypt, iv);
return cipher;
}
public ParametersWithIV generateIV(PKCS5S2ParametersGenerator key, int keySize, int blockSize) {
try {
ParametersWithIV iv = null;
iv = ((ParametersWithIV) key.generateDerivedParameters(keySize, blockSize));
return iv;
} catch (Exception e) {
return null;
}
}
public PKCS5S2ParametersGenerator keyGeneration(byte[] password, byte[] salt, int iterations) {
try {
PKCS5S2ParametersGenerator key = new PKCS5S2ParametersGenerator();
key.init(password, salt, iterations);
return key;
} catch (Exception e) {
return null;
}
}
public byte[] sha256String(String password, Charset charset) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(password.getBytes(charset));
return md.digest();
} catch (NoSuchAlgorithmException ex) {
return null;
}
}
public byte[] sha256String(String password, String charset) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(password.getBytes(charset));
return md.digest();
} catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
return null;
}
}
}
And I tested in main method:
public static void main(String[] args) {
RijndaelEncryption s = new RijndaelEncryption();
byte[] salt = new byte[]{1, 2, 3, 4, 5, 6, 7, 8};
String encryptStr = s.encryptString("763059", "515t3ma5m15B4d35", salt, 1000, 256, 128);
System.out.println("Encryptation: " + encryptStr);
}
To get:
Encryptation: 3cHrXxxL1Djv0K2xW4HuCg==
I am not any C# expert, but there are a few things to be checked:
Reading the documentation about Rfc2898DeriveBytes I see the function is using SHA1 hash, so try you may try to use PBKDF2WithHmacSHA1
On both instances (Rfc2898DeriveBytes, PBEKeySpec) you should make sure you the key size is the same (256 bit), it is surely wrong in your Java code
You may try to encode and print the keys to really make sure they are the same.
I need to add Java Cryptography Extensions to allow 256 keys.
Depends on your JVM version. I believe Oracle JDK since v. 1.8u162 by default contains the Unlimited Strength JCE policy. If you take any current JRE version, you should be ok
Additional: you are using (static) zero array IV, which is not secure
I have an answer for the original question. For future reference without bouncycastle.
You had a few problems.
Key size needed to be 256 + 128 (blocksize as well)
C# and Java byte[] don't act the same because java bytes are always signed which messes with the encryption of the password.
Both of these pieces of code give as output:
xD4R/yvV2tHajUS9p4kqJg==
C# code:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace tryencryption
{
class Program
{
static void Main(string[] args)
{
var f = EncryptText("yme", "515t3ma5m15B4d35");//(word, password)
Console.WriteLine(f);
Console.ReadKey();
}
public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, string passwordString)
{
byte[] encryptedBytes = null;
byte[] salt = new byte[] { (byte)0x49, (byte)0x64, (byte)0x76, (byte)0x65, (byte)0x64, (byte)0x65, (byte)0x76, (byte)0x61, (byte)0x6e, (byte)0x20, (byte)0x4d, (byte)0x65, (byte)0x76 };
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordString, salt, 1000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CBC;
using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
cs.Close();
}
encryptedBytes = ms.ToArray();
}
}
return encryptedBytes;
}
public static string EncryptText(string input, string password)
{
byte[] bytesToBeEncrypted = Encoding.Unicode.GetBytes(input);
byte[] bytesEncrypted = AES_Encrypt(bytesToBeEncrypted, password);
string result = Convert.ToBase64String(bytesEncrypted);
return result;
}
}
}
Java code (this was from an android project bcs that's my usecase but should work everywhere):
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String result = encrypt("yme", "515t3ma5m15B4d35");
}
private static String encrypt(String word, String password) {
byte[] salt = new byte[] { (byte)0x49, (byte)0x64, (byte)0x76, (byte)0x65, (byte)0x64, (byte)0x65, (byte)0x76, (byte)0x61, (byte)0x6e, (byte)0x20, (byte)0x4d, (byte)0x65, (byte)0x76};
try {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(), salt, 1000, 256 + 128);
Key secretKey = factory.generateSecret(pbeKeySpec);
byte[] test = secretKey.getEncoded();
byte[] key = new byte[32];
byte[] iv = new byte[16];
System.arraycopy(secretKey.getEncoded(), 0, key, 0, 32);
System.arraycopy(secretKey.getEncoded(), 32, iv, 0, 16);
SecretKeySpec secret = new SecretKeySpec(key, "AES");
AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret, ivSpec);
//Realise Im using UTF16 here! Maybe you need UTF8
byte[] plaintextintobytes =word.getBytes(StandardCharsets.UTF_16LE);
byte[] encrypted = cipher.doFinal(plaintextintobytes);
String encryptedInformation = Base64.encodeToString(encrypted, Base64.NO_WRAP);
return encryptedInformation;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return "";
}
}
My problem is with symmetric decryption. Not asymmetric decryption. So the correct answer is here Decrypt PGP encrypted file with passphrase only in Java
I use gpg to encrypt "hello":
[root#shc-sma-cd13 opt]# echo "hello" | gpg --symmetric --armor --cipher-algo AES256 --passphrase "2R79P7z5f8350VEp" --batch
-----BEGIN PGP MESSAGE-----
Version: GnuPG v2.0.22 (GNU/Linux)
jA0ECQMC1XpaSrXhBAfU0jsBXw817k4k4iT++AGV8MUev4/gKkuIwAW2VaJsEANa
+0ZuqZgFp/8N7AndRhyNj5WGcloQQkLkwvIV3Q==
=GwQi
-----END PGP MESSAGE-----
I use Java to decrypt the string:
public class AESUtils1 {
private static final String KEY_VAL = "2R79P7z5f8350VEp";
public static String AESDecode(String content) {
try {
SecretKey key = new SecretKeySpec(KEY_VAL.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] byte_content = new BASE64Decoder().decodeBuffer(content);
byte[] byte_decode = cipher.doFinal(byte_content);
String AES_decode = new String(byte_decode, "utf-8");
return AES_decode;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
//如果有错就返加nulll
return null;
}
public static void main(String[] args) {
String encryptString = "jA0ECQMC1XpaSrXhBAfU0jsBXw817k4k4iT++AGV8MUev4/gKkuIwAW2VaJsEANa\n" +
" +0ZuqZgFp/8N7AndRhyNj5WGcloQQkLkwvIV3Q==\n" +
" =GwQi";
String decryptString = AESDecode(encryptString);
System.out.println("decryptString: " + decryptString);
}
}
But it fails with error message:
javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:936)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:847)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
at javax.crypto.Cipher.doFinal(Cipher.java:2164)
at com.hpe.itsma.itsmaInstaller.AESUtils1.AESDecode(AESUtils1.java:33)
at com.hpe.itsma.itsmaInstaller.AESUtils1.main(AESUtils1.java:57)
decryptString: null
I am curious that what is the real encrypted string from gpg that I can put it into Java. The output of gpg is different from using Java to encrypt "hello".
And another interesting thing is that every time I run command echo "hello" | gpg --symmetric --armor --cipher-algo AES256 --passphrase "2R79P7z5f8350VEp" --batch, the result is always different. Is that possible to decrypt the string which is encrypted by gpg. Or the wrong way I used of gpg?
Thanks all. Finally, I figure out the solution. Cause my data was symmetric encrypted. The decryption will be different from the asymmetric decryption. I put my code below, also you can find the same answer here Decrypt PGP encrypted file with passphrase only in Java
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openpgp.*;
import org.bouncycastle.openpgp.operator.jcajce.JcaPGPDigestCalculatorProviderBuilder;
import org.bouncycastle.openpgp.operator.jcajce.JcePBEDataDecryptorFactoryBuilder;
import org.bouncycastle.util.io.Streams;
import java.io.*;
import java.security.NoSuchProviderException;
import java.security.Security;
public class SymmetricDecyption {
public static byte[] decrypt(byte[] var0, char[] var1) throws IOException, PGPException, NoSuchProviderException {
ByteArrayInputStream var2 = new ByteArrayInputStream(var0);
InputStream var11 = PGPUtil.getDecoderStream(var2);
PGPObjectFactory var3 = new PGPObjectFactory(var11);
Object var5 = var3.nextObject();
PGPEncryptedDataList var4;
if (var5 instanceof PGPEncryptedDataList) {
var4 = (PGPEncryptedDataList) var5;
} else {
var4 = (PGPEncryptedDataList) var3.nextObject();
}
PGPPBEEncryptedData var6 = (PGPPBEEncryptedData) var4.get(0);
InputStream var7 = var6.getDataStream((new JcePBEDataDecryptorFactoryBuilder((new JcaPGPDigestCalculatorProviderBuilder()).setProvider("BC").build())).setProvider("BC").build(var1));
PGPObjectFactory var8 = new PGPObjectFactory(var7);
PGPCompressedData var9 = (PGPCompressedData) var8.nextObject();
var8 = new PGPObjectFactory(var9.getDataStream());
PGPLiteralData var10 = (PGPLiteralData) var8.nextObject();
return Streams.readAll(var10.getInputStream());
}
public static void main(String[] var0) throws Exception {
String password = "2R79P7z5f8350VEp";
File file = new File("C:\\Users\\zhongtao.CORPDOM\\Desktop\\file.txt.asc");
InputStream input = new FileInputStream(file);
byte[] byt = new byte[input.available()];
input.read(byt);
Security.addProvider(new BouncyCastleProvider());
byte[] var5 = decrypt(byt, password.toCharArray());
System.out.println("Decrypted data is: " + new String(var5));
}
}
Code:
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class crypto {
public static void main(String [] args) {
String s = args[0];
String s1 = args[1];
String ivkey = "thisisasecretword1";
byte[] ivraw = ivkey.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(ivraw, "AES");
byte[] iv = { 't','h','i','s','a','s','e','c','r','e','t','w','o','r','d','1' };
IvParameterSpec ivspec = new IvParameterSpec(iv);
if (s.equalsIgnoreCase("ENCRYPT")) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivspec);
byte[] encrypted = cipher.doFinal(s1.getBytes());
System.out.println("encrypt: " + new String(Base64.encodeBase64(encrypted)));
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivspec);
byte[] encrypted = cipher.doFinal(Base64.decodeBase64(s1));
System.out.println("decrypt: " + new String(encrypted));
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
I'm trying to compile this just to test the new encryption methods that we're thinking of using. This is the first iteration but will be dutifully secured at a later date to implement a randomized key. Anyway, when I try to compile this I set my classpath in osx to the location where the commons-coded-1.9.jar is located. I run javac crypto.java and no errors. I run java crypto "ENCRYPT" "TEST" and just get a NoClassDefFoundError: crypto message. I've been screwing with this but can't see where I made the mistake. Hopefully a fresh pair of eyes will be able to shine some light on it.