I am trying to figure out why my DES code for cbc mode is not working. I get an error that says :
error: unreported exception NoSuchProviderException; must be caught or declared to be thrown
desCipher = Cipher.getInstance("DES/CBC/PKCS5Padding", "CB");
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
public class JEncrytion
{
public static void main(String[] argv) {
try{
KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
SecretKey myDesKey = keygenerator.generateKey();
Cipher desCipher;
// Create the cipher
desCipher = Cipher.getInstance("DES/CBC/PKCS5Padding", "CB");
// Initialize the cipher for encryption
desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
//sensitive information
byte[] text = "hello world how are you".getBytes();
System.out.println("Text [Byte Format] : " + text);
System.out.println("Text : " + new String(text));
// Encrypt the text
byte[] textEncrypted = desCipher.doFinal(text);
System.out.println("Text Encryted : " + textEncrypted);
// Initialize the same cipher for decryption
desCipher.init(Cipher.DECRYPT_MODE, myDesKey);
// Decrypt the text
byte[] textDecrypted = desCipher.doFinal(textEncrypted);
System.out.println("Text Decryted : " + new
String(textDecrypted));
}catch(NoSuchAlgorithmException e){
e.printStackTrace();
}catch(NoSuchPaddingException e){
e.printStackTrace();
}catch(InvalidKeyException e){
e.printStackTrace();
}catch(IllegalBlockSizeException e){
e.printStackTrace();
}catch(BadPaddingException e){
e.printStackTrace();
}
}
}
Do what the message says - declare an exception:
public static void main(String[] argv) throws Exception {
In your case a general exception is sufficient.
You need not to use Provider CB in Cipher.getInstance(). So, you will not get NoSuchProviderException anymore.
Just see below code, It works perfectly.
import java.security.InvalidKeyException;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.SecretKey;
public class JEncryption
{
public static void main(String[] argv) {
try{
KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
SecretKey myDesKey = keygenerator.generateKey();
Cipher desCipher;
// Create the cipher
desCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
// Initialize the cipher for encryption
desCipher.init(Cipher.ENCRYPT_MODE, myDesKey,iv);
//sensitive information
byte[] text = "hello world how are you".getBytes();
System.out.println("Text [Byte Format] : " + text);
System.out.println("Text : " + new String(text));
// Encrypt the text
byte[] textEncrypted = desCipher.doFinal(text);
System.out.println("Text Encryted : " + textEncrypted);
// Initialize the same cipher for decryption
desCipher.init(Cipher.DECRYPT_MODE, myDesKey,iv);
// Decrypt the text
byte[] textDecrypted = desCipher.doFinal(textEncrypted);
System.out.println("Text Decryted : " + new String(textDecrypted));
}catch(NoSuchAlgorithmException 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();
}
}
}
Related
I am new to React Native.
The server side guy has written encryption logic in Java which goes as following
import java.io.UnsupportedEncodingException;
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;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
#Service
public class AES {
#Autowired
static AesProps props;
private static String secretkey = "abcdefghijklmnopqhijklmnopq"; // Sample key
private static SecretKeySpec secretKey;
private static byte[] key;
public static void setKey(String myKey) {
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public static String encrypt(String strToEncrypt) {
try {
setKey(secretkey);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
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;
}
I am trying to find a way to encrypt in React Native, which will give me the same cipher as above Java code.
I went through react-native-aes-cryptobut many things are missing. Like how to use PKCS5PADDING and how to do corresponding SecretKeySpec.
Any help would be much appreciated.
I am trying to read a file of size 1KB, then encrypting and decrypting it with AES algorithm in CBC mode. When I am trying to initialize cipher it is throwing an error. Please find the code below.
I could not find an init method in cipher class which accepts "encryption mode", "secret key", and the initialization vector of class IvParameterSpec. I can see init method with expecting parameters like(int encryption mode, Key key, AlgorithmParameters algoParameters, SecureRandom secureRandom)
Do I need to convert my key and initialization vector to the required class.
Any insights to proceed further would be helpful.
import sun.security.provider.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.io.File;
import java.security.AlgorithmParameters;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidParameterSpecException;
public class AESFileEncryptionDecryption {
public class AES128CBC{
SecretKey secretKey;
Cipher cipher;
SecureRandom secureRandom = new SecureRandom();
byte[] iv = new byte[16];
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
{
try {
secretKey = KeyGenerator.getInstance("AES").generateKey();
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(1,secretKey,ivParameterSpec);
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
File inputFile_1KB = new File("/Users/siddharthsinha/Desktop/input1KB.txt");
File encryptedFile_1KB = new File("/Users/siddharthsinha/Desktop/input1KB.encrypted");
File decryptedFile_1KB = new File("/Users/siddharthsinha/Desktop/input1KB.decrypted.txt");
}
}
your code is neither catching nor throwing two possibly thrown exceptions:
try {
secretKey = KeyGenerator.getInstance("AES").generateKey();
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(1,secretKey,ivParameterSpec);
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
So I have generated a key pair in keytool and generated a symmetric key and the encrypted a String with the symmetric key and then encrypted the symmetric key. Now I have to decrypt the symmetric key and I am having some trouble. The code I am using for decryption is not throwing back any errors but it is not actually doing anything either and I am not sure what I am doing wrong.
package ReadFileExample;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.KeyException;
import java.security.KeyPair;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.security.cert.Certificate;
import java.security.KeyStore;
import java.security.Key;
import java.io.FileInputStream;
public class generatekey {
static Cipher cipher;
public static void main(String[] args) throws Exception {
// generating a symmetric key using the AES algorithm
KeyGenerator generator = KeyGenerator.getInstance("AES");
// 128 bit key
generator.init(128);
//generates a secret key
SecretKey secretkey = generator.generateKey();
// returns an AES cipher
cipher = Cipher.getInstance("AES");
//print key
System.out.println("Key: " + cipher);
String plainText = "Hello World";
// call to method encrypt
String encryptedText = encrypt(plainText, secretkey);
// print orignial text and encrypted text
System.out.println("Plain Text: " + plainText);
System.out.println("Encrypted Text: " + encryptedText);
String publicKey = "C:/Users/girgich/public.cert";
// allows to write data to a file
FileOutputStream fos = null;
// write bytes to file
BufferedOutputStream bos = null;
// create file to which data needs to be written
String fileName = "C:/Users/girgich/newFile.txt";
try{
// allows written data to go into the written path
fos = new FileOutputStream(fileName);
// converts written data into bytes
bos = new BufferedOutputStream(fos);
// writes the encrypted text into file
bos.write(encryptedText.getBytes());
System.out.println("encryptedText has been written successfully in "
+fileName);
// allows to catch bug in code
} catch (IOException e) {
e.printStackTrace();
} finally {
try{
// check for null exception
if (bos != null){
bos.close();
}
// check for null exception
if (fos != null){
fos.close();
}
} catch (IOException e){
e.printStackTrace();
}
}
// creates a file input stream by opening a path to the file needed
FileInputStream fin = new
FileInputStream("C:/Users/girgich/public.cert");
// implements the X509 certificate type
CertificateFactory f = CertificateFactory.getInstance("X.509");
// initalizes data found in the file
X509Certificate certificate =
(X509Certificate)f.generateCertificate(fin);
// gets public key from this certificate
PublicKey pk = certificate.getPublicKey();
System.out.println(pk);
String encryptedTextKey = encryptedKey(pk, secretkey);
System.out.println("Encrypted Key: " + encryptedTextKey);
// allows to write data to a file
FileOutputStream newFos = null;
// write bytes to file
BufferedOutputStream newBos = null;
// create file to which data needs to be written
String fileNameKey = "C:/Users/girgich/symmetric.txt";
try{
// allows written data to go into the written path
newFos = new FileOutputStream(fileNameKey);
// converts written data into bytes
newBos = new BufferedOutputStream(newFos);
// writes the encrypted text into file
newBos.write(encryptedTextKey.getBytes());
System.out.println("encryptedKey has been written successfully in "
+fileNameKey);
// allows to catch bug in code
} catch (IOException e) {
e.printStackTrace();
} finally {
try{
// check for null exception
if (newBos != null){
newBos.close();
}
// check for null exception
if (newFos != null){
newFos.close();
}
} catch (IOException e){
e.printStackTrace();
}
}
String decrypt = (encryptedTextKey);
}
public static String encrypt(String plainText, SecretKey secretkey) throws
Exception {
//Encodes the string into a sequence of bytes
byte[] plainTextByte = plainText.getBytes();
//intialize cipher to encryption mode
cipher.init(Cipher.ENCRYPT_MODE, secretkey);
//data is encrypted
byte[] encryptedByte = cipher.doFinal(plainTextByte);
Base64.Encoder encoder = Base64.getEncoder();
//encodes bytes into a string using Base64
String encryptedText = encoder.encodeToString(encryptedByte);
// return the string encrypted text to the main method
return encryptedText;
}
public static String encryptedKey(PublicKey pk, SecretKey secretkey) throws Exception {
// data written to byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// writes data types to the output stream
ObjectOutputStream writter = new ObjectOutputStream(baos);
//specific object of secretkey is written to the output stream
writter.writeObject(secretkey);
//creates a byte array
byte[] plainTextByteKey = baos.toByteArray();
//creates a cipher using the RSA algorithm
Cipher cipher = Cipher.getInstance("RSA");
// initalizes cipher for encryption using the public key
cipher.init(Cipher.ENCRYPT_MODE, pk);
//encrypts data
byte[] encryptedByteKey = cipher.doFinal(plainTextByteKey);
Base64.Encoder encoderKey = Base64.getEncoder();
// encodes the byte array into a string.
String encryptedTextKey = encoderKey.encodeToString(encryptedByteKey);
return encryptedTextKey;
}
public void decrypt(String encryptedTextKey) {
byte[] decryptedData = null;
String password = "******";
try {
FileInputStream is = new FileInputStream("C:/Users/girgich/keystore.jks");
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(is, password.toCharArray());
String alias = "mykey";
Key key = keystore.getKey(alias, password.toCharArray());
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, key);
decryptedData = cipher.doFinal(encryptedTextKey.getBytes());
System.out.println("Decrypted Key: " + decryptedData);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I need to generate a Key in order to use it for encryption and decryption using an AES cipher.
The key must be generated on runtime using a single id value.
How could I generate a Key taking a single string as source?
Hope this can help you.
package com.lahiru.security;
import java.io.UnsupportedEncodingException;
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;
public static void main(String[] args){
String id = "00001";
String plainText = "This is plain text";
String cipherText = encrypt(plainText, id);
System.out.println("Cipher Text after encrption ::: " + cipherText);
System.out.println("Plain Text after decryption ::: " + decrypt(cipherText, id));
}
public static void setKey(String myKey)
{
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public static String encrypt(String strToEncrypt, String secret)
{
try
{
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
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 static String decrypt(String strToDecrypt, String secret)
{
try
{
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
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;
}
}
I want to take a piece of plain text, a symmetric key(from a previous computation) in the form of a byte[] and output a cipher text. cipherText = encrypt(plainText,sharedSecret)
How do I merge the plain text and the shared secret?
public static String encrypt(String plainText, byte[] sharedSecret){
String cipherText = "";
//combining the sharedSecret with the plainText
return cipherText;
}
Check this code for symmetric key encryption. You can refactor to suit your encrypt method.
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
public class SymmEncryption {
public static void main(String[] args) throws InvalidAlgorithmParameterException {
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(256); // 56 is the keysize. Fixed for DES
//Initialization Vector
byte[] iv = "1234567812345678".getBytes();
IvParameterSpec ivSpec = new IvParameterSpec(iv);
SecretKey secretKey = keyGenerator.generateKey();
System.out.println(secretKey.getFormat());
Cipher desCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//algorithm/mode/padding
//Electronic Codebook (ECB)
System.out.format("Secret Key: %s--%s--%s%n", secretKey.getAlgorithm(), secretKey.getFormat(), secretKey.getEncoded());
// Initialize the cipher for encryption
desCipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
// sensitive information
byte[] text = "No body can see me".getBytes();
System.out.println("Hex text: " + byteArrayToHex(text));
System.out.println("Text [Byte Format] : " + text);
System.out.println("Text : " + new String(text));
// Encrypt the text
byte[] textEncrypted = desCipher.doFinal(text);
System.out.println("Text Encryted : " + textEncrypted);
System.out.println("Hex Encrypted text: " + byteArrayToHex(textEncrypted));
// Initialize the same cipher for decryption
desCipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
// Decrypt the text
byte[] textDecrypted = desCipher.doFinal(textEncrypted);
System.out.println("Text Decryted : " + new String(textDecrypted));
System.out.println("Hex Decrypted text: " + byteArrayToHex(textDecrypted));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
}
static String byteArrayToHex(byte[] a) {
StringBuilder sb = new StringBuilder();
for (byte b : a)
sb.append(String.format("%02x", b & 0xff));
return sb.toString();
}
}