Crypto Bad Padding Exception - java-8

I really need some help. I am working on this assignment in school. I'm supposed to read a txt file into a list or string, and Encrypt that list of string, save it and Decrypt it back into a list of string. I was able to Encrypt it and save it, but when I try to Decrypt it back, it give me an error message about Bad Padding. I really don't how to fix this problem. Any help will be really good.
This is my code for Encrypting it
import java.awt.FileDialog;
import java.awt.Frame;
import java.io.*;
import java.nio.file.*;
import java.security.*;
import java.util.*;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
public class WordAnalysisMenu {
private static KeyGenerator kgen;
private static SecretKey key;
private static byte[] iv = null;
static Scanner sc = new Scanner(System.in);
private static void init(){
try {
kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
key = kgen.generateKey();
} catch (NoSuchAlgorithmException e) {
}
}
public static void main (String [] arge) throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IOException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
List<String> warPeace = new ArrayList<>();
while(true) {
int choice = menu();
switch(choice) {
case 0:
break;
case 1:
//select file for reading
warPeace = readFile();
break;
case 7:
//apply the cipher and save it to a file
init();
Frame frame = new Frame();
FileDialog fileDialog = new FileDialog(frame, "", FileDialog.SAVE);
fileDialog.setVisible(true);
Path path = Paths.get(fileDialog.getDirectory() + fileDialog.getFile());
iv = ListEncrypter(warPeace, path, key);
break;
case 8:
// read the ciper file, decode, and print
init();
frame = new Frame();
fileDialog = new FileDialog(frame, "", FileDialog.LOAD);
fileDialog.setVisible(true);
Path inputFile = Paths.get(fileDialog.getDirectory() + fileDialog.getFile());
warPeace = ListDecrypter(inputFile, key, iv);
break;
case 9:
System.out.println("Good bye!");
System.exit(0);
break;
default:
break;
}
}
}
public static int menu() {
int choice = 0;
System.out.println("\nPlease make a selection: ");
System.out.println("1.\t Select a file for reading.");
System.out.println("7.\t Apply cipher & save");
System.out.println("8.\t Read encoded file");
System.out.println("9.\t Exit");
Scanner scan = new Scanner(System.in);
try {
choice = scan.nextInt();
scan.nextLine();
}
catch(InputMismatchException ime) {
System.out.println("Invalid input!");
}
return choice;
}
public static List<String> readFile() {
List<String> word = new ArrayList<String>();
Frame f = new Frame();
FileDialog saveBox = new FileDialog(f, "Reading text file", FileDialog.LOAD);
saveBox.setVisible(true);
String insName = saveBox.getFile();
String fileSavePlace = saveBox.getDirectory();
File inFile = new File(fileSavePlace + insName);
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(inFile));
String line;
while (((line = in.readLine()) != null)) {
System.out.println(line);
String s = new String();
word.add(line);
}
} catch (IOException io) {
System.out.println("There Was An Error Reading The File");
} finally {
try {
in.close();
} catch (Exception e) {
e.getMessage();
}
}
return word;
}
private static byte[] ListEncrypter(List<String> content, Path outputFile, SecretKey key)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException, IllegalBlockSizeException, BadPaddingException {
Cipher encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//Cipher encryptCipher = Cipher.getInstance("AES/CFB8/NoPadding");
encryptCipher.init(Cipher.ENCRYPT_MODE, key);
StringBuilder sb = new StringBuilder();
content.stream().forEach(e -> sb.append(e).append(System.lineSeparator()));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, encryptCipher);
cipherOutputStream.write(encryptCipher.doFinal(sb.toString().getBytes()));
//cipherOutputStream.write(sb.toString().getBytes());
cipherOutputStream.flush();
cipherOutputStream.close();
ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
Files.copy(inputStream, outputFile, StandardCopyOption.REPLACE_EXISTING);
return encryptCipher.getIV();
}
private static List<String> ListDecrypter(Path inputFile, SecretKey key, byte[] iv) throws
NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
InvalidAlgorithmParameterException, IOException, IllegalBlockSizeException, BadPaddingException {
Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//Cipher decryptCipher = Cipher.getInstance("AES/CBC/CFB8NoPadding");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
decryptCipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec);
List<String> fileContent = new ArrayList<>();
String line = null;
ByteArrayInputStream inputStream = new ByteArrayInputStream(Files.readAllBytes(inputFile));
try(CipherInputStream chipherInputStream = new CipherInputStream(new FileInputStream(inputFile.toFile()), decryptCipher);
BufferedReader br = new BufferedReader(new InputStreamReader(chipherInputStream))) {
while ((line = br.readLine()) != null) {
System.out.println(line);
//fileContent.add(line);
}
}
return null;
}
}
This is the error message.
Exception in thread "main" java.io.IOException:
javax.crypto.BadPaddingException: Given final block not properly
padded

Related

Run ansible playbook from java

Is there a way to execute ansible playbook from java.Can you please help me with reference could not find any good tutorial.
The simplest way is to run your command using ProcessBuilder:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class AnsibleServive {
public static void main(String[] args) {
runCommand("ansible-playbook test.yml -i host.ini");
}
private static void runCommand(String command) {
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("bash", "-c", command);
try {
Process process = processBuilder.start();
StringBuilder output = new StringBuilder();
StringBuilder errOutput = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((line = errReader.readLine()) != null) {
errOutput.append(line + "\n");
}
int exitVal = process.waitFor();
if (exitVal == 0) {
System.out.println("Command Successfully executed.");
System.out.println(output);
} else {
System.err.println("Error ocured during running command.");
System.out.println(output);
System.err.println(errOutput);
}
} catch (IOException | InterruptedException e) {
System.err.println("Failed to execute command.");
e.printStackTrace();
}
}
}

Error: cannot find symbol for BufferReader

I have the following code:
import.java.io.*;
public class BasheminParkingLot
{
public static void main(String[]args)throws Exception
{
Stack parkinglot = new Stack();
Stack alley= new Stack();
File f = new File("bashemin.in");
FileInputStream finstream = new FileInputStream(f);
InputStreamReader finreader = new InputStreamReader(finstream);
BufferReader finput = new BufferReader(finreader);
String line = finput.readLine();
String plate = "";
System.out.println();
System.out.println("The Bashemin Status");
System.out.println();
while(line!=null)
{
if(line.charAt(0)=='a')
{
plate = line.substring(1);
System.out.println ("car" + plate + " arrived and parked");
parkinglot.Push(plate);
}
}
}
}
and am getting the error:
BasheminParkingLot.java:13: error: cannot find symbol
BufferReader finput = new BufferReader(finreader);
^
I was wondering if anyone could help me debug this?? Thanks!
This shouldn't be BufferReader. It should be BufferedReader.
The following code will work:
import java.io.*;
class Stack {
int x;
void Push(String value) {
// DO SOMETHING
}
}
public class BasheminParkingLot
{
public static void main(String[]args)throws IOException
{
Stack parkinglot = new Stack();
Stack alley= new Stack();
File f = new File("bashemin.in");
FileInputStream finstream = new FileInputStream(f);
InputStreamReader finreader = new InputStreamReader(finstream);
BufferedReader finput = new BufferedReader(finreader);
String line = finput.readLine();
String plate = "";
System.out.println();
System.out.println("The Bashemin Status");
System.out.println();
while(line!=null)
{
if(line.charAt(0)=='a')
{
plate = line.substring(1);
System.out.println ("car" + plate + " arrived and parked");
parkinglot.Push(plate);
}
}
}
}

GUI JFrame background color change

I've revisited this post. I have been able to upload the text file, create a GUI, populate the GUI with JRadioButtons that are labeled from the text file...
Now, I cannot get the background to change color when the JRadioButton is selected! I know that it has something to do with the ActionListener, but how do I fix this? The color needs to be implemented from the hex color code.
public class FP extends JFrame implements ActionListener {
TreeMap<String, String> buttonMap = new TreeMap <>();
// Constructor
#SuppressWarnings("empty-statement")
public FP() throws IOException {
JPanel panel = new JPanel();
add(panel, BorderLayout.CENTER);
panel.setBorder(new TitledBorder("Pick a Radio Button!"));
JRadioButton[] btnArray = new JRadioButton[20];
ButtonGroup btnGroup = new ButtonGroup();
BufferedReader reader;
reader = new BufferedReader(new FileReader("src/colors.txt"));
String currentLine = reader.readLine();
while (currentLine != null) {
String[] pair = currentLine.split("\\s+");
buttonMap.put(pair[0],pair[1]);
currentLine = reader.readLine();
}
//check retrieving values from the buttonMap
for(Map.Entry<String,String> entry : buttonMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
}
for (int i = 0; i<20; i++){
for(Map.Entry<String, String> entry : buttonMap.entrySet()){
JRadioButton rb = new JRadioButton(entry.getKey() + " " + entry.getValue());
panel.add(rb);
btnGroup.add(rb);
rb.addActionListener(this);
}
}
//private final JRadioButton btnMale = new JRadioButton("Male")
Collection bMapIt = buttonMap.entrySet();
Iterator it = bMapIt.iterator();
System.out.println("Colors and codes");
while(it.hasNext())
System.out.println(it.next());
}
#Override
public void actionPerformed(ActionEvent e) {
setBackground(Color.decode(buttonMap.get(e)));
}
public static void main(String[] args) throws IOException {
FP frame = new FP();
frame.setVisible(true);
frame.setSize(350, 240);
frame.setTitle("Final Project");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
for(Map.Entry<String, String> entry : buttonMap.entrySet()){
for (int i = 0; i<1; i++){
btnArray[i] = new JRadioButton(entry.getKey() + " " + entry.getValue());
panel.add(btnArray[i]);
btnGroup.add(btnArray[i]);
btnArray[i].addActionListener((ActionEvent e) -> {
String btnColor = buttonMap.get(((JRadioButton) e.getSource()).getText());
String hexColor = entry.getValue();
System.out.println(hexColor);
panel.setBackground(Color.decode("#"+hexColor));
});
}
}
This with the addition of class....
#Override
public void actionPerformed(ActionEvent e) {}
}

How to use accesslog_parser.pl Kannel access log parser?

I have found kannel access log parser accesslog_parser.pl in utils folder.
How to use this file for parse.
Also i want convert kannel_access.log in csv format. Please help me.
Assuming Kannel log is at /var/log/kannel/access.log
This should do
cat /var/log/kannel/access.log |accesslog_parser.pl
May be an old question but I'd like to share this small tool a wrote in java for parsing kannel log files and outputing the results in csv format:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.StringTokenizer;
/**
*
* #author bashizip
*/
public class KannelLogsParser {
static String fileName;
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// fileName = args[0];
fileName = "access_kannel.txt";
String allLines = readLines(fileName);
parseAndWriteToCsv(allLines);
}
static String readLines(String fileName) {
BufferedReader br = null;
String sCurrentLine = null;
StringBuilder sb = new StringBuilder();
try {
br = new BufferedReader(
new FileReader(fileName));
while ((sCurrentLine = br.readLine()) != null) {
sb.append(sCurrentLine).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return sb.toString();
}
private static void parseAndWriteToCsv(String allLines) throws IOException {
String[] lines = allLines.split("\n");
System.out.println("lines to parse : " + lines.length);
StringTokenizer st;
StringBuilder output = new StringBuilder();
output.append("DATE;Heure;sent;SMS; SMSC; SVC; ACT; BINF; FID; from; to; flags; msg;;udh"+"\n");
int count = 0;
for (String line : lines) {
count++;
System.out.println("Parsing ..." + 100 * count / lines.length + "%");
st = new StringTokenizer(line, " ");
while (st.hasMoreTokens()) {
String currentToken = st.nextToken();
boolean messageToken = false;
boolean afterMessageToken = false;
if (currentToken.startsWith("[")) {
System.out.println(currentToken);
messageToken = currentToken.startsWith("[msg");
try {
currentToken = currentToken.substring(currentToken.indexOf(":") + 1, currentToken.indexOf("]"));
} catch (Exception e) {
System.err.println(e.getMessage());
messageToken = true;
currentToken = currentToken.substring(currentToken.indexOf(":") + 1);
}
}
currentToken = currentToken.replace("[", "");
currentToken = currentToken.replace("]", "");
output.append(currentToken);
if (!messageToken) {
output.append(";");
} else if (afterMessageToken) {
afterMessageToken = false;
output.append(" ");
} else {
output.append(" ");
afterMessageToken = true;
}
}
output.append("\n");
}
Files.write(Paths.get(fileName + ".csv"), output.toString().getBytes());
System.out.println("Output CVS file: " + fileName + ".csv");
System.out.println("Finished !");
}
}
Hope it can help someone one day :-)

Vaadin: Downloaded file has whole path as file name

I have a download action implemented on my Vaadin application but for some reason the downloaded file has the original file's full path as the file name.
Any idea?
You can see the code on this post.
Edit:
Here's the important part of the code:
package com.bluecubs.xinco.core.server.vaadin;
import com.bluecubs.xinco.core.server.XincoConfigSingletonServer;
import com.vaadin.Application;
import com.vaadin.terminal.DownloadStream;
import com.vaadin.terminal.FileResource;
import java.io.*;
import java.net.URLEncoder;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
/**
*
* #author Javier A. Ortiz Bultrón<javier.ortiz.78#gmail.com>
*/
public class FileDownloadResource extends FileResource {
private final String fileName;
private File download;
private File newFile;
public FileDownloadResource(File sourceFile, String fileName,
Application application) {
super(sourceFile, application);
this.fileName = fileName;
}
protected void cleanup() {
if (newFile != null && newFile.exists()) {
newFile.delete();
}
if (download != null && download.exists() && download.listFiles().length == 0) {
download.delete();
}
}
#Override
public DownloadStream getStream() {
try {
//Copy file to directory for downloading
InputStream in = new CheckedInputStream(new FileInputStream(getSourceFile()),
new CRC32());
download = new File(XincoConfigSingletonServer.getInstance().FileRepositoryPath
+ System.getProperty("file.separator") + UUID.randomUUID().toString());
newFile = new File(download.getAbsolutePath() + System.getProperty("file.separator") + fileName);
download.mkdirs();
OutputStream out = new FileOutputStream(newFile);
newFile.deleteOnExit();
download.deleteOnExit();
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
final DownloadStream ds = new DownloadStream(
new FileInputStream(newFile), getMIMEType(), fileName);
ds.setParameter("Content-Disposition", "attachment; filename="
+ URLEncoder.encode(fileName, "utf-8"));
ds.setCacheTime(getCacheTime());
return ds;
} catch (final FileNotFoundException ex) {
Logger.getLogger(FileDownloadResource.class.getName()).log(Level.SEVERE, null, ex);
return null;
} catch (IOException ex) {
Logger.getLogger(FileDownloadResource.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
}
I already debugged and verified that fileName only contains the file's name not the whole path.
The answer was actually a mix of houman001's answer and this post: https://vaadin.com/forum/-/message_boards/view_message/200534
I went away from the above approach to a simpler working one:
StreamSource ss = new StreamSource() {
byte[] bytes = //Get the file bytes here
InputStream is = new ByteArrayInputStream(bytes);
#Override
public InputStream getStream() {
return is;
}
};
StreamResource sr = new StreamResource(ss, <file name>, <Application Instance>);
getMainWindow().open(sr, "_blank");
Here is my code that works fine (downloading a blob from database as a file), but it's using a Servlet and OutputStream rather than DownloadStream in your case:
public class TextFileServlet extends HttpServlet
{
public static final String PARAM_BLOB_ID = "id";
private final Logger logger = LoggerFactory.getLogger(TextFileServlet.class);
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException
{
Principal userPrincipal = req.getUserPrincipal();
PersistenceManager pm = PMFHolder.get().getPersistenceManager();
Long id = Long.parseLong(req.getParameter(PARAM_BLOB_ID));
MyFile myfile = pm.getObjectById(MyFile.class, id);
if (!userPrincipal.getName().equals(myfile.getUserName()))
{
logger.info("TextFileServlet.doGet - current user: " + userPrincipal + " file owner: " + myfile.getUserName());
return;
}
res.setContentType("application/octet-stream");
res.setHeader("Content-Disposition", "attachment;filename=\"" + myfile.getName() + "\"");
res.getOutputStream().write(myfile.getFile().getBytes());
}
}
I hope it helps you.
StreamResource myResource = createResource(attachmentName);
System.out.println(myResource.getFilename());
if(attachmentName.contains("/"))
attachmentName = attachmentName.substring(attachmentName.lastIndexOf("/"));
if(attachmentName.contains("\\"))
attachmentName = attachmentName.substring(attachmentName.lastIndexOf("\\"));
myResource.setFilename(attachmentName);
FileDownloader fileDownloader = new FileDownloader(myResource);
fileDownloader.extend(downloadButton);

Resources