I am converting legacy application from .net to java. Legacy method using encryption using public key.
string text = "<base64encodedstring here>";
IBuffer buffer = CryptographicBuffer.DecodeFromBase64String(text);
AsymmetricKeyAlgorithmProvider asymmetricKeyAlgorithmProvider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.get_RsaPkcs1());
CryptographicKey cryptographicKey = asymmetricKeyAlgorithmProvider.ImportPublicKey(buffer, 3);
IBuffer buffer2 = CryptographicBuffer.ConvertStringToBinary(data, 0);
IBuffer buffer3 = CryptographicEngine.Encrypt(cryptographicKey, buffer2, null);
byte[] array;
CryptographicBuffer.CopyToByteArray(buffer3, ref array);
//return CryptographicBuffer.EncodeToBase64String(buffer3);
Here is my Java code to convert the given text into the public key
public static PublicKey getKey(String key) throws Exception{
try{
byte[] byteKey = Base64.getDecoder().decode(key);
X509EncodedKeySpec X509publicKey = new X509EncodedKeySpec(byteKey);
KeyFactory kf = KeyFactory.getInstance("RSA","BC");
return kf.generatePublic(X509publicKey);
}
catch(Exception e){
throw e;
}
}
Here is my main method
public static void main(String[] args) {
String text = "base64encodedstring";
try {
Security.addProvider(new BouncyCastleProvider());
decode(text);
PublicKey pubKey=getKey(text);
byte[] input = "plaintext".getBytes();
Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] cipherText = cipher.doFinal(input);
System.out.println("cipher: " + new String(cipherText));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
But When I try to get the public key I get the exception below
java.security.spec.InvalidKeySpecException: encoded key spec not recognised
at org.bouncycastle.jcajce.provider.asymmetric.util.BaseKeyFactorySpi.engineGeneratePublic(Unknown Source)
at org.bouncycastle.jcajce.provider.asymmetric.rsa.KeyFactorySpi.engineGeneratePublic(Unknown Source)
at java.security.KeyFactory.generatePublic(Unknown Source)
at com.test.EncryptionUtil.getKey(EncryptionUtil.java:38)
at com.test.EncryptionUtil.main(EncryptionUtil.java:60)
Am I doing something wrong? I am new to cryptography.
With some more research I found the way how it is doing in C#, but not able to convert it into java
public static CryptographicKey GetCryptographicPublicKeyFromCert(string strCert)
{
int length;
CryptographicKey CryptKey = null;
byte[] bCert = Convert.FromBase64String(strCert);
// Assume Cert contains RSA public key
// Find matching OID in the certificate and return public key
byte[] rsaOID = EncodeOID("1.2.840.113549.1.1.1");
int index = FindX509PubKeyIndex(bCert, rsaOID, out length);
// Found X509PublicKey in certificate so copy it.
if (index > -1)
{
byte[] X509PublicKey = new byte[length];
Array.Copy(bCert, index, X509PublicKey, 0, length);
AsymmetricKeyAlgorithmProvider AlgProvider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
CryptKey = AlgProvider.ImportPublicKey(CryptographicBuffer.CreateFromByteArray(X509PublicKey));
}
return CryptKey;
}
What is the purpose of EncodeOID method and how it can be achieved in Java. The link below explains the creation of base64 encoded public key string and decode it in C#
http://blogs.msdn.com/b/stcheng/archive/2013/03/12/windows-store-app-how-to-perform-rsa-data-encryption-with-x509-certificate-based-key-in-windows-store-application.aspx
There is no direct way to read microsoft Capi1PublicKey into java. I first converted the Capi1PublicKey to X509-encoded public key in WinRT. then I used created key in java.
Obviously the key isn't X509-encoded. Find out how it is encoded and use an appropriate KeySpec.
C# uses AsymmetricAlgorithmNames.get_RsaPkcs1 you need to find equivalent for your JAVA code.
You may want to have look at this Import Public RSA Key From Certificate
Related
I have data encrypted with AES/CBC/PKCS5Padding
I have the secret key but no iv.
I am unable to decrypt the data. What exactly are the steps. I copied a page's steps but I am sure I am doing something wrong since the data is hex.
Below is my code. I use the decrypt function with two params.
public class DCrypt2 {
private static String key = "3jiUqR/0J4/HX98XimcDvg==";//
private static String msg ="636F98E19CCAEB9C6ED1095F70C4739AEBA6200E83926EA3DA42DA4A391AC08B";//"2925D99C3A7520D84D64A80AAFB20BF63B22B6A8017B7438598BE36419B71174";
public static void main(String[] args) {
byte[] myIV = getIV(msg);
byte[] myMSG = getMSG(msg);
String my_msg = myMSG.toString();
decrypt(msg, myIV);
System.out.println("Second Try ");
System.out.println(key);
System.out.println(msg);
System.out.println("____________________________________");
//System.out.println(Base64.getDecoder().decode(msg));
//System.out.println(myDeHex(msg));
//msg = myDeHex(msg);
int extra = msg.length()%16;
System.out.println(extra+" ok "+msg.length());
for(int i = 0; i<extra;i++) {
System.out.println("ANOTHER");
msg +=" ";
}
System.out.println(extra+" ok "+msg.length());
}
public static String decrypt(String msg, byte[] iv) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//Cipher cipher = Cipher.getInstance("AES/CBC/nopadding");
SecretKeySpec the_key = new SecretKeySpec(key.getBytes(), "AES");// get / create symmetric encryption key
//SecretKeySpec the_key = new SecretKeySpec(Base64.getDecoder().decode(key), "AES");
// byte[] decoded = Base64.getDecoder().decode(msg);
IvParameterSpec ivspec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, the_key, ivspec);
byte[] input = Base64.getEncoder().encode(msg.getBytes());
if(input.length%16 > 0 ) {
System.out.println(input.length%16);
input = Arrays.copyOf(input, (input.length)+(16-(input.length%16)));
System.out.println(input.length+ " my size");
}
String res = new String(cipher.doFinal( input));
//String res = Base64.getEncoder().encodeToString(cipher.doFinal(msg.getBytes("UTF-8")));
//String res = new String(Base64.getDecoder().decode(cipher.doFinal(msg.getBytes("UTF-8"))));
System.out.println("Results: "+res);
return res;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
}
There is a good technical write-up here: https://www.rfc-editor.org/rfc/rfc3602#section-2
You need an Initialization Vector:
https://crypto.stackexchange.com/questions/29134/precisely-how-does-cbc-mode-use-the-initialization-vector
The IV's purpose is to ensure same plaintexts encrypt to different
ciphertexts. When an adversary learns the IV after the plaintext has
been encrypted, no harm is done, since it has already served its
purpose.
The IV can be made public after encryption, without impacting the
security of the system. Usually, it is prefixed to the ciphertext.
Source / More info
I am trying to use GCM Mode for encryption and decryption. Unfortunately decryption doesn't work.
Do I have to use the same initialization vector for both encryption and decryption classes? I already tried that, unsuccessfully...
Could the random argument in keyGen.init(128, random) be the problem?
Encryption code:
public class AES128SymmetricEncryption {
private static final int GCM_NONCE_LENGTH = 12; // in bytes
private static final int GCM_TAG_LENGTH = 16; // in bytes
public static void encode (FileInputStream ciphertextSource, FileOutputStream plaintextDestination)
{
try {
int numRead;
SecureRandom random = SecureRandom.getInstanceStrong();
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128, random);
SecretKey key = keyGen.generateKey();
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");
GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, getIV(random));
cipher.init(Cipher.ENCRYPT_MODE, key, spec);
byte[] buf = new byte[2048];
while ((numRead = ciphertextSource.read(buf)) > 0) {
byte[] decryptedBlock = cipher.update(buf, 0, numRead);
plaintextDestination.write(decryptedBlock);
}
}
catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (plaintextDestination != null) {
ciphertextSource.close();
}
if (plaintextDestination != null) {
plaintextDestination.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static byte[] getIV(SecureRandom random) {
final byte[] nonce = new byte[GCM_NONCE_LENGTH];
random.nextBytes(nonce);
System.out.println(nonce);
return nonce;
}
public static void main(String[] args) throws GeneralSecurityException, IOException
{
Security.addProvider(new BouncyCastleProvider());
FileInputStream fis = new FileInputStream("C:/Users/roehrlef/Desktop/Test Data/Source Data/100KB.jpg");
FileOutputStream fos = new FileOutputStream("C:/Users/roehrlef/Desktop/Test Data/Encrypted Data/encrypted.jpg");
encode(fis, fos);
}
}
Decryption code:
public class AES128SymmetricDecryption {
private static final int GCM_NONCE_LENGTH = 12; // in bytes
private static final int GCM_TAG_LENGTH = 16; // in bytes
public static void decode (FileInputStream ciphertextSource, FileOutputStream plaintextDestination)
{
try {
int numRead = 0;
SecureRandom random = SecureRandom.getInstanceStrong();
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128, random);
SecretKey key = keyGen.generateKey();
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");
GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, getIV(random));
cipher.init(Cipher.DECRYPT_MODE, key, spec);
CipherInputStream cis = new CipherInputStream(ciphertextSource, cipher);
byte[] buf = new byte[2048];
while ((numRead = cis.read(buf)) > 0) {
byte[] decryptedBlock = cipher.update(buf, 0, numRead);
plaintextDestination.write(decryptedBlock);
}
}
catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (plaintextDestination != null) {
ciphertextSource.close();
}
if (plaintextDestination != null) {
plaintextDestination.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static byte[] getIV(SecureRandom random) {
final byte[] nonce = new byte[GCM_NONCE_LENGTH];
random.nextBytes(nonce);
System.out.println(nonce);
return nonce;
}
public static void main(String[] args) throws GeneralSecurityException, IOException
{
Security.addProvider(new BouncyCastleProvider());
FileInputStream fis = new FileInputStream("C:/Users/roehrlef/Desktop/Test Data/Encrypted Data/encrypted.jpg");
FileOutputStream fos = new FileOutputStream("C:/Users/roehrlef/Desktop/Test Data/Decrypted Data/decrypted.jpg");
decode(fis, fos);
}
}
You're using KeyGenerator twice; once for encryption and once for decryption. This class generates a new random key. With symmetric ciphers you need to use the same key for encryption and decryption (hence the name).
In general you should use the following classes for the following purposes:
For symmetric keys (e.g. AES, HMAC):
KeyGenerator: brand new secret (symmetric) keys;
SecretKeyFactory: decoding secret (symmetric) keys, for instance generated by the method Key#getEncoded() implemented by most key classes;
And for asymmetric public / private key pairs (e.g. RSA):
KeyPairGenerator: brand new public / private asymmetric key pairs;
KeyFactory: decoding public / private (asymmetric) keys from a stored key format, for instance generated by the method Key#getEncoded() implemented by most key classes;
Both symmetric and asymmetric keys may be stored in key stores:
KeyStore: storing keys / certificates in a key container such as PKCS#12 key stores;
Finally there are some other options for creating keys:
KeyAgreement: establishing a key by a key agreement function such as Diffie-Hellman key exchange;
Cipher#unwrap: unwrapping (decrypting) keys created using Cipher#wrap (or a similar function on another platform) with another key.
You should probably either store and retrieve the key in a KeyStore - which you can load / save to file. Note that not all key stores are created equal; Java 9 expanded the functionality of PKCS#12 key stores and made them the default. You code also encode the key and use a SecretKeyFactory to decode it again.
Or you can just cheat and reuse the SecretKey instance you generated during encryption, and implement key storage later. That would be good for testing purposes. In the end you need to share the key for symmetric encryption.
And yes, the IV needs to be identical on both sides. Usually it is just stored in front of the ciphertext. The IV should be unique for each encryption, so you have to use the random number generator over there.
I have tried adding getbytes("UTF") or getbytes("UTF-8"), since it was suggested in a similar question.
It said we need to try UTF while converting bytes to string and vice a versa.
But still it is not working for my code...please help
public class Password1 {
private static final String ALGO = "AES";
private static byte[] keyValue = new byte[]{'t','h','y','u','e','f','z','s','y','k','f','l','d','a','b','m'};
public static void main(String[] args) {
//Password1 p = new Password1();
Scanner sc = new Scanner(System.in);
String i = sc.nextLine();
System.out.println("Password = "+i);
try {
String en = encrypt(i);
System.out.println(en);
String dec = decrypt(en);
System.out.println("Encrypted = " + en);
System.out.println("Decrypted = " + dec);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String encrypt(String Data) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = c.doFinal(Data.getBytes("UTF-8"));
String encrypted = new BASE64Encoder().encode(encVal);
return encrypted;
}
public static String decrypt(String encrypted) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.DECRYPT_MODE, key);
//Byte bencrypted = Byte.valueOf(encrypted);
byte[] decoded = new BASE64Decoder().decodeBuffer(encrypted);
byte[] decValue = c.doFinal(decoded);
String decrypted = new String(decValue);
return decrypted;
}
private static Key generateKey() throws Exception {
MessageDigest sha = MessageDigest.getInstance("SHA-1");
keyValue = sha.digest(keyValue);
keyValue = Arrays.copyOf(keyValue, 16);
SecretKeySpec key = new SecretKeySpec(keyValue, ALGO);
return key;
}
}
When you call encrypt() you replace the password by its hash, and then use the hash as a key.
Then you call decrypt(), and rehash the hash, and use the hashed hash as the key. So you're not using the same key for encryption and decryption.
Generate the key once in main(), and pass it as parameter to encrypt() and decrypt(). Make keyValue final. Or even better, make it a local variable of main.
On the line where you have Cipher.getInstance(ALGO) have your ALGO variable be "AES/CBC/PKCS5Padding" (or whatever other mode and padding you want to use). This should resolve any padding issues you might run into like the one you are now.
If you don't do it in this way I believe you'll have to handle all of the padding logic yourself.
JB Nizet's answer about how you're generating keys is the other half of your problem.
I have an application developed on BlackBerry JDE 5.0.0 that encrypts a String using DES algorithm with ECB mode. After the encryption, the result is encoded by base64 encoding. But whenever I compare the result that i get from my encryption method with the result that i get on the online encryptor engine, it always give different result on the several last character. I tried to decrypt the result that i get form my encryption method with the online encriptor engine and it looks like the result is not the valid one. So how can I fix that different result on the several last character?
Here my encryption method code:
public String encryptDESECB(String text) throws MessageTooLongException
{
byte[] input = text.getBytes();
byte[] output = new byte[8];
byte[] uid = null;
uid = "431654625bd37673e3b00359676154074a04666a".getBytes();
DESKey key = new DESKey(uid);
try {
DESEncryptorEngine engine = new DESEncryptorEngine(key);
engine.encrypt(input, 0, output, 0);
String x= BasicAuth.encode(new String(output));
System.out.println("AFTER ENCODE"+x);
return new String(x);
} catch (CryptoTokenException e) {
return "NULL";
} catch (CryptoUnsupportedOperationException e) {
return "NULL";
}
}
The String that i want to encrypt is "00123456"
The Result that i get from my encryption method is:YnF2BWFV/8w=
The Result that i get from online encryptor engine (http://www.tools4noobs.com/online_tools/encrypt/) : YnF2BWFV9sw=
The Result that i get from android (With the same encryption algorithm & Method) : YnF2BWFV9sw=
Here's the code on Android:
public static String encryptDesECB(String data) {
try {
DESKeySpec keySpec = newDESKeySpec("431654625bd37673e3b00359676154074a04666a".getBytes("UTF8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(keySpec);
// ENCODE plainTextPassword String
byte[] cleartext = data.getBytes("UTF8");
Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, key);
Logger.log(Log.INFO, new String(cipher.doFinal(cleartext)));
String encrypedPwd = Base64.encodeToString(cipher.doFinal(cleartext), Base64.DEFAULT);
Logger.log(Log.INFO, encrypedPwd);
return encrypedPwd;
} catch (Exception e) {
Logger.log(e);
return null;
}
}
Can anyone help me with this?
This is most likely caused by padding, as DES works with 8 byte blocks.
For more information check out this link:
http://www.tero.co.uk/des/explain.php#Padding
As long as you can properly decrypt the content you'll be fine.
I found my mistake. It turn out my BasicAuth Class isn't the correct one for encoding the encrypted string. Now I'm using the correct one Base64 Class for the encoding, and it turn out fine.
I am currently writing a program in Java that will accept strings from PHP and either encrypt or decrypt them depending on need. The mechanism of encryption is AES-256 and I am using the BouncyCastle API to do it. To ensure that there are fewer problems in transferring the data back and forth, I use Base64 to encode the strings. The problem I am experiencing is that randomly, I cannot decrypt a string-some string can be decrypted ok, others cannot. I found a great article here at stackoverflow I thought could help here.
But I could not really see how it could fit my circumstances (I am not an encryption expert). Here's my current code. Thanks for your help.
class AES {
private final BlockCipher AESCipher = new AESEngine();
private PaddedBufferedBlockCipher pbbc;
private KeyParameter key;
AES()
{
init();
}
private void init()
{
try
{
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(256);
SecretKey sk = kg.generateKey();
key=new KeyParameter(sk.getEncoded());
pbbc=new PaddedBufferedBlockCipher(AESCipher, new PKCS7Padding());
}
catch (Exception e)
{
//Take care of later
}
}
private byte[] processing(byte[] input, boolean encrypt)
throws DataLengthException, InvalidCipherTextException {
pbbc.init(encrypt, key);
byte[] output = new byte[pbbc.getOutputSize(input.length)];
int bytesWrittenOut = pbbc.processBytes(
input, 0, input.length, output, 0);
pbbc.doFinal(output, bytesWrittenOut);
return output;
}
private byte[] _encrypt(byte[] input)
throws DataLengthException, InvalidCipherTextException {
return processing(input, true);
}
private byte[] _decrypt(byte[] input)
throws DataLengthException, InvalidCipherTextException {
return processing(input, false);
}
public String Encrypt(String input)
{
try
{
byte[] ba = input.getBytes("UTF-8");
byte[] encr = _encrypt(ba);
byte[] encryptedByteValue = new Base64().encode(encr);
String encryptedValue = new String(encryptedByteValue);
return encryptedValue;//+" and decrypted is "+Decrypt(encryptedValue);
}
catch (Exception e)
{
return "ENCRYPT_ERROR "+e.getMessage();
}
}
public String Decrypt(String input)
{
try
{
byte[] decodedValue = new Base64().decode(input.getBytes());
byte[] retr = _decrypt(decodedValue);
return new String(retr, "UTF-8").replaceAll("\\u0000", "");
}
catch (Exception e)
{
return "DECRYPT_ERROR "+e.getMessage();
}
}
I figured out what the problem is, and it was two fold. This is what I wound up doing:
1) I was using cURL to communicate strings between Java and PHP and encoding encrypted text as Base64. Since the plus sign is valid in Base64 and not handled by cURL (at least by older versions), I would have mangled strings, thus leading to the error. I switched to hex encoding.
2) I had to remove carriage return (\r\n) characters from strings that went into the Java layer.
Hope this helps someone.