NullPointerException exception when encrypting and serializing [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I'm trying to encrypt an ArrayList type and serialize it. Following is my code.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.NoSuchPaddingException;
import premierleague.model.FootballClub;
import premierleague.model.Match;
/**
*
* #author Akila
*/
public class Serializing implements Serializable{
private FileInputStream fileIn;
private FileOutputStream fileOut;
private ObjectInputStream in;
private ObjectOutputStream out;
public ArrayList<FootballClub> FootBallInputStream() throws FileNotFoundException, IOException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchPaddingException {
Cipher cipher = Cipher.getInstance("DES");
File file = new File("FootballClub.ser");
fileIn = new FileInputStream(file);
CipherInputStream CipherIn = new CipherInputStream(in, cipher);
in = new ObjectInputStream(CipherIn);
ArrayList<FootballClub> e = (ArrayList<FootballClub>) in.readObject();
in.close();
fileIn.close();
return e;
}
public void FootBallOutputStream(ArrayList<FootballClub> e) throws FileNotFoundException, IOException, NoSuchAlgorithmException, NoSuchPaddingException {
Cipher cipher = Cipher.getInstance("DES");
File file = new File("FootballClub.ser");
fileOut = new FileOutputStream(file);
CipherOutputStream cipherOut = new CipherOutputStream(out,cipher);
out = new ObjectOutputStream(cipherOut);
out.writeObject(e);
out.close();
fileOut.close();
}
}
Although i get a NullPointer exception when trying to use the these methods.
Exception in thread "main" java.lang.NullPointerException
at javax.crypto.CipherInputStream.getMoreData(CipherInputStream.java:103)
at javax.crypto.CipherInputStream.read(CipherInputStream.java:224)
at java.io.ObjectInputStream$PeekInputStream.read(ObjectInputStream.java:2289)
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2302)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2773)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:798)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:298)
at premierleague.controller.Serializing.FootBallInputStream(Serializing.java:41)
I've already initiaized CipherInputStream object and ObjectInputStream object. Yet, it throws me a null pointer exception
EDIT
public ArrayList<FootballClub> FootBallInputStream() throws FileNotFoundException, IOException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, key);
File file = new File("FootballClub.ser");
fileIn = new FileInputStream(file);
CipherInputStream CipherIn = new CipherInputStream(fileIn, cipher);
in = new ObjectInputStream(CipherIn);
ArrayList<FootballClub> e = (ArrayList<FootballClub>) in.readObject();
in.close();
fileIn.close();
return e;
}
public void FootBallOutputStream(ArrayList<FootballClub> e) throws FileNotFoundException, IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
Cipher cipher = (Cipher.getInstance("DES"));
cipher.init(Cipher.ENCRYPT_MODE, key);
File file = new File("FootballClub.ser");
fileOut = new FileOutputStream(file);
CipherOutputStream cipherOut = new CipherOutputStream(fileOut, cipher);
out = new ObjectOutputStream(cipherOut);
out.writeObject(e);
out.close();
fileOut.close();
}
Exception
Exception in thread "main" java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2304)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2773)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:798)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:298)
at premierleague.controller.Serializing.FootBallInputStream(Serializing.java:47)
FootballClub Class
package premierleague.model;
/**
*
* #author Akila
*/
public class FootballClub extends SportsClub implements Comparable<FootballClub>{
private int wins;
private int defeats;
private int draws;
private int currentPoints=0;
private int goalsRecieved;
private int goalsScored;
// public FootballClub(String name, String location) {
// super.getClubName()= ;
// super.getLocation()= location;
//
// }
public int getWins() {
return wins;
}
public void setWins(int wins) {
this.wins = wins;
}
public int getDefeats() {
return defeats;
}
public void setDefeats(int defeats) {
this.defeats = defeats;
}
public int getDraws() {
return draws;
}
public void setDraws(int draws) {
this.draws = draws;
}
public int getCurrentPoints() {
return currentPoints;
}
public void setCurrentPoints(int currentPoints) {
this.currentPoints = currentPoints;
}
public int getGoalsRecieved() {
return goalsRecieved;
}
public void setGoalsRecieved(int goalsRecieved) {
this.goalsRecieved = goalsRecieved;
}
public int getGoalsScored() {
return goalsScored;
}
public void setGoalsScored(int goalsScored) {
this.goalsScored = goalsScored;
}
// #Override
// public int compareTo(FootballClub o) {
// if (this.getCurrentPoints()> o.getCurrentPoints()) {
// return 1;
//
// }else if (this.getCurrentPoints()== o.getCurrentPoints()){
// if (this.getCurrentPoints()> o.getCurrentPoints()) {
// return 1;
//
// }else{
// return -1;
// }
// }else{
// return -1;
// }
//
// }
//
#Override
public int compareTo(FootballClub o) {
if(this.getCurrentPoints()>o.getCurrentPoints()){
return 1;
}else if(this.getCurrentPoints()==o.getCurrentPoints()){
if(this.getCurrentPoints()>o.getCurrentPoints()){
return 1;
}else {
return -1;
}
}else{
return -1;
}
}
public static final long serialVersionUID = 948599023243074087L;
}
NEW EDIT
public ArrayList<FootballClub> FootBallInputStream() throws FileNotFoundException, IOException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
File file = new File("FootballClub.ser");
fileIn = new FileInputStream(file);
SecretKey key = KeyGenerator.getInstance("AES").generateKey();
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
CipherInputStream cipherIn = new CipherInputStream(fileIn, cipher);
in = new ObjectInputStream(cipherIn);
SealedObject sealed = (SealedObject) in.readObject();
ArrayList<FootballClub> e = (ArrayList<FootballClub>) sealed.getObject(cipher);
in.close();
fileIn.close();
return e;
}
public void FootBallOutputStream(ArrayList<FootballClub> e) throws FileNotFoundException, IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException {
File file = new File("FootballClub.ser");
fileOut = new FileOutputStream(file);
SecretKey key = KeyGenerator.getInstance("AES").generateKey();
Cipher cipher = (Cipher.getInstance("AES"));
cipher.init(Cipher.ENCRYPT_MODE, key);
SealedObject sealed = new SealedObject(e, cipher);
CipherOutputStream cipherOut = new CipherOutputStream(fileOut, cipher);
out = new ObjectOutputStream(cipherOut);
out.writeObject(sealed);
out.close();
fileOut.close();
}
NEW EXCEPTION
Exception in thread "main" java.io.StreamCorruptedException: invalid stream header: CF8CA0C1
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:801)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:298)
at premierleague.controller.Serializing.FootBallInputStream(Serializing.java:54)

try
cipher = Cipher.getInstance("DES")
instead of
Cipher cipher = Cipher.getInstance("DES");
also maybe check your brackets and you're returning something in the first method but their is no return type

Related

Converting TripleDes algorithm

I want to convert following C# to java code, so we can decrypt old messages and encrypt new ones in java.
public class encryptionUtil
{
private TripleDESCryptoServiceProvider TripleDes;
private UTF8Encoding utfEncoding;
private byte[] key;
private byte[] iv;
private string sysKey;
private string sysUser;
public encryptionUtil()
{
this.TripleDes = new TripleDESCryptoServiceProvider();
this.utfEncoding = new UTF8Encoding();
this.key = this.utfEncoding.GetBytes("123456789012345678901234");
this.iv = this.utfEncoding.GetBytes("12345678");
this.sysKey = WindowsIdentity.GetCurrent().Name;
this.sysUser = WindowsIdentity.GetCurrent().User.Value;
}
public string EncryptData(string plaintext)
{
string str;
try
{
plaintext = plaintext + this.sysUser;
byte[] bytes = Encoding.Unicode.GetBytes(plaintext);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream((Stream) memoryStream, this.TripleDes.CreateEncryptor(this.key, this.iv), CryptoStreamMode.Write);
cryptoStream.Write(bytes, 0, bytes.Length);
cryptoStream.FlushFinalBlock();
str = Convert.ToBase64String(memoryStream.ToArray());
}
catch (Exception ex)
{
ProjectData.SetProjectError(ex);
str = plaintext ;
ProjectData.ClearProjectError();
}
return str;
}
public string DecryptData(string encryptedtext)
{
string str;
try
{
byte[] buffer = Convert.FromBase64String(encryptedtext);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream((Stream) memoryStream, this.TripleDes.CreateDecryptor(this.key, this.iv), CryptoStreamMode.Write);
cryptoStream.Write(buffer, 0, buffer.Length);
cryptoStream.FlushFinalBlock();
string[] strArray = Encoding.Unicode.GetString(memoryStream.ToArray());
str = Microsoft.VisualBasic.CompilerServices.Operators.CompareString(strArray[1], this.token, false) != 0 ? "" : strArray[0];
}
catch (Exception ex)
{
ProjectData.SetProjectError(ex);
str = "";
ProjectData.ClearProjectError();
}
return str;
}
Encryption output in c# for "Encrypt this in java"
7UlYtjB6Nls4Q3Ac4VzdY2k6hVRa1Eqjyt2ZG4818WxLCwFhx1fEeTCvOStTylyMM5ucL4DmF1NKBRga44Yqrj89VHRKZuWnFC24jMkSxucZkB3niLa7WOT4GKlii7716w6TC9iJGYLhy8mY1kqwaw==
Java code written so far, how to proceed further so that I get same result as above?
package com.mycompany.util;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
public class EncryptionUtil {
private static SecretKey sharedkey;
private static byte [] sharedvector;
static {
int keySize = 168;
int ivSize = 8;
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
keyGenerator.init(keySize);
sharedkey = keyGenerator.generateKey();
sharedvector = new byte [ivSize];
byte [] data = sharedkey.getEncoded();
int half = ivSize / 2;
System.arraycopy(data, data.length-half, sharedvector, 0, half);
System.arraycopy(sharedvector, 0, sharedvector, half, half);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
public static void main(String [] args) throws Exception {
String plainText = "Encrypt this in java";
String systemId= "949367136-5890454";
String dataText = plainText+systemId
String keyString = "key1234";
String ivString = "iv1234";
try {
byte[] keyBytes = keyString.getBytes("UTF-8");
byte[] ivBytes = ivString.getBytes("UTF-8");
byte[] dataBytes = plainText.getBytes("UTF-8");
System.out.println("key="+keyBytes.toString());
System.out.println("iv="+ivBytes.toString());
System.out.println("plaintextBytesUTF-8="+dataBytes.toString());
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String Encrypt(String val) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, sharedkey, new IvParameterSpec(sharedvector));
return new sun.misc.BASE64Encoder().encode(cipher.doFinal(val.getBytes()));
}
public static String Decrypt(String val) throws GeneralSecurityException, IOException {
Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, sharedkey, new IvParameterSpec(sharedvector));
return new String(cipher.doFinal(new sun.misc.BASE64Decoder().decodeBuffer(val)));
}
}

3DES Encryption Oracle/JAVA equivalent

I'm trying to migrate the oracle method dbms_obfuscation_toolkit.DES3Encrypt to a Java Function. My problem is that I don't get the same encrypted value in both scenes.
For this procedure in Oracle:
set serveroutput on;
declare
input raw(128);
encrypted raw(2048);
cadena varchar2(60);
begin
dbms_obfuscation_toolkit.DES3Encrypt(
input => utl_raw.cast_to_raw('TESTDATATESTDATATESTDATA'),
key => utl_raw.cast_to_raw('GD6GTT56HKY4HGF6FH3JG9J5F62FT1'),
encrypted_data => encrypted
);
dbms_output.put_line(rawtohex(encrypted));
end;
I get this output:
8A2E6792E39B0C850377F9A0E054033963F979E4A3FBA25B
However, with this Java class:
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
public class TripleDes2
{
private static final String PLAIN_TEXT = "TESTDATATESTDATATESTDATA";
private static final String SHARED_KEY = "GD6GTT56HKY4HGF6FH3JG9J5F62FT1";
public static void main(String args []) throws Exception
{
String algorithm = "DESede";
String transformation = "DESede/CBC/PKCS5Padding";
byte[] keyValue = SHARED_KEY.getBytes("UTF-8");
DESedeKeySpec keySpec = new DESedeKeySpec(keyValue);
IvParameterSpec iv = new IvParameterSpec(new byte[8]);
SecretKey key = SecretKeyFactory.getInstance(algorithm).generateSecret(keySpec);
Cipher encrypter = Cipher.getInstance(transformation);
encrypter.init(Cipher.ENCRYPT_MODE, key, iv);
byte[] input = PLAIN_TEXT.getBytes("UTF-8");
byte[] encrypted = encrypter.doFinal(input);
System.out.println(new String(Hex.encodeHex(encrypted)).toUpperCase());
}
}
I'm getting this value:
82EBC149F298DE55E4FF1540615E60ACDB7743FE79CD2CF4BB6FD232893F83D0
I'm not sure if my Java Code is right. Can you help me?
Thank you very much.
This is my final code, it works like a charm:
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
public class TripleDes3 {
private Cipher cipher = null;
private SecretKey key = null;
private byte[] bytes = null;
private IvParameterSpec iv = null;
public static void main(String[] args) throws Exception {
try {
String hexKey = "GD6GTT56HKY4HGF6FH3JG9J5";
//TripleDes3 encryptor = new TripleDes3(new String(Hex.decodeHex(hexKey.toCharArray())));
TripleDes3 encryptor = new TripleDes3(hexKey);
String original = "ABC";
System.out.println("Oringal: \"" + original + "\"");
String enc = encryptor.encrypt(original);
System.out.println("Encrypted: \"" + enc.toUpperCase() + "\"");
String dec = encryptor.decrypt(enc);
System.out.println("Decrypted: \"" + dec.toUpperCase() + "\"");
if (dec.equals(original)) {
System.out.println("Encryption ==> Decryption Successful");
}
} catch (Exception e) {
System.out.println("Error: " + e.toString());
}
}
public TripleDes3(String encryptionKey) throws GeneralSecurityException, DecoderException {
cipher = Cipher.getInstance("DESede/CBC/NoPadding");
try {
key = new SecretKeySpec(encryptionKey.getBytes("ISO8859_15"), "DESede");
iv = new IvParameterSpec(Hex.decodeHex("0123456789abcdef".toCharArray()));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String encrypt(String input) throws GeneralSecurityException, UnsupportedEncodingException {
bytes = input.getBytes("ISO8859_15");
bytes = Arrays.copyOf(bytes, ((bytes.length+7)/8)*8);
return new String(Hex.encodeHex(encryptB(bytes)));
}
public String decrypt(String input) throws GeneralSecurityException, DecoderException, UnsupportedEncodingException {
bytes = Hex.decodeHex(input.toCharArray());
String decrypted = new String(decryptB(bytes), "ISO8859_15");
if (decrypted.indexOf((char) 0) > 0) {
decrypted = decrypted.substring(0, decrypted.indexOf((char) 0));
}
return decrypted;
}
public byte[] encryptB(byte[] bytes) throws GeneralSecurityException {
cipher.init(Cipher.ENCRYPT_MODE, (Key) key, iv);
return cipher.doFinal(bytes);
}
public byte[] decryptB(byte[] bytes) throws GeneralSecurityException {
cipher.init(Cipher.DECRYPT_MODE, (Key) key, iv);
return cipher.doFinal(bytes);
}
}
And this is the Oracle Code:
DECLARE
v_data VARCHAR2(255);
v_retval RAW(255);
p_str VARCHAR2(255);
p_key RAW(255);
BEGIN
p_str := 'ABC';
p_key := utl_raw.cast_to_raw('GD6GTT56HKY4HGF6FH3JG9J5F62FT1');
v_data := RPAD(p_str, CEIL(LENGTH(p_str)/8)*8, CHR(0));
dbms_obfuscation_toolkit.DES3Encrypt
(
input => utl_raw.cast_to_raw(v_data),
key => p_key,
which => 1,
encrypted_data => v_retval
);
dbms_output.put_line(v_retval);
END;

java.lang.NoClassDefFoundError: org/apache/commons/codec/binary/Base64

Admin please don't mark it as duplicate read my question completely. I am encrypting and decrypting some text but while running in same file with main its running fine but when i call its encrypt and decrypt function from outside. Its giving an error at runtime. I am attaching the code.
package desede;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import security.SHA256Algo;
import shradhafinalwiddesign.UpdateFile;
import shradhafinalwiddesign.UserRegistration;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Simple TripleDES Encrypt/Decrypt Test
* sha1, utf-8, no padding
*
* uses commons-codec-1.6
* javac -cp :commons-codec-1.6.jar TripleDESTest.java
* java -cp :commons-codec-1.6.jar TripleDESTest
*/
public class TripleDesDemo {
public static void main(String[] args) throws Exception {
String text = "textToEncrypt";
UserRegistration user = new UserRegistration() ;
user.setlUsername("tarunv") ;
user.setAnswer("tommysdsfdsfsd") ;
user.setLastaccess("pets namesdfsfds") ;
user.setLpassword("computersdfdsfd") ;
String h1 = SHA256Algo.createHash(user.getlUsername()) ;
String h2 = SHA256Algo.createHash(user.getLpassword()) ;
String h3 = SHA256Algo.createHash(user.getAnswer()) ;
String hash1 = UpdateFile.modifyHashValue(h1).substring(0, 24) ;
String hash2 = UpdateFile.modifyHashValue(h2) ;
String hash3 = UpdateFile.modifyHashValue(h3) ;
System.out.println(" key1 : "+hash1.length()+" key2 : "+hash2.length()+" key3 : "+hash3.length());
byte[] arr = toByteArray(user) ;
byte[] codedtext = TripleDesDemo._encrypt(arr,"tarunvermacdac#gmail.com");
byte[] codedtext1 = TripleDesDemo._encrypt(codedtext,"tarun.spicyabc#gmail.com");
byte[] codedtext2 = TripleDesDemo._encrypt(codedtext1,"direct_tarun#yahoo.co.in");
writeSmallBinaryFile(codedtext2, "tarun.bat") ;
byte[] texttoDecrypt = readSmallBinaryFile("tarun.bat");
byte[] decodedtext = TripleDesDemo._decrypt(texttoDecrypt,"direct_tarun#yahoo.co.in");
byte[] decodedtext1 = TripleDesDemo._decrypt(decodedtext,"tarun.spicyabc#gmail.com");
byte[] decodedtext2 = TripleDesDemo._decrypt(decodedtext1,"tarunvermacdac#gmail.com");
System.out.println(codedtext + " ---> " + toObject(decodedtext2));
}
public static byte[] _encrypt(byte[] plainTextBytes, String secretKey) throws Exception {
byte[] keyBytes = secretKey.getBytes();
SecretKey key = new SecretKeySpec(keyBytes, "DESede");
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.ENCRYPT_MODE, key);
//byte[] plainTextBytes = message.getBytes("utf-8");
byte[] buf = cipher.doFinal(plainTextBytes);
byte [] base64Bytes = Base64.encodeBase64(buf);
//String base64EncryptedString = new String(base64Bytes);
return base64Bytes ;
}
public static byte[] _decrypt(byte[] encryptedText, String secretKey) throws Exception {
//byte[] message = Base64.decodeBase64(encryptedText);
byte[] message = Base64.decodeBase64(encryptedText);
byte[] keyBytes = secretKey.getBytes();
SecretKey key = new SecretKeySpec(keyBytes, "DESede");
Cipher decipher = Cipher.getInstance("DESede");
decipher.init(Cipher.DECRYPT_MODE, key);
byte[] plainText = decipher.doFinal(message);
return plainText ;
//return toObject(plainText);
}
public static byte[] toByteArray(UserRegistration obj) throws IOException {
byte[] bytes = null;
ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
try {
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
bytes = bos.toByteArray();
} finally {
if (oos != null) {
oos.close();
}
if (bos != null) {
bos.close();
}
}
return bytes;
}
public static UserRegistration toObject(byte[] bytes) throws IOException, ClassNotFoundException {
UserRegistration obj = null;
ByteArrayInputStream bis = null;
ObjectInputStream ois = null;
try {
bis = new ByteArrayInputStream(bytes);
ois = new ObjectInputStream(bis);
obj = (UserRegistration) ois.readObject();
} finally {
if (bis != null) {
bis.close();
}
if (ois != null) {
ois.close();
}
}
return obj;
}
public static byte[] readSmallBinaryFile(String aFileName) throws IOException {
Path path = Paths.get(aFileName);
return Files.readAllBytes(path);
}
public static void writeSmallBinaryFile(byte[] aBytes, String aFileName) throws IOException {
Path path = Paths.get(aFileName);
Files.write(path, aBytes); //creates, overwrites
}
}
The code is running fine with main but not when i call its function from other class which is in other package. Here is the exception.
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: org/apache/commons/codec/binary/Base64 at desede.TripleDesAlgo._encrypt(TripleDesAlgo.java:81)
And this is .classpath file
Thanks in advance for any help.
You are missing commons-codec.jar. Download it from http://commons.apache.org/proper/commons-codec/download_codec.cgi.
Then add it project build path. To do that right click the project, click Properties, click "Java Build Path", open "Library" tab, and click "Add External JARs...".
Or if you are using maven add dependency for
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.6</version>
</dependency>

GPG decryptor doesn't work properly

I'm trying to write gpg encryptor/decryptor (code below). In first step program encrypts "#data1\n#data2\n#data3\n" string and in next step decrypts the array of bytes that decryptor returns. But... why text from decryptor is not the same as "#data1\n#data2\n#data3\n" ? Where did I missed something ? Thanks for your help.
package tests.crypto;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.util.Iterator;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPPublicKeyRingCollection;
import org.bouncycastle.openpgp.PGPSecretKey;
import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.bouncycastle.openpgp.PGPSecretKeyRingCollection;
import org.bouncycastle.openpgp.PGPUtil;
import org.bouncycastle.openpgp.operator.bc.BcPBESecretKeyDecryptorBuilder;
import org.bouncycastle.openpgp.operator.bc.BcPGPDigestCalculatorProvider;
import org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyConverter;
import Decoder.BASE64Encoder;
public class GPGTest {
char[] pass = { 'p', 'a', 's', 's' };
public static void main(String[] args) throws Exception {
GPGTest gTest = new GPGTest();
gTest.setUpCipher();
}
public void setUpCipher() throws NoSuchAlgorithmException,
InvalidKeyException, IllegalBlockSizeException,
NoSuchProviderException, BadPaddingException,
NoSuchPaddingException {
System.out.println("--- setup cipher ---");
// public key
String publicKeyFilePath = "E:/Programs/Keys/GPG/Public/public.key";
File publicKeyFile = new File(publicKeyFilePath);
// secret key
String secretKeyFilePath = "E:/Programs/Keys/GPG/Secret/private.key";
File secretKeyFile = new File(secretKeyFilePath);
// security provider
Security.addProvider(new BouncyCastleProvider());
try {
// Read the public key
FileInputStream pubIn = new FileInputStream(publicKeyFile);
PGPPublicKey pgpPubKey = readPublicKey(pubIn);
PublicKey pubKey = new JcaPGPKeyConverter().getPublicKey(pgpPubKey);
// Read the private key
FileInputStream secretIn = new FileInputStream(secretKeyFile);
PGPSecretKey pgpSecretKey = readSecretKey(secretIn);
PGPPrivateKey pgpPrivKey = pgpSecretKey
.extractPrivateKey(new BcPBESecretKeyDecryptorBuilder(
new BcPGPDigestCalculatorProvider()).build(pass));
PrivateKey privKey = new JcaPGPKeyConverter()
.getPrivateKey(pgpPrivKey);
Cipher cipher = Cipher.getInstance("RSA");
// Encrypt data
byte[] encData = encryptData(cipher, pubKey, new String(
"#data1\n#data2\n#data3\n").getBytes());
String cryptString = new BASE64Encoder().encode(encData);
System.out.println("\n\nEncrypted data=" + cryptString);
// Decrypt data
byte[] decData = decryptData(cipher, privKey, encData);
String decryptString = new BASE64Encoder().encode(decData);
System.out.println("\n\nDecrypted data=" + decryptString);
} catch (Exception e) {
System.out.println("Setup cipher exception");
System.out.println(e.toString());
}
}
public byte[] encryptData(Cipher cipher, PublicKey pubKey, byte[] clearText) {
byte[] encryptedBytes = null;
try {
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
encryptedBytes = cipher.doFinal(clearText);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return encryptedBytes;
}
public byte[] decryptData(Cipher cipher, PrivateKey privKey, byte[] encryptedText) {
byte[] decryptedBytes = null;
try {
cipher.init(Cipher.DECRYPT_MODE, privKey);
decryptedBytes = cipher.doFinal(encryptedText);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return decryptedBytes;
}
private static PGPPublicKey readPublicKey(InputStream input) throws IOException, PGPException {
PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(input));
Iterator<?> keyRingIter = pgpPub.getKeyRings();
while (keyRingIter.hasNext()) {
PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIter.next();
Iterator<?> keyIter = keyRing.getPublicKeys();
while (keyIter.hasNext()) {
PGPPublicKey key = (PGPPublicKey) keyIter.next();
if (key.isEncryptionKey()) {
return key;
}
}
}
throw new IllegalArgumentException(
"Can't find encryption key in key ring.");
}
private static PGPSecretKey readSecretKey(InputStream input) throws IOException, PGPException {
PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(input));
Iterator<?> keyRingIter = pgpSec.getKeyRings();
while (keyRingIter.hasNext()) {
PGPSecretKeyRing keyRing = (PGPSecretKeyRing) keyRingIter.next();
Iterator<?> keyIter = keyRing.getSecretKeys();
while (keyIter.hasNext()) {
PGPSecretKey key = (PGPSecretKey) keyIter.next();
if (key.isSigningKey()) {
return key;
}
}
}
throw new IllegalArgumentException(
"Can't find signing key in key ring.");
}
}
They aren't the same because you are base-64 encoding the results of the decryption, rather than decoding it as text. Do this instead:
byte[] decData = decryptData(cipher, privKey, encData);
System.out.println("\n\nDecrypted data=" + new String(decData));
It is poor practice to use the platform default character encoding. Instead, you should convert text to bytes with with specific encoding, and use the same coding when decoding the bytes.
byte[] plaintext = "#data1\n#data2\n#data3\n").getBytes(StandardCharsets.UTF_8);
...
String recovered = new String(decData, StandardCharsets.UTF_8);

What is wrong with this code?

Thanx to evry one help me ..but still there is 2 problem after editing the code
import java.io.*;
import java.math.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class RCC4 {
public RCC4(){}
public static void main(String[] args)throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException{
String test = "testisperfect";
System.out.println(RCC4.keyGet());
byte b[] = RCC4.keyGet().getBytes();
byte plain[] = test.getBytes();
**byte c[] = RCC4.encrypt(plain,b);**
**byte p[] = RCC4.decrypt(c,b);**
**System.out.println(new String(c)) ;
System.out.println(new String(p));**
}
public static byte[] encrypt(byte[] plaintext,byte[] keyBytes)
{
byte[] e = null;
try
{
Key key = new SecretKeySpec(keyBytes,"RC4");
Cipher enCipher = Cipher.getInstance("RC4");
**enCipher.init(Cipher.ENCRYPT_MODE ,key);**
e = enCipher.doFinal(plaintext);
}
catch(Exception ex)
{
ex.printStackTrace();
}
return e;
}
public static byte[] decrypt(byte[] ciphertext,byte[] keyBytes)
{
byte de[] = null;
try
{
Key key = new SecretKeySpec(keyBytes,"RC4");
Cipher deCipher = Cipher.getInstance("RC4");
**deCipher.init(Cipher.DECRYPT_MODE, key);**
de = deCipher.doFinal(ciphertext);
}
catch(Exception e)
{
e.printStackTrace();
}
return de;
}
public static Key getKey()
{
Key key = null;
try
{
SecureRandom sr = new SecureRandom();
KeyGenerator kg = KeyGenerator.getInstance("RC4");
kg.init(128,sr);
key = kg.generateKey();
}catch(Exception e)
{
e.printStackTrace();
}
return key;
}
public static String keyGet()
{
Key k = RCC4.getKey();
byte[] b = k.getEncoded();
BigInteger big = new BigInteger(b);
String s = big.toString();
return s;
}
}
When I press "Build file" it says process completed but at running file a message says
112670544188765215715791498302542646231
java.security.InvalidKeyException: Illegal key size or default parameters
at RCC4.encrypt(RCC4.java:37)
at RCC4.main(RCC4.java:23)
java.security.InvalidKeyException: Illegal key size or default parameters
at RCC4.decrypt(RCC4.java:53)
at RCC4.main(RCC4.java:24)
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.<init>(String.java:479)
at RCC4.main(RCC4.java:26)
Process completed.
These Lines are indicated as *
Answer to original question:
Key key = new SecretKeySpec(byte[]keyBytes,RC4);
should be
Key key = new SecretKeySpec(keyBytes, "RC4");
Also,
deCipher.init(Cipher.WHATEVER, keyBytes);
should be
deCipher.init(Cipher.WHATEVER, key);
Then it compiles, however there's still some issue with the application logic. That's up to you again :).
Answer to new question:
The problem was the unneeded usage of SecretKeySpec. Somewhere between getKey(), keyGet() all the byte[] games and SecretKeySpec it got wrong somehow. I didn't have the patience to track it, so I just deleted it and made the code somewhat more readable to make sure I didn't miss anything. I think you will still understand it since it still is basically your code and it is much simpler now.
import java.security.*;
import javax.crypto.*;
public class RCC4 {
public static void main(String[] args) throws Exception {
String plain = "testisperfect";
Key key = RCC4.getKey();
String encrypted = RCC4.encrypt(plain, key);
String decrypted = RCC4.decrypt(encrypted, key);
System.out.println(encrypted);
System.out.println(decrypted);
}
private static String rc4(String plaintext, int mode, Key key) throws Exception {
Cipher cipher = Cipher.getInstance("RC4");
cipher.init(mode, key);
return new String(cipher.doFinal(plaintext.getBytes()));
}
public static String encrypt(String plaintext, Key key) throws Exception {
return rc4(plaintext, Cipher.ENCRYPT_MODE, key);
}
public static String decrypt(String ciphertext, Key key) throws Exception {
return rc4(ciphertext, Cipher.DECRYPT_MODE, key);
}
public static Key getKey() throws Exception {
KeyGenerator kg = KeyGenerator.getInstance("RC4");
SecureRandom sr = new SecureRandom();
kg.init(128, sr);
return kg.generateKey();
}
}
You need import SecretKeySpec which is under package javax.crypto.spec.
You're not calling the method correctly in that you're passing in the parameter type with the parameter. Parameter types are only shown when declaring a method, not when calling the method.
In other words, it's not
Key key = new SecretKeySpec(byte[] keyBytes, RC4);
it's instead
Key key = new SecretKeySpec(keyBytes, RC4);
You will of course need to have a keyBytes variable declared and initialized before trying to pass it into the parameter of this method.
package test;
import java.io.*;
import java.math.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class RCC4 {
public RCC4() {
}
public static void main(String[] args) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, IOException {
String test = "testisperfect";
System.out.println(RCC4.keyGet());
byte b[] = RCC4.keyGet().getBytes();
byte plain[] = test.getBytes();
byte c[] = RCC4.encrypt(plain, b);
byte p[] = RCC4.decrypt(c, b);
System.out.println(new String(c));
System.out.println(new String(p));
}
public static byte[] encrypt(byte[] plaintext, byte[] keyBytes) {
byte[] e = null;
try {
Key key = new SecretKeySpec(keyBytes, "RC4");
Cipher enCipher = Cipher.getInstance("RC4");
enCipher.init(Cipher.ENCRYPT_MODE, key);
e = enCipher.doFinal(plaintext);
} catch (Exception ex) {
ex.printStackTrace();
}
return e;
}
public static byte[] decrypt(byte[] ciphertext, byte[] keyBytes) {
byte de[] = null;
try {
Key key = new SecretKeySpec(keyBytes, "RC4");
Cipher deCipher = Cipher.getInstance("RC4");
deCipher.init(Cipher.DECRYPT_MODE, RCC4.getKey());
de = deCipher.doFinal(ciphertext);
} catch (Exception e) {
e.printStackTrace();
}
return de;
}
public static Key getKey() {
Key key = null;
try {
SecureRandom sr = new SecureRandom();
KeyGenerator kg = KeyGenerator.getInstance("RC4");
kg.init(128, sr);
key = kg.generateKey();
} catch (Exception e) {
e.printStackTrace();
}
return key;
}
public static String keyGet() {
Key k = RCC4.getKey();
byte[] b = k.getEncoded();
BigInteger big = new BigInteger(b);
String s = big.toString();
return s;
}
}

Categories