• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Rob Spoor
  • Bear Bibeault
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:
  • Frits Walraven
  • Himai Minh

pbe Encryption

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Friends am new to java am having error while encrypting using pbe am getting error

java.security.spec.InvalidKeySpecException: Invalid key spec

Unresolved compilation problem:
The constructor PBEKeySpec(char[], byte[], int) is undefined


and my code is
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

package attributehide;

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.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

/**
*
* @author
*/
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Random;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

public class Encdec {
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 char[] secretkey;
public Encdec() {

}

/**
*
* @param secretKey Key used to encrypt data
* @param plainText Text input to be encrypted
* @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 void PBEKeySpec(char[] secretkey, byte[] salt, int iterationCount){
this.secretkey=secretkey;
this.salt=salt;
this.iterationCount=iterationCount;
}
*/
public class PBEKeySpec extends Object implements KeySpec{

public PBEKeySpec(char[] charArray, byte[] salt, int iterationCount) {
// TODO Auto-generated constructor stub
}

}



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);
System.out.println(key);
// 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 sun.misc.BASE64Encoder().encode(out);
return encStr;
}





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 = new sun.misc.BASE64Decoder().decodeBuffer(encryptedText);
byte[] utf8 = dcipher.doFinal(enc);
String charSet="UTF-8";
String plainStr = new String(utf8, charSet);
return plainStr;
}

}

pl help me am in critical situation
thanks in advance
 
Bartender
Posts: 1166
17
Netbeans IDE Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why have you defined your own class PBEKeySpec ?
How are you testing this?
 
nagarajan nk
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
sir i dont know sir am new to java pl help me, am using that code for encrypting for the following class datas

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@page import="java.io.FileInputStream"%>

<%@page import="attributehide.*"%>

<%@page import="org.apache.poi.hssf.usermodel.HSSFRow"%>
<%@page import="org.apache.poi.hssf.usermodel.HSSFSheet" %>
<%@page import="org.apache.poi.hssf.usermodel.HSSFWorkbook" %>
<%@page import="java.io.FileOutputStream"%>
<%@page import="database.dbConnection"%>

<%@page import="java.sql.*" %>
<%@page import="java.util.Calendar"%>
<%@page import="java.util.Random"%>
<%@page import="java.math.BigInteger"%>
<%@page import="java.util.Scanner"%>
<%@page import="java.io.*"%>
<%@ page import="java.util.List"%>
<%@ page import="java.util.Iterator"%>
<%@ page import="java.io.File"%>
<%@ page import="org.apache.commons.io.FilenameUtils"%>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="database.dbConnection"%>

<%@page import=" java.util.HashMap"%>
<%@page import="test.RandomStringGenerator" %>
<%@page import="encn.Encript" %>
<%@page import="attributehide.Encdec" %>
<%@page import="javax.servlet.http.Part"%>
<%@page import="excelWork.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%


try{

//String patientid=request.getParameter("patientid");
//String key=request.getParameter("publickey");
String patientid="7234";
String key=RandomStringGenerator.generateRandomString(8,RandomStringGenerator.Mode.NUMERIC);
System.out.println(key);
HSSFWorkbook hwb=new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");

HSSFRow rowhead= sheet.createRow((short)0);
Encdec enc=new Encdec();
rowhead.createCell((short) 0).setCellValue(enc.encrypt(key,"teststk"));
rowhead.createCell((short) 1).setCellValue(enc.encrypt(key,"testrpt"));
rowhead.createCell((short) 2).setCellValue(enc.encrypt(key,"scanstk"));
rowhead.createCell((short) 3).setCellValue(enc.encrypt(key,"scanrpt"));
rowhead.createCell((short) 4).setCellValue(enc.encrypt(key,"pridoctor"));


Encdec encdec=new Encdec();
Connection con = dbConnection.getConn();
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("Select * from laboratory where patientid= '"+patientid+"'");
int i=1;
String filename=null;
while(rs.next())
{
filename="C:/reports/"+patientid+".xls" ;
HSSFRow row= sheet.createRow((short)i);
row.createCell((short) 0).setCellValue(enc.encrypt(key,rs.getString("teststk")));
row.createCell((short) 1).setCellValue(enc.encrypt(key,rs.getString("testrpt")));
row.createCell((short) 2).setCellValue(enc.encrypt(key,rs.getString("scanstk")));
row.createCell((short) 3).setCellValue(enc.encrypt(key,rs.getString("scanrpt")));
row.createCell((short) 4).setCellValue(enc.encrypt(key,rs.getString("pridoctor")));

i++;
}

FileOutputStream fileOut = new FileOutputStream(filename);
hwb.write(fileOut);
InputStream filecontent =null;
//filecontent = filename.getInputStream();
ServletInputStream sis = ((ServletRequest) response).getInputStream();
filecontent=sis;
FileInputStream fin=new FileInputStream(filename);
//part filepart=fileOut.getPart();
fileOut.close();

System.out.println("Your excel file has been generated!");
String insertTableSQL = "INSERT INTO patientkey VALUES(?,?)";
Connection conn=dbConnection.getConn();
PreparedStatement ps=conn.prepareStatement(insertTableSQL);
ps.setString(1,patientid);

ps.setString(2,key);
ps.executeUpdate();
%>
<h1>Report generated Successfully</h1>
<%


//JavaMailEx mail=new JavaMailEx();
//mail.SendMail("your key", "naga.nk91@gmail.com",key);

}
catch ( Exception ex )
{
System.out.println(ex);

}

%>
</body>
</html>
 
Richard Tookey
Bartender
Posts: 1166
17
Netbeans IDE Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

nagarajan nk wrote:sir i dont know sir am new to java pl help me, am using that code for encrypting for the following class datas



You don't need to create your own version of PBEKeySpec. Just import the one in package javax.crypto.spec.

A JSP is totally unsuitable for for testing your Encdec class. Just create a simple Java main program test harness. I did this to test your Encdec class (removing you definition of PBEKeySpec) and it worked.

That JSP creates two instances of class Encdec one of which does not seem to be used. Why are you encrypting cell values which are column titles (such as "teststk") ? Surely they do not need to be encrypted !

You should not put SQL directly into a JSP. You should create a class that has methods that perform the major operation needed by the JSP and test this outside of you JSP. In this way you dramatically simplify the JSP so that it becomes maintainable.

I don't understand the security model you are using. It seems dreadfully flawed to be sending a randomly generated key by insecure email (I have to read between the lines here since you have commented out email code) or into a database that anyone seems to be able to access. Could you explain your key exchange process?

You are obviously out of your depth with both Java and cryptography and this combination is pretty much sure to result in an insecure system. I can only imagine that this is a college/university project because if it is meant to go into a real world production system then the management of your company is very suspect.



 
nagarajan nk
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
sir i asked your code sir
 
Sheriff
Posts: 67537
173
Mac Mac OS X IntelliJ IDE jQuery TypeScript Java iOS
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
"nagarajan nk", please check your purple mooseages for an important administrative matter. Failure to do so will result in the removal of your account.
 
Richard Tookey
Bartender
Posts: 1166
17
Netbeans IDE Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Nagarajan - when you post code that you did not write you should really provide an acknowledgement and reference to the source. I don't know whether or not http://stackoverflow.com/questions/26956095/how-to-get-the-original-text-if-i-forget-the-key is where you got the code from but most of it is the same as your code.
 
Rancher
Posts: 43024
76
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There's a lot to be said about this code, but if you're a beginner -as you state- then I predict that you will not get it to work. There is simply too much going on that you will need to understand first. Can you maybe start with something simpler?
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic