DesEncrypter !
Hi folks,
I need help with passing a string from another method to the DesEncrypter class.
here's what my code looks like:
import javax.swing.*;
import java.math.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
public class MenuE
JTextArea outputArea = new JTextArea(25,25);
JScrollPane scroller = new JScrollPane(outputArea);
public MenuE()
StringBuffer output = new StringBuffer();
String CK;
String powerString = JOptionPane.showInputDialog(null, "Enter receiver's public key, e.", "Public Key, e", JOptionPane.QUESTION_MESSAGE);
String modString = JOptionPane.showInputDialog(null, "Enter receiver's public key, N", "Public Key,N", JOptionPane.QUESTION_MESSAGE);
String output3 = " n = " + powerString + " e = " + modString;
outputArea.setText(output3);
outputArea.setEditable(false);
JOptionPane.showMessageDialog(null, scroller);
outputArea.setText(output3);
The problem here is that how can i pass "output3" to DesEncrypter?
import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class DesEncrypter {
Cipher ecipher;
Cipher dcipher;
DesEncrypter(SecretKey key) {
try {
ecipher = Cipher.getInstance("DES");
dcipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
} catch (javax.crypto.NoSuchPaddingException e) {
} catch (java.security.NoSuchAlgorithmException e) {
} catch (java.security.InvalidKeyException e) {
public String encrypt(String str) {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
return null;
public String decrypt(String str) {
try {
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
// Decrypt
byte[] utf8 = dcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
return null;
public static void main(String args[]) {
try{
// Generate a temporary key. In practice, you would save this key.
// See also e464 Encrypting with DES Using a Pass Phrase.
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
// Create encrypter/decrypter class
DesEncrypter encrypter = new DesEncrypter(key);
// Encrypt
String encrypted = encrypter.encrypt(output3);
System.out.println(encrypted);
/**outputArea.setText(encrypted);
outputArea.setEditable(false);
JOptionPane.showMessageDialog(null, scroller);
outputArea.setText(encrypted);**/
// Decrypt
String decrypted = encrypter.decrypt(encrypted);
System.out.println(decrypted);
} catch (Exception e) {
Thanks a lot !
Hi Sabre150,
i think i will send you all of my source code and let you see...compile everything and run Message.java..to generate the d, run primemenu.java..
Convert.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
public class Convert{
String s;
String a;
StringBuffer output = new StringBuffer();
public Convert()
public Convert(String s)
StringBuffer sb = new StringBuffer();
sb = new StringBuffer(s);
int i;
i = sb.length();
i = i - 1;
for(int x = 0; x<=i; x++)
switch (sb.charAt(x))
case '0' : a = "01";
break;
case '1' : a = "01";
break;
case '2' : a = "02";
break;
case '3' : a = "03";
break;
case '4' : a = "04";
break;
case '5' : a = "05";
break;
case '6' : a = "06";
break;
case '7' : a = "07";
break;
case '8' : a = "08";
break;
case '9' : a = "09";
break;
case 'a' : a = "10";
break;
case 'b': a = "11";
break;
case 'c' : a = "12";
break;
case 'd' : a = "13";
break;
case 'e' : a = "14";
break;
case 'f' : a = "15";
break;
case 'g' : a = "16";
break;
case 'h' : a = "17";
break;
case 'i' : a = "18";
break;
case 'j' : a = "19";
break;
case 'k' : a = "20";
break;
case 'l': a = "21";
break;
case 'm' : a = "22";
break;
case 'n' : a = "23";
break;
case 'o' : a = "24";
break;
case 'p' : a = "25";
break;
case 'q' : a = "26";
break;
case 'r' : a = "27";
break;
case 's' : a = "28";
break;
case 't' : a = "29";
break;
case 'u' : a = "30";
break;
case 'v' : a = "31";
break;
case 'w' : a = "32";
break;
case 'x' : a = "33";
break;
case 'y' : a = "34";
break;
case 'z' : a = "35";
break;
case 'A' : a = "36";
break;
case 'B' : a = "37";
break;
case 'C' : a = "38";
break;
case 'D' : a = "39";
break;
case 'E' : a = "40";
break;
case 'F' : a = "41";
break;
case 'G' : a = "42";
break;
case 'H' : a = "43";
break;
case 'I' : a = "44";
break;
case 'J' : a = "45";
break;
case 'K' : a = "46";
break;
case 'L' : a = "47";
break;
case 'M' : a = "48";
break;
case 'N' : a = "49";
break;
case 'O' : a = "50";
break;
case 'P' : a = "51";
break;
case 'Q' : a = "52";
break;
case 'R' : a = "53";
break;
case 'S' : a = "54";
break;
case 'T' : a = "55";
break;
case 'U' : a = "56";
break;
case 'V' : a = "57";
break;
case 'W' : a = "58";
break;
case 'X' : a = "59";
break;
case 'Y' : a = "60";
break;
case 'Z' : a = "61";
break;
case '`' : a = "62";
break;
case '~' : a = "63";
break;
case '!' : a = "64";
break;
case '@' : a = "65";
break;
case '#' : a = "66";
break;
case '$' : a = "67";
break;
case '%': a = "68";
break;
case '^' : a = "69";
break;
case '&' : a = "70";
break;
case '*' : a = "71";
break;
case '(' : a = "72";
break;
case ')' : a = "73";
break;
case '-' : a = "74";
break;
case '_' : a = "75";
break;
case '=' : a = "76";
break;
case '+' : a = "77";
break;
case '[' : a = "78";
break;
case ']' : a = "79";
break;
case '{' : a = "80";
break;
case '}' : a = "81";
break;
case '\\' : a = "82";
break;
case '|' : a = "83";
break;
case ';' : a = "84";
break;
case ':' : a = "85";
break;
case '\'' : a = "86";
break;
case '"' : a = "87";
break;
case ',' : a = "88";
break;
case '.' : a = "89";
break;
case '<' : a = "90";
break;
case '>' : a = "91";
break;
case '?' : a = "92";
break;
case '/' : a = "93";
break;
default : a = "94";
output = output.append(a);
s = output.toString();
JOptionPane.showMessageDialog(null,s,"Encrypted Message", JOptionPane.INFORMATION_MESSAGE);
MenuC m = new MenuC(s);
//MenuT t = new MenuT(s);
Decrypt.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
public class Decrypt extends JFrame{
String t;
String a;
StringBuffer output = new StringBuffer();
JTextArea outputArea = new JTextArea(30,30);
JScrollPane scroller = new JScrollPane(outputArea);
public Decrypt()
public Decrypt(String DTxt)
StringBuffer sb1 = new StringBuffer();
sb1 = new StringBuffer(DTxt);
String u;
String q;
//JOptionPane.showMessageDialog(null, sb1, "Your decrypted msg", JOptionPane.INFORMATION_MESSAGE);
int i;
i = sb1.length();
//JOptionPane.showMessageDialog(null ,i,"Length of your message", JOptionPane.INFORMATION_MESSAGE);
i = i - 1;
for(int x=0; x<=i; x++)
for(int y=2; y<=i+1 ; y++)
String z = sb1.substring(x,y);
u = z.toString();
int v = Integer.parseInt(u);
if (u == "08")
v = 8;
else if (u == "09")
v = 9;
else
switch (v)
case 00 : a = "0";
break;
case 01 : a = "1";
break;
case 02 : a = "2";
break;
case 03 : a = "3";
break;
case 04 : a = "4";
break;
case 05 : a = "5";
break;
case 06 : a = "6";
break;
case 07 : a = "7";
break;
case 8 : a = "8";
break;
case 9 : a = "9";
break;
case 10 : a = "a";
break;
case 11: a = "b";
break;
case 12 : a = "c";
break;
case 13 : a = "d";
break;
case 14 : a = "e";
break;
case 15 : a = "f";
break;
case 16 : a = "g";
break;
case 17 : a = "h";
break;
case 18 : a = "i";
break;
case 19 : a = "j";
break;
case 20 : a = "k";
break;
case 21: a = "l";
break;
case 22 : a = "m";
break;
case 23 : a = "n";
break;
case 24 : a = "o";
break;
case 25 : a = "p";
break;
case 26 : a = "q";
break;
case 27 : a = "r";
break;
case 28 : a = "s";
break;
case 29 : a = "t";
break;
case 30 : a = "u";
break;
case 31 : a = "v";
break;
case 32 : a = "w";
break;
case 33 : a = "x";
break;
case 34 : a = "y";
break;
case 35 : a = "z";
break;
case 36 : a = "A";
break;
case 37 : a = "B";
break;
case 38 : a = "C";
break;
case 39 : a = "D";
break;
case 40 : a = "E";
break;
case 41 : a = "F";
break;
case 42 : a = "G";
break;
case 43 : a = "H";
break;
case 44 : a = "I";
break;
case 45 : a = "J";
break;
case 46 : a = "K";
break;
case 47 : a = "L";
break;
case 48 : a = "M";
break;
case 49 : a = "N";
break;
case 50 : a = "O";
break;
case 51 : a = "P";
break;
case 52 : a = "Q";
break;
case 53 : a = "R";
break;
case 54 : a = "S";
break;
case 55 : a = "T";
break;
case 56 : a = "U";
break;
case 57 : a = "V";
break;
case 58 : a = "W";
break;
case 59 : a = "X";
break;
case 60 : a = "Y";
break;
case 61 : a = "Z";
break;
case 62 : a = "`";
break;
case 63 : a = "~";
break;
case 64 : a = "!";
break;
case 65 : a = "@";
break;
case 66 : a = "#";
break;
case 67 : a = "$";
break;
case 68: a = "%";
break;
case 69 : a = "^";
break;
case 70 : a = "&";
break;
case 71 : a = "*";
break;
case 72 : a = "(";
break;
case 73 : a = ")";
break;
case 74 : a = "-";
break;
case 75 : a = "_";
break;
case 76 : a = "=";
break;
case 77 : a = "+";
break;
case 78 : a = "[";
break;
case 79 : a = "]";
break;
case 80 : a = "{";
break;
case 81 : a = "}";
break;
case 82 : a = "\\";
break;
case 83 : a = "|";
break;
case 84 : a = ";";
break;
case 85 : a = ":";
break;
case 86 : a = "\'";
break;
case 87 : a = "\"";
break;
case 88: a = ",";
break;
case 89 : a = ".";
break;
case 90 : a = "<";
break;
case 91 : a = ">";
break;
case 92 : a = "?";
break;
case 93 : a = "/";
break;
case 94 : a = " ";
break;
default : a = "";
x = x + 2;
y = y + 1;
output = output.append(a);
q = output.toString();
String text = " This is your message = \n " + q;
outputArea.setText(text);
outputArea.setEditable(false);
JOptionPane.showMessageDialog(null, scroller);
outputArea.setText(text);
GeneratePrime.java
import java.awt.*;
import java.applet.*;
import java.math.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class GeneratePrime extends Applet implements ActionListener {
TextField startfield, outfield;
Button startButton;
// layout
public void init() {
setLayout(new GridBagLayout()); GridBagConstraints c;
c = new GridBagConstraints();
c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.WEST;
add(new Label(getParameter("startAt") + ":"), c);
c = new GridBagConstraints();
c.gridx = 1; c.gridy = 0; c.anchor = GridBagConstraints.WEST;
add(startfield = new TextField("1000000000",40), c);
c = new GridBagConstraints();
c.gridx = 0; c.gridy = 1; c.anchor = GridBagConstraints.WEST;
c.gridwidth = 2;
add(startButton = new Button(getParameter("startSearch")), c);
c = new GridBagConstraints();
c.gridx = 0; c.gridy = 2; c.anchor = GridBagConstraints.WEST;
add(new Label(getParameter("nextPrime") + "="), c);
c = new GridBagConstraints();
c.gridx = 1; c.gridy = 2; c.anchor = GridBagConstraints.WEST;
add(outfield = new TextField(40), c);
outfield.setEditable(false);
// register listeners
startfield.addActionListener(this);
startButton.addActionListener(this);
// listen, dispatch
public void actionPerformed(ActionEvent e) {
search();
// search for next prime
public void search() {
String input = startfield.getText();
BigInteger n = new BigInteger("0");
BigInteger one = new BigInteger("1");
BigInteger two = new BigInteger("2");
boolean ok = true;
try {
BigInteger temp = new BigInteger(input);
n = temp;
catch (NumberFormatException ex) {
outfield.setText(getParameter("invalid"));
ok = false;
if (ok) {
if ((n.signum() <= 0) | (n.equals(one))) { // n < 2 => n := 2
n = two;
if ((n.getLowestSetBit() != 0) & (! n.equals(two))) {
n = n.add(one); // even -> odd (except for 2)
while (! n.isProbablePrime(7)) {
n = n.add(two);
// System.out.println(n);
outfield.setText(""+n);
return;
Kira.java
import javax.swing.*;
import java.math.*;
public class Kira
BigInteger No;
BigInteger Mod;
BigInteger Power;
public Kira()
public Kira(BigInteger No, BigInteger Power, BigInteger Mod)
this.No = No;
this.Power = Power;
this.Mod = Mod;
public BigInteger getNo()
return No;
public void setNo(BigInteger No)
this.No = No;
public BigInteger getPower()
return Power;
public void setPower(BigInteger Power)
this.Power = Power;
public BigInteger getMod()
return Mod;
public void setMod(BigInteger Mod)
this.Mod = Mod;
public BigInteger find_CT()
return No.modPow(Power,Mod);
Kira3.java
import javax.swing.*;
import java.math.*;
public class Kira3
BigInteger CText;
BigInteger D;
BigInteger N;
BigInteger DText;
BigInteger x;
public Kira3()
public Kira3(BigInteger CText, BigInteger N, BigInteger D)
this.CText = CText;
this.D = D;
this.N = N;
public BigInteger getCText()
return CText;
public void setCText(BigInteger CText)
this.CText = CText;
public BigInteger getN()
return N;
public void setN(BigInteger N)
this.N = N;
public BigInteger getD()
return D;
public void setD(BigInteger D)
this.D = D;
public BigInteger DText()
return CText.modPow(D,N);
MenuC.java
import javax.swing.*;
import java.math.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
public class MenuC
JTextArea outputArea = new JTextArea(25,25);
JScrollPane scroller = new JScrollPane(outputArea);
public MenuC()
public MenuC(String s)
StringBuffer output = new StringBuffer();
String CT;
String powerString = JOptionPane.showInputDialog(null, "Enter receiver's public key, e.", "Public Key, e", JOptionPane.QUESTION_MESSAGE);
BigInteger Power = new BigInteger(powerString);
String modString = JOptionPane.showInputDialog(null, "Enter receiver's public key, N", "Public Key,N", JOptionPane.QUESTION_MESSAGE);
int a = modString.length();
BigInteger Mod = new BigInteger(modString);
StringBuilder sb = new StringBuilder(s);
int i;
i = sb.length();
i = i - 1;
String t;
for(int x=0; x<=i; x++)
for(int y=2; y<=i+1 ; y++)
String z = sb.substring(x,y);
BigInteger No = new BigInteger(z);
Kira k = new Kira(No,Power,Mod);
t = k.find_CT() + "";
int j = t.length();
int m;
int n;
if ( j != a)
do
t = "0" + t;
m = t.length();
while( m < a);
else
t = t;
output = output.append(t);
x = x + 2;
y = y + 1;
CT = output.toString();
String output1 = "Cipher Text = " + CT;
outputArea.setText(output1);
outputArea.setEditable(false);
JOptionPane.showMessageDialog(null, scroller);
outputArea.setText(output1);
//JOptionPane.showMessageDialog(null,output1, "Cipher Text", JOptionPane.INFORMATION_MESSAGE);
MenuD.java
import javax.swing.*;
import java.math.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
public class MenuD extends JFrame
public MenuD()
public MenuD(String s)
StringBuffer DT = new StringBuffer();
String output = " This is your Cipher Text " + s ;
JOptionPane.showMessageDialog(null,output,"Cipher Text", JOptionPane.INFORMATION_MESSAGE);
String pk_N = JOptionPane.showInputDialog(null, "Enter public key, N.", "Public Key, e", JOptionPane.QUESTION_MESSAGE);
int j = pk_N.length();
BigInteger N = new BigInteger(pk_N);
String sk_D = JOptionPane.showInputDialog(null, "Enter Secret Key, D", "Secret Key,D", JOptionPane.QUESTION_MESSAGE);
BigInteger D = new BigInteger(sk_D);
StringBuffer CT = new StringBuffer(s);
int i = CT.length();
i = i - 1;
for(int x=0; x<=i; x++)
for(int y=j; y<=i+1 ; y++)
String a = CT.substring(x,y);
BigInteger CText = new BigInteger(a);
Kira3 k3 = new Kira3(CText,N,D);
String DText = ""+ k3.DText();
DT = DT.append(DText);
x = x + j;
y = y + j - 1;
String DTxt = DT.toString();
JOptionPane.showMessageDialog(null,DTxt, "DT", JOptionPane.INFORMATION_MESSAGE);
Decrypt d = new Decrypt(DTxt);
Message.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
public class Message extends JFrame implements ActionListener
JMenu jmnFile = new JMenu("File");
JMenuItem jmiOpen = new JMenuItem("Open");
JMenuItem jmiSave = new JMenuItem("Save");
JMenuItem jmiEncrypt = new JMenuItem("Encrypt");
JMenuItem jmiDecrypt = new JMenuItem("Decrypt");
JMenuItem jmiSend = new JMenuItem("Send");
JMenuItem jmiReceive = new JMenuItem("Receive");
JMenuItem jmiExit = new JMenuItem("Exit");
JButton jbtEncrypt = new JButton("Encrypt");
JButton jbtDecrypt = new JButton("Decrypt");
JButton jbtSend = new JButton("Send");
JButton jbtReceive = new JButton("Receive");
JButton jbtExit = new JButton ("Exit");
JTextArea jtaMsg = new JTextArea(1,1);
JFileChooser jfcDialog = new JFileChooser();
Message()
Container frame = getContentPane();
frame.setLayout(new BorderLayout(2,2));
frame.setBackground(Color.lightGray);
JMenuBar jmb = new JMenuBar();
setJMenuBar(jmb);
jmb.add(jmnFile);
jmnFile.add(jmiOpen);
jmnFile.add(jmiSave);
jmnFile.addSeparator();
jmnFile.add(jmiEncrypt);
jmnFile.add(jmiDecrypt);
jmnFile.addSeparator();
jmnFile.add(jmiExit);
jfcDialog.setCurrentDirectory(new File("."));
JPanel msgArea = new JPanel();
msgArea.setLayout(new BorderLayout());
msgArea.add(jtaMsg,BorderLayout.CENTER);
JPanel buttonArea = new JPanel();
buttonArea.setLayout(new GridLayout(1,5));
buttonArea.add(jbtEncrypt);
buttonArea.add(jbtDecrypt);
buttonArea.add(jbtExit);
frame.add(msgArea,BorderLayout.CENTER);
frame.add(buttonArea,BorderLayout.SOUTH);
jmiOpen.addActionListener(this);
jmiSave.addActionListener(this);
jmiEncrypt.addActionListener(this);
jmiDecrypt.addActionListener(this);
jmiExit.addActionListener(this);
jbtEncrypt.addActionListener(this);
jbtDecrypt.addActionListener(this);
jbtExit.addActionListener(this);
public void actionPerformed(ActionEvent e)
if(e.getSource()==jmiOpen)
if(jfcDialog.showOpenDialog(this)==JFileChooser.APPROVE_OPTION)
File fileName=jfcDialog.getSelectedFile();
try
BufferedInputStream fin = new BufferedInputStream(
new FileInputStream(fileName));
byte b[]=new byte[fin.available()];
fin.read(b,0,b.length);
jtaMsg.append(new String(b,0,b.length));
fin.close();
catch(IOException ex)
JOptionPane.showMessageDialog(this,"Error : " + ex.getMessage(),
"ERROR",JOptionPane.WARNING_MESSAGE);
if(e.getSource()==jmiSave)
if(jfcDialog.showSaveDialog(this)==JFileChooser.APPROVE_OPTION)
File fileName=jfcDialog.getSelectedFile();
try
BufferedOutputStream fout = new BufferedOutputStream(
new FileOutputStream(fileName));
byte b[]=(jtaMsg.getText()).getBytes();
fout.write(b,0,b.length);
fout.close();
catch(IOException ex)
JOptionPane.showMessageDialog(this,"Error : " + ex.getMessage(),
"Error",JOptionPane.WARNING_MESSAGE);
if(e.getSource()==jmiEncrypt || e.getSource()==jbtEncrypt)
String s = jtaMsg.getText();
Convert c = new Convert(s);
if(e.getSource()==jmiDecrypt || e.getSource()==jbtDecrypt)
String s = jtaMsg.getText();
MenuD d = new MenuD(s);
if(e.getSource()==jmiExit || e.getSource()==jbtExit)
System.exit(1);
public static void main(String args[])
Message frame = new Message();
frame.setTitle("Message");
frame.setSize(600,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
Dimension Screen = Toolkit.getDefaultToolkit().getScreenSize();
int W_Screen = Screen.width;
int L_Screen = Screen.height;
Dimension frameSize = frame.getSize();
int x = (W_Screen - Screen.width)/2;
int y = (L_Screen - Screen.height)/2;
frame.setLocation(x,y);
PrimeMenu.java
import javax.swing.*;
import java.math.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
public class PrimeMenu {
public static void main(String args[])
JOptionPane.showMessageDialog(null,"This program will calculate secret key, D.","Secret Key, D",
JOptionPane.INFORMATION_MESSAGE);
String P = JOptionPane.showInputDialog(null, "Please enter, P", "P",
JOptionPane.QUESTION_MESSAGE);
BigInteger p = new BigInteger(P);
String Q = JOptionPane.showInputDialog(null, "Please enter, Q", "Q",
JOptionPane.QUESTION_MESSAGE);
BigInteger q = new BigInteger(Q);
String E = JOptionPane.showInputDialog(null, "Please enter Public Key, e", "Public Key, e",
JOptionPane.QUESTION_MESSAGE);
BigInteger e = new BigInteger(E);
BigInteger mul = new BigInteger("0");
mul = p.multiply(q);
JOptionPane.showMessageDialog(null,mul, "PQ", JOptionPane.INFORMATION_MESSAGE);
BigInteger MI = new BigInteger("0");
BigInteger r = new BigInteger("0");
r = p.subtract( new BigInteger("1") ) ;
r = r.multiply( q.subtract(new BigInteger("1") ) ) ;
MI = e.modInverse(r);
JOptionPane.showMessageDialog(null,MI, "Secret Key,D", JOptionPane.INFORMATION_MESSAGE);
}
Similar Messages
-
Date field encryption using Dbms_Obfuscation_Toolkit.DESENCRYPT
Hi,
I need to encrypt the date field in the table using Dbms_Obfuscation_Toolkit.DESENCRYPT .
This is an table is an existing table and is accessed by many interfaces, so we cannot change the column type of this date field.
Is there a possibility of encrypting the date field and store it in the same column (DATE type).
And access this using Dbms_Obfuscation_Toolkit.DESDECRYPT.
We are using Oracle 11.2.0.2.0.
Thanks in advance.
Agathya>
Is there a possibility of encrypting the date field and store it in the same column (DATE type).
>
No - the DESENCRYPT procedure returns a RAW value which can't be stored in a DATE column.
See DESENCRYPT Procedures and Functions in Chapter 82 (DBMS_OBFUSCATION_TOOLKIT) of the PL/SQl Packages and Types Doc
http://docs.oracle.com/cd/B28359_01/appdev.111/b28419/d_obtool.htm#i997215
For what you want to do just use the ENCRYPT option of the CREATE TABLE or ALTER TABLE statements.
See Using Transparent Data Encryption in the Advanced Security Admin Guide
http://docs.oracle.com/cd/B28359_01/network.111/b28530/asotrans.htm#BABJJAIG
>
3.2 Using Transparent Data Encryption
The following steps discuss using transparent data encryption:
•Enabling Transparent Data Encryption
•Setting and Resetting theMaster Encryption Key
•Opening the Encrypted Wallet
•Creating Tables with Encrypted Columns
•Encrypting Columns in Existing Tables
•Creating an Index on an Encrypted Column
•Adding or Removing Salt from an Encrypted Column
•Changing the Encryption Key or Algorithm for Tables Containing Encrypted Columns
>
Section 3.2.5.2 Encrypting an Unencrypted Column shows the ALTER TABLE statement for encrypting an existing column - this would leave the column as a DATE and you would work with it normally
>
3.2.5.2 Encrypting an Unencrypted Column
To encrypt an unencrypted column, use the ALTER TABLE MODIFY command, specifying the unencrypted column with the ENCRYPT clause. Example 3-7 encrypts the first_name column in the employee table.
Example 3-7 Encrypting an Unencrypted Column
ALTER TABLE employee MODIFY (first_name ENCRYPT);
The first_name column is encrypted with the default AES192 algorithm. Salt is added to the data, by default.
You can choose to encrypt the column using a different algorithm. You can also specify NO SALT, if you wish to index the column. -
DBMS_OBFUSCATION_TOOLKIT.DESENCRYPT Problem
I am trying to encrypt and deencrypt a column in one of my table.I use oracle version 8.1.7.when i compile my procedure with the procedure DBMS_OBFUSCATION_TOOLKIT.DESENCRYPT is gets created and no errors.When i try to run the procedure i get the following error:
ERROR at line 1:
ORA-06521: PL/SQL: Error mapping function
ORA-06512: at "DIEBOLD.DBMS_OBFUSCATION_TOOLKIT_FFI", line 0
ORA-06512: at "DIEBOLD.DBMS_OBFUSCATION_TOOLKIT", line 15
Since this package uses libraries do i need to do anything different?
Thanks in advance.It doesn't help. My problem is that the following code result different in Oracle 8i and Oracle 10g.
declare
-- Local variables here
i integer;
text RAW(128) := UTL_RAW.CAST_TO_RAW('00000000');
key RAW(128) := UTL_RAW.CAST_TO_RAW('01234567');
enc_data RAW(128);
begin
-- Test statements here
DBMS_OBFUSCATION_TOOLKIT.desencrypt (input => text,
KEY => key,
encrypted_data => enc_data
end; -
DESEncrypt Function don't work with any charakter
Hi!
I wrote a function to encrypt data using the DESEncrypt function:
Create or replace function verschluessel (input_str varchar2,key_string varchar2) return RAW as
input_string varchar2 (4000);
encrypted_string varchar2(4000);
raw_input RAW(4000);
raw_key RAW(128) := UTL_RAW.CAST_TO_RAW(key_string);
encrypted_raw RAW(4000);
test smallint := 8 - mod(length(input_str),8);
ergaenz varchar2(7);
begin
loop
if test = 0 OR test = 8 then
exit;
end if;
ergaenz := ergaenz || ' ';
test := test - 1;
end loop;
input_string := input_str || ergaenz;
raw_input := UTL_RAW.CAST_TO_RAW(input_string);
dbms_obfuscation_toolkit.DESEncrypt(input => raw_input,key => raw_key,
encrypted_data => encrypted_raw);
return encrypted_raw;
end verschluessel;
The problem is, if the input_string contains german umlaute or special french characters, the error message ORA-28232 "Invalid input size for Obfuscation toolkit" appears.
How can I solve that ?
Thanx Andri.Resolving issues with Touch ID
Make sure that you're using the latest version of iOS.
Make sure that your fingers and the Home button are clean and dry.*
Note: Cover the Home button completely. Don't tap too quickly, don't press down hard, and don't move your finger while Touch ID is scanning. Make sure that your finger touches the metal ring around the Home button.
If you're using a protective case or screen protector, it must leave the Home button and the surrounding ring completely unobscured. If it doesn't, remove the case or screen protector and try again.
Tap Settings > Touch ID & Passcode and verify that:
iPhone Unlock or iTunes & App Store is on.
You enrolled one or more fingerprints.
Try enrolling a different finger.
If you can't enroll any of your fingers, take your iPhone 5s to an Apple Retail Store, Apple Authorized Service Provider, or contact AppleCare for further assistance.
* Moisture, lotions, sweat, oils, cuts, or dry skin might affect fingerprint recognition. Certain activities can also temporarily affect fingerprint recognition, including exercising, showering, swimming, cooking, or other conditions or changes that affect your fingerprint. -
Implement DESEncrypt and DESDecrypt in Java
Hello!
I'd like to reimplement the methods DESEncrypt and DESDecrypt, which are part of the dbms_obfuscation_toolkit, in Java, in order to be able to use EJBs mapped to tables containing encrypted data. The problem is that I can't find all the implementation details of these functions:
DES is the algorithm: this is OK.
Which chaining mode is used? I have tried ECB, and it doesn't work as soon as the input is more than 8-bytes long.
I also tried CBC and the other ones, but I need an IV to use them, and I don't know what IV is used by DESEncrypt and DESDecrypt.
Which padding mode is used? NoPadding? PKCS5Padding?
The only thing that works is DES/ECB/NoPadding, for inputs less than 8 bytes long. For longer inputs, I need more information.
JB.Thanks for your help. I forgot to mention that I was using Oracle 8.1.7.
Anyway, after more experiments, I finally managed to find out what the exact algorithm parameters are:
Algorithm: DES
Chaining mode: CBC
Padding mode: NoPadding
IV: byte array containing only zeros (8 bytes long)
JB. -
Good evening,
I would like someone to help me with this problem. I have a Macbook Pro 13 " i5 . The problem started when I installed the operating system " Yosemite " and began to slowly get my computer, so I decided to disable " FileVault " and began decrypted my hard drive, and load stayed says " calculating time remaining "and I left 2 prendidao days and not moving , I do not know what to do, my mac is too slow , I need help , as I solve this problem due to Yosemite.Unless you are willing to erase the drive, all you can do is wait.
-
If I know the max length of input data, can I know the max length of encrypted output ?
(e.g. for storing password in encrypted format, i should know the size of field, if max length of password is known )The toolkit needs data in 8 byte multiples.
That means if your password is varchar2(30) use raw(32) to store the encrypted passwords. -
How to implement logger in this ftp server
I have written a FTP Server that is used by the clients to upload xml over to the server.
Currently it is using a console and it is printing stuff out on a console.
I have tried a lot to implement a logger class so that all console messages get written to a file.
But it has not been working out at all.
I would deeply appreciate if all you java gurus out there could modify the code given below to correctly log messages to a log file.
Please do Explain if possible ...I will try to rectify this issue in several other applications i developed as well.
import java.net.*;
import java.io.*;
import java.util.*;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.text.Format;
import java.lang.Object;
import java.lang.*;
import javax.crypto.*;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.KeySpec;
public class FTPServer
{ public static void main(String args[]) throws Exception
{ ServerSocket soc=new ServerSocket(5217);
System.out.println("FTP Server Started on Port Number 5217");
while(true)
System.out.println("Waiting for Connection ...");
transferfile t=new transferfile(soc.accept());
class transferfile extends Thread
Socket ClientSoc;
DataInputStream din;
DataOutputStream dout;
transferfile(Socket soc)
{ try
{ ClientSoc=soc;
din=new DataInputStream(ClientSoc.getInputStream());
dout=new DataOutputStream(ClientSoc.getOutputStream());
System.out.println("FTP Client Connected ...");
System.out.println("External IP of Client ..." + ClientSoc.getInetAddress());
//System.out.println("FTP Client Connected ..." + ClientSoc.getRemoteSocketAddress());
start();
catch(Exception ex)
//encrypto routine starts
class DesEncrypter {
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;
DesEncrypter(String passPhrase) {
try {
// Create the key
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance(
"PBEWithMD5AndDES").generateSecret(keySpec);
ecipher = Cipher.getInstance(key.getAlgorithm());
dcipher = Cipher.getInstance(key.getAlgorithm());
// Prepare the parameter to the ciphers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
// Create the ciphers
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (java.security.InvalidAlgorithmParameterException e) {
} catch (java.security.spec.InvalidKeySpecException e) {
} catch (javax.crypto.NoSuchPaddingException e) {
} catch (java.security.NoSuchAlgorithmException e) {
} catch (java.security.InvalidKeyException e) {
// Buffer used to transport the bytes from one stream to another
byte[] buf = new byte[1024];
public void encrypt(InputStream in, OutputStream out) {
try {
// Bytes written to out will be encrypted
out = new CipherOutputStream(out, ecipher);
// Read in the cleartext bytes and write to out to encrypt
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {
out.write(buf, 0, numRead);
out.close();
} catch (java.io.IOException e) {
public void decrypt(InputStream in, OutputStream out) {
try {
// Bytes read from in will be decrypted
in = new CipherInputStream(in, dcipher);
// Read in the decrypted bytes and write the cleartext to out
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {
out.write(buf, 0, numRead);
//added later on
in.close();
out.close();
} catch (java.io.IOException e) {
} //encryptor routine ends
//not implemented right now as we arent using the ftp server to download stuff...can be activated later on if we want
void SendFile() throws Exception
String filename=din.readUTF();
File f=new File(filename);
if(!f.exists())
dout.writeUTF("File Not Found");
return;
else
{ dout.writeUTF("READY");
FileInputStream fin=new FileInputStream(f);
int ch;
do
ch=fin.read();
dout.writeUTF(String.valueOf(ch));
while(ch!=-1);
fin.close();
dout.writeUTF("File Received Successfully");
String Compare(String filename) throws Exception
///dout.writeUTF("entering compare");
String dateTempString=new String();
Date dateValue=new Date();
SimpleDateFormat formatter = new SimpleDateFormat ("hhmmss");
dateTempString = formatter.format(dateValue);
File dir1 = new File("C:\\FTPnew");
boolean success2 = dir1.mkdir();
if (!success2) {
// Directory creation failed /Already Exists
File dir = new File("C:\\FTPnew\\server");
boolean success = dir.mkdir();
if (!success) {
// Directory creation failed /Already Exists
File ftemp=new File(dir,dateTempString + filename);
File fnewtemp=new File(dir,"new-enc-"+filename);
// Create encrypter/decrypter class
DesEncrypter encrypter = new DesEncrypter("My Pass Phrase!");
FileOutputStream fout=new FileOutputStream(fnewtemp);
int ch;
String temp;
do
{ temp=din.readUTF();
ch=Integer.parseInt(temp);
if(ch!=-1)
fout.write(ch);
}while(ch!=-1);
fout.close();
//dout.writeUTF("written temp en file");
// Decrypt
encrypter.decrypt(new FileInputStream(fnewtemp),
new FileOutputStream(ftemp));
//String Option;
dout.writeUTF("Delete");
System.out.println("File Upload Successfull--Duplicate file with timestamp Created");
boolean success1 = fnewtemp.delete();
return "hello" ;
void ReceiveFile() throws Exception
String ip=din.readUTF();
System.out.println("\tRequest Coming from Internal IP Address : "+ ip);
String filename=din.readUTF();
if(filename.compareTo("File not found")==0)
return;
// Destination directory
File dir11 = new File("C:\\FTPnew");
boolean success22 = dir11.mkdir();
if (!success22) {
// Directory creation failed /Already Exists
File dir = new File("C:\\FTPnew\\server");
boolean success21 = dir.mkdir();
if (!success21) {
// Directory creation failed /Already Exists
File f=new File(dir ,"enc-"+filename);
File fe=new File(dir,filename);
String option;
if(fe.exists())
//dout.writeUTF("File Already Exists");
String compvalue = Compare(filename);
//dout.writeUTF(compvalue);
if(compvalue.compareTo("hello")==0)
//dout.writeUTF("Transfer Completed");
return;
option=din.readUTF();
else
//dout.writeUTF("SendFile");
option="Y";
if(option.compareTo("Y")==0)
// Generate a temporary key.
// Create encrypter/decrypter class
DesEncrypter encrypter = new DesEncrypter("My Pass Phrase!");
FileOutputStream fout=new FileOutputStream(f);
int ch;
String temp;
do
{ temp=din.readUTF();
ch=Integer.parseInt(temp);
if(ch!=-1)
fout.write(ch);
}while(ch!=-1);
fout.close();
// Decrypt
encrypter.decrypt(new FileInputStream(f),
new FileOutputStream(fe));
boolean success2 = f.delete();
dout.writeUTF("Delete");
System.out.println("File Upload Successfull");
else
return;
public void run()
while(true)
try
String Command=din.readUTF();
if(Command.compareTo("SEND")==0)
System.out.println("\tSEND Command Received ...");
ReceiveFile();
continue;
catch(Exception ex)
//System.out.println("\tClient Terminated Abnormally ...........");
continue;
}Stick a
Logger log = Logger.getLogger( "me ftp server" );at the top.
Checn Sys.out.println to log.info( ... )
Add a logging prefs file.
http://java.sun.com/j2se/1.4.2/docs/guide/util/logging/overview.html -
Issue with Ftp Client / Server using Sockets
I have developed a Ftp Client and a Ftp Server. The client Connects to the Ftp Server and sends files to the ftp server. It is a multi threaded server and can have multiple clients connecting to it.
If a client goes down...the server waits till the client comes up
Similarly the client waits if a server goes down and reconnects when the server is again up and running
i am having a strange issue here. When two clients go down and reconnect to the server...They take a long time to connect and transferring of files takes a long time...
Other wise in all other scenarios the duo work properly.
Any feedback and suggestion about this strange issue from all you java gurus out there will be deeply appreciated.
Here is the client code
import java.net.*;
import java.net.Socket;
import java.net.InetAddress;
import java.io.*;
import java.io.File;
import java.util.*;
import java.lang.*;
import java.lang.Object;
import javax.crypto.*;
import java.util.regex.*;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.KeySpec;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.File.*;
import java.nio.channels.FileLock;
public class FTPClient {
public static void main(String[] args) throws Exception
Timer timer = new Timer("Test Timer");
timer.scheduleAtFixedRate(new TimerTask()
private int counter = 0;
public void run() {
try {
System.out.println(counter++);
Socket soc=new Socket("xxx.x.x.xx",5217);
System.out.println("Socket Initialised.");
transferfileClient t=new transferfileClient(soc);
t.SendFile();
System.out.println("run complete.");
catch(Exception ex)
}, 10000, 40000);
static class transferfileClient
Socket ClientSoc;
DataInputStream din;
DataOutputStream dout;
BufferedReader br;
transferfileClient(Socket soc)
try
ClientSoc=soc;
din=new DataInputStream(ClientSoc.getInputStream());
dout=new DataOutputStream(ClientSoc.getOutputStream());
br=new BufferedReader(new InputStreamReader(System.in));
catch(Exception ex)
//encrypto routine starts
class DesEncrypter {
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;
DesEncrypter(String passPhrase) {
try {
// Create the key
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance(
"PBEWithMD5AndDES").generateSecret(keySpec);
ecipher = Cipher.getInstance(key.getAlgorithm());
dcipher = Cipher.getInstance(key.getAlgorithm());
// Prepare the parameter to the ciphers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
// Create the ciphers
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (java.security.InvalidAlgorithmParameterException e) {
} catch (java.security.spec.InvalidKeySpecException e) {
} catch (javax.crypto.NoSuchPaddingException e) {
} catch (java.security.NoSuchAlgorithmException e) {
} catch (java.security.InvalidKeyException e) {
// Buffer used to transport the bytes from one stream to another
byte[] buf = new byte[1024];
public void encrypt(InputStream in, OutputStream out) {
try {
// Bytes written to out will be encrypted
out = new CipherOutputStream(out, ecipher);
// Read in the cleartext bytes and write to out to encrypt
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {
out.write(buf, 0, numRead);
out.close();
} catch (java.io.IOException e) {
public void decrypt(InputStream in, OutputStream out) {
try {
// Bytes read from in will be decrypted
in = new CipherInputStream(in, dcipher);
// Read in the decrypted bytes and write the cleartext to out
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {
out.write(buf, 0, numRead);
out.close();
} catch (java.io.IOException e) {
} //encryptor routine ends
void SendFile() throws Exception
try
String directoryName;
// File object referring to the directory.
String[] files; // Array of file names in the directory.
//directory = new File ( "C:\\FTP\\" ) ;
File directory1 = new File("C:\\FTP");
boolean successmk = directory1.mkdir();
if (!successmk) {
// Directory creation failed /Already Exists
File directory = new File("C:\\FTP\\ftpc");
boolean successmk1 = directory.mkdir();
if (!successmk1) {
// Directory creation failed /Already Exists
//directory = new File ( "E:\\FTP-encrypted" ) ;
if (directory.isDirectory() == false) {
if (directory.exists() == false)
System.out.println("There is no such directory!");
else
System.out.println("That file is not a directory.");
else {
files = directory.list();
System.out.println("Files in directory \"" + directory + "\":");
for (int i = 0; i < files.length; i++)
String patternStr = "xml";
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(files);
boolean matchFound = matcher.find();
if (matchFound) {
System.out.println(" " + files[i]);
String filename;
filename=files[i];
File f=new File(directory,filename);
FileLock lock = null;
FileOutputStream fos = new FileOutputStream(f, true);
lock = fos.getChannel().tryLock();
if (lock == null) {
System.out.println(" Failed to get the file lock: means that the file is locked by other instance.");
fos.close();
else
InetAddress addr = InetAddress.getLocalHost();
// Get IP Address
//byte[] ipAddr = addr.getAddress();
String ip= addr.toString();
// Get hostname
//String hostname = addr.getHostName();
System.out.println(" Lock Acquired.");
lock.release();
fos.close();
dout.writeUTF("SEND");
dout.writeUTF(ip);
dout.writeUTF(filename);
//String msgFromServer=din.readUTF();
DesEncrypter encrypter = new DesEncrypter("My Pass Phrase!");
// Encrypt
FileInputStream fino=new FileInputStream(f);
encrypter.encrypt(fino,
new FileOutputStream("ciphertext.txt"));
fino.close();
FileInputStream fin=new FileInputStream("ciphertext.txt");
int ch;
do
ch=fin.read();
dout.writeUTF(String.valueOf(ch));
while(ch!=-1);
fin.close();
String option;
option=din.readUTF();
if((option.compareTo("Delete")==0))
boolean success = (new File("ciphertext.txt")).delete();
boolean success1 = f.delete();
if (success) {
System.out.println("File Sent ...");
if (success1) {
System.out.println("--File deleted from Client ...");
for (int j = 0; j < 999999999; j++){}
}//pattermatch loop ends here
else
{ //System.out.println(" " + "Not an XML file-------->" +files[i]);
for (int jb = 0; jb < 111999999; jb++){}
}// for loop ends here for files in directory
}//else loop ends for directory files listing
System.out.println("sendfile finished...");
return;
} catch(Exception ex) {ex.printStackTrace();}
}//sendfile ends here
public void displayMenu() throws Exception
System.out.println(" Send File");
SendFile();
return;
And here is the server code...
import java.net.*;
import java.io.*;
import java.util.*;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.text.Format;
import java.lang.Object;
import java.lang.*;
import javax.crypto.*;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.KeySpec;
public class FTPServer
{ public static void main(String args[]) throws Exception
{ ServerSocket soc=new ServerSocket(5217);
System.out.println("FTP Server Started on Port Number 5217");
while(true)
System.out.println("Waiting for Connection ...");
transferfile t=new transferfile(soc.accept());
class transferfile extends Thread
Socket ClientSoc;
DataInputStream din;
DataOutputStream dout;
transferfile(Socket soc)
{ try
{ ClientSoc=soc;
din=new DataInputStream(ClientSoc.getInputStream());
dout=new DataOutputStream(ClientSoc.getOutputStream());
System.out.println("FTP Client Connected ...");
System.out.println("External IP of Client ..." + ClientSoc.getInetAddress());
//System.out.println("FTP Client Connected ..." + ClientSoc.getRemoteSocketAddress());
start();
catch(Exception ex)
//encrypto routine starts
class DesEncrypter {
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;
DesEncrypter(String passPhrase) {
try {
// Create the key
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance(
"PBEWithMD5AndDES").generateSecret(keySpec);
ecipher = Cipher.getInstance(key.getAlgorithm());
dcipher = Cipher.getInstance(key.getAlgorithm());
// Prepare the parameter to the ciphers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
// Create the ciphers
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (java.security.InvalidAlgorithmParameterException e) {
} catch (java.security.spec.InvalidKeySpecException e) {
} catch (javax.crypto.NoSuchPaddingException e) {
} catch (java.security.NoSuchAlgorithmException e) {
} catch (java.security.InvalidKeyException e) {
// Buffer used to transport the bytes from one stream to another
byte[] buf = new byte[1024];
public void encrypt(InputStream in, OutputStream out) {
try {
// Bytes written to out will be encrypted
out = new CipherOutputStream(out, ecipher);
// Read in the cleartext bytes and write to out to encrypt
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {
out.write(buf, 0, numRead);
out.close();
} catch (java.io.IOException e) {
public void decrypt(InputStream in, OutputStream out) {
try {
// Bytes read from in will be decrypted
in = new CipherInputStream(in, dcipher);
// Read in the decrypted bytes and write the cleartext to out
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {
out.write(buf, 0, numRead);
//added later on
in.close();
out.close();
} catch (java.io.IOException e) {
} //encryptor routine ends
//not implemented right now as we arent using the ftp server to download stuff...can be activated later on if we want
void SendFile() throws Exception
String filename=din.readUTF();
File f=new File(filename);
if(!f.exists())
dout.writeUTF("File Not Found");
return;
else
{ dout.writeUTF("READY");
FileInputStream fin=new FileInputStream(f);
int ch;
do
ch=fin.read();
dout.writeUTF(String.valueOf(ch));
while(ch!=-1);
fin.close();
dout.writeUTF("File Received Successfully");
String Compare(String filename) throws Exception
///dout.writeUTF("entering compare");
String dateTempString=new String();
Date dateValue=new Date();
SimpleDateFormat formatter = new SimpleDateFormat ("hhmmss");
dateTempString = formatter.format(dateValue);
File dir1 = new File("C:\\FTPnew");
boolean success2 = dir1.mkdir();
if (!success2) {
// Directory creation failed /Already Exists
File dir = new File("C:\\FTPnew\\server");
boolean success = dir.mkdir();
if (!success) {
// Directory creation failed /Already Exists
File ftemp=new File(dir,dateTempString + filename);
File fnewtemp=new File(dir,"new-enc-"+filename);
// Create encrypter/decrypter class
DesEncrypter encrypter = new DesEncrypter("My Pass Phrase!");
FileOutputStream fout=new FileOutputStream(fnewtemp);
int ch;
String temp;
do
{ temp=din.readUTF();
ch=Integer.parseInt(temp);
if(ch!=-1)
fout.write(ch);
}while(ch!=-1);
fout.close();
//dout.writeUTF("written temp en file");
// Decrypt
encrypter.decrypt(new FileInputStream(fnewtemp),
new FileOutputStream(ftemp));
//String Option;
dout.writeUTF("Delete");
System.out.println("File Upload Successfull--Duplicate file with timestamp Created");
boolean success1 = fnewtemp.delete();
return "hello" ;
void ReceiveFile() throws Exception
String ip=din.readUTF();
System.out.println("\tRequest Coming from Internal IP Address : "+ ip);
String filename=din.readUTF();
if(filename.compareTo("File not found")==0)
return;
// Destination directory
File dir11 = new File("C:\\FTPnew");
boolean success22 = dir11.mkdir();
if (!success22) {
// Directory creation failed /Already Exists
File dir = new File("C:\\FTPnew\\server");
boolean success21 = dir.mkdir();
if (!success21) {
// Directory creation failed /Already Exists
File f=new File(dir ,"enc-"+filename);
File fe=new File(dir,filename);
String option;
if(fe.exists())
//dout.writeUTF("File Already Exists");
String compvalue = Compare(filename);
//dout.writeUTF(compvalue);
if(compvalue.compareTo("hello")==0)
//dout.writeUTF("Transfer Completed");
return;
option=din.readUTF();
else
//dout.writeUTF("SendFile");
option="Y";
if(option.compareTo("Y")==0)
// Generate a temporary key.
// Create encrypter/decrypter class
DesEncrypter encrypter = new DesEncrypter("My Pass Phrase!");
FileOutputStream fout=new FileOutputStream(f);
int ch;
String temp;
do
{ temp=din.readUTF();
ch=Integer.parseInt(temp);
if(ch!=-1)
fout.write(ch);
}while(ch!=-1);
fout.close();
// Decrypt
encrypter.decrypt(new FileInputStream(f),
new FileOutputStream(fe));
boolean success2 = f.delete();
dout.writeUTF("Delete");
System.out.println("File Upload Successfull");
else
return;
public void run()
while(true)
try
String Command=din.readUTF();
if(Command.compareTo("SEND")==0)
System.out.println("\tSEND Command Received ...");
ReceiveFile();
continue;
catch(Exception ex)
//System.out.println("\tClient Terminated Abnormally ...........");
continue;Please note that this is not an FTP client and server. FTP is defined by a standard IETF protocol and this isn't it.
Then, move the following lines:
din=new DataInputStream(ClientSoc.getInputStream());
dout=new DataOutputStream(ClientSoc.getOutputStream());
System.out.println("FTP Client Connected ...");
System.out.println("External IP of Client ..." + ClientSoc.getInetAddress());
//System.out.println("FTP Client Connected ..."+ClientSoc.getRemoteSocketAddress());from the constructor into the run() method. i.e. don't do anything with the socket in the thread which handles the accept(). -
Can't get it to work!!! Please help with IllegalBlockSizeException
I have tried several things, I have searched the forume many times ever
since yesterday, but I just can't figure this out. Here is my method to encrypt:
private void encryptPassword(String p)
try{
//generate key using DES algorithm
byte key[] = "ababcabc".getBytes();
SecretKeySpec secretKey = new SecretKeySpec(key,"DES");
//get cipher for DES algorithm
Cipher cipher = Cipher.getInstance ("DES");
cipher.init(Cipher.ENCRYPT_MODE,secretKey);
//encrypt password
//byte[] tmp = Base64.encode(p.getBytes());
byte[] encryptedPswd = cipher.doFinal(p.getBytes("UTF-8"));
//byte[] encryptedPswd = cipher.doFinal(tmp);
password = new String(encryptedPswd, "UTF-8");
catch(Exception e){
logger.error("ERROR: Unable to encrypt password "
+ "due to Exception: " + e);
And here is my method to decrypt:
private String decryptPassword()
try
{ //generate key using DES algorithm
byte key[] = "ababcabc".getBytes();
SecretKeySpec secretKey = new SecretKeySpec(key,"DES");
//get cipher for DES algorithm
Cipher cipher = Cipher.getInstance ("DES");
cipher.init(Cipher.DECRYPT_MODE,secretKey);
//byte[] cipherCode = Base64.decode(password.getBytes());
//byte[] decryptedPswd = cipher.doFinal(cipherCode);
byte[] decryptedPswd = cipher.doFinal(password.getBytes("UTF-8"));
return new String(decryptedPswd, "UTF-8");
catch(Exception e){
logger.error("ERROR: Unable to decrypt password "
+ "due to Exception: " + e);
return "";
As you can see, I have tried to use Base64 encoder, but that didn't work either. I got ArrayIndexOutOfBounds exception with that. I followed this thread to try that: http://forum.java.sun.com/thread.jsp?forum=9&thread=302490. I used to get BadPaddingException when I didn't use "UTF-8" encoding. But now I get IllegalBlockSizeException. Please let me know what I am doing wrong.
Thank you so much!
MaliaI found the answer to my question at this site: http://javaalmanac.com/egs/javax.crypto/DesString.html
The key is to use base64 encoding, but I didn't know that the class sun.misc.BASE64Encoder and sun.misc.BASE64Decoder comes with regular JDK. I searched for base64 encoders, but the implementation from Ostermiller didn't work for me. So, for those having the same problem, go to that site. Here is the snapshot:
public class DesEncrypter {
Cipher ecipher;
Cipher dcipher;
DesEncrypter(SecretKey key) {
try {
ecipher = Cipher.getInstance("DES");
dcipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
} catch (javax.crypto.NoSuchPaddingException e) {
} catch (java.security.NoSuchAlgorithmException e) {
} catch (java.security.InvalidKeyException e) {
public String encrypt(String str) {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
return null;
public String decrypt(String str) {
try {
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
// Decrypt
byte[] utf8 = dcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
return null;
Here's an example that uses the class:
try {
// Generate a temporary key. In practice, you would save this key.
// See also e464 Encrypting with DES Using a Pass Phrase.
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
// Create encrypter/decrypter class
DesEncrypter encrypter = new DesEncrypter(key);
// Encrypt
String encrypted = encrypter.encrypt("Don't tell anybody!");
// Decrypt
String decrypted = encrypter.decrypt(encrypted);
} catch (Exception e) { -
How to store en-crypted passwords in Oracle database.
There are several user IDs for whom passwords are to be stored in database which are to be encrypted and there should be a function to compare the passwords entered with the passwords stored in the database .
Could any one let me know how to do this in Oralce.
thanksI'm giving u a small example -
declare
encryp raw(192) :=utl_raw.cast_to_raw('satyakidesatyaki');
ekey raw(8) :=utl_raw.cast_to_raw('12345678');
encryp1 raw(192);
begin
dbms_obfuscation_toolkit.desencrypt(input=>encryp,key=>ekey,encrypted_data =>encryp1);
dbms_output.put_line('after encry'||encryp1);
end;
I Hope this will help u a bit.
Satyaki. -
Are there any tools for data encryption and decryption ?
Hi,
i am using oracle 9i R2, i want encrypt my data. Are there any tools available in market.
Please let me know the ways to do data encryption and decryption.
Thanks in advance
Prasuna.970489 wrote:
using DBMS_OBFUSCATION_TOOLKIT.Encrypt /DESEncrypt we can't secure our password...So i am looking for an another alternative.As Blue Shadow said, what are you really trying to achieve?
Encrypting a password is itself not secure. Anything that can be encrypted can be decrypted. That is why Oracle itself DOES NOT encrypt passwords.
Surprised??
Here's what Oracle does with passwords, and what others should be doing if they have to store them.
When the password is created, the presented password - clear text - is concatenated with the username. The resulting character string is then passed through a one-way hashing function. It is that hashed value that is stored. Then when a user presents his credentials to log on to the system, the presented credentials are combined and hashed in the same manner as when the password was created, and the resulting hash value compared to the stored value. -
How to Implement simple Timer in this code
Hi there guys,
This is a small ftp client that i wrote. It has encryption and all bulit into it. I want to initiate the sendfile function every 5 minutes.
The program starts with the displaymenu function wherein a menu with various options is displayed.
How Do i Do that? I went online and tried doing it myself but cud not possibly think of a reason as to why my changes were not working.
Here is the basic code. I earnestly hope that some of you guys out there will help me. This is a very simple problem and sometimes it is the finer point that eludes us. any help will be deeply appreciated
import java.net.*;
import java.io.*;
import java.util.*;
import java.lang.*;
import javax.crypto.*;
import java.util.regex.*;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.KeySpec;
class FTPClient
public static void main(String args[]) throws Exception
Socket soc=new Socket("127.0.0.1",5217);
transferfileClient t=new transferfileClient(soc);
t.displayMenu();
class transferfileClient
Socket ClientSoc;
DataInputStream din;
DataOutputStream dout;
BufferedReader br;
transferfileClient(Socket soc)
try
ClientSoc=soc;
din=new DataInputStream(ClientSoc.getInputStream());
dout=new DataOutputStream(ClientSoc.getOutputStream());
br=new BufferedReader(new InputStreamReader(System.in));
catch(Exception ex)
//encrypto routine starts
class DesEncrypter {
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;
DesEncrypter(String passPhrase) {
try {
// Create the key
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance(
"PBEWithMD5AndDES").generateSecret(keySpec);
ecipher = Cipher.getInstance(key.getAlgorithm());
dcipher = Cipher.getInstance(key.getAlgorithm());
// Prepare the parameter to the ciphers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
// Create the ciphers
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (java.security.InvalidAlgorithmParameterException e) {
} catch (java.security.spec.InvalidKeySpecException e) {
} catch (javax.crypto.NoSuchPaddingException e) {
} catch (java.security.NoSuchAlgorithmException e) {
} catch (java.security.InvalidKeyException e) {
// Buffer used to transport the bytes from one stream to another
byte[] buf = new byte[1024];
public void encrypt(InputStream in, OutputStream out) {
try {
// Bytes written to out will be encrypted
out = new CipherOutputStream(out, ecipher);
// Read in the cleartext bytes and write to out to encrypt
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {
out.write(buf, 0, numRead);
out.close();
} catch (java.io.IOException e) {
public void decrypt(InputStream in, OutputStream out) {
try {
// Bytes read from in will be decrypted
in = new CipherInputStream(in, dcipher);
// Read in the decrypted bytes and write the cleartext to out
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {
out.write(buf, 0, numRead);
out.close();
} catch (java.io.IOException e) {
} //encryptor routine ends
void SendFile() throws Exception
String directoryName; // Directory name entered by the user.
File directory; // File object referring to the directory.
String[] files; // Array of file names in the directory.
//TextIO.put("Enter a directory name: ");
//directoryName = TextIO.getln().trim();
directory = new File ( "E:\\FTP-encrypted\\FTPClient" ) ;
if (directory.isDirectory() == false) {
if (directory.exists() == false)
System.out.println("There is no such directory!");
else
System.out.println("That file is not a directory.");
else {
files = directory.list();
System.out.println("Files in directory \"" + directory + "\":");
for (int i = 0; i < files.length; i++)
String patternStr = "xml";
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(files);
boolean matchFound = matcher.find();
if (matchFound) {
dout.writeUTF("SEND");
System.out.println(" " + files[i]);
String filename;
filename=files[i];
File f=new File(filename);
dout.writeUTF(filename);
String msgFromServer=din.readUTF();
if(msgFromServer.compareTo("File Already Exists")==0)
String Option;
System.out.println("File Already Exists. Want to OverWrite (Y/N) ?");
Option=br.readLine();
if(Option=="Y")
dout.writeUTF("Y");
else
dout.writeUTF("N");
return;
System.out.println("Sending File ...");
// Generate a temporary key. In practice, you would save this key.
// See also e464 Encrypting with DES Using a Pass Phrase.
System.out.println("Secret key generated ...");
// Create encrypter/decrypter class
DesEncrypter encrypter = new DesEncrypter("My Pass Phrase!");
// Encrypt
FileInputStream fino=new FileInputStream(f);
System.out.println("Initialised ...");
encrypter.encrypt(fino,
new FileOutputStream("ciphertext.txt"));
System.out.println("generated ...");
fino.close();
FileInputStream fin=new FileInputStream("ciphertext.txt");
int ch;
do
ch=fin.read();
dout.writeUTF(String.valueOf(ch));
while(ch!=-1);
fin.close();
boolean success = (new File("ciphertext.txt")).delete();
if (success) {
System.out.println("temp file deleted .../n/n");
for (int j = 0; j < 999999999; j++){}
}//pattermatch loop ends here
else
{ System.out.println(" " + "Not an XML file-------->" +files[i]); }
}// for loop ends here for files in directory
}//else loop ends for directory files listing
System.out.println(din.readUTF());
}//sendfile ends here
void ReceiveFile() throws Exception
String fileName;
System.out.print("Enter File Name :");
fileName=br.readLine();
dout.writeUTF(fileName);
String msgFromServer=din.readUTF();
if(msgFromServer.compareTo("File Not Found")==0)
System.out.println("File not found on Server ...");
return;
else if(msgFromServer.compareTo("READY")==0)
System.out.println("Receiving File ...");
File f=new File(fileName);
if(f.exists())
String Option;
System.out.println("File Already Exists. Want to OverWrite (Y/N) ?");
Option=br.readLine();
if(Option=="N")
dout.flush();
return;
FileOutputStream fout=new FileOutputStream(f);
int ch;
String temp;
do
temp=din.readUTF();
ch=Integer.parseInt(temp);
if(ch!=-1)
fout.write(ch);
}while(ch!=-1);
fout.close();
System.out.println(din.readUTF());
public void displayMenu() throws Exception
while(true)
System.out.println("[ MENU ]");
System.out.println("1. Send File");
System.out.println("2. Receive File");
System.out.println("3. Exit");
System.out.print("\nEnter Choice :");
int choice;
choice=Integer.parseInt(br.readLine());
if(choice==1)
SendFile();
else if(choice==2)
dout.writeUTF("GET");
ReceiveFile();
else
dout.writeUTF("DISCONNECT");
System.exit(1);here is a simple demo of a Timer usage.
public class Scheduler{
private Timer timer = null;
private FTPClient client = null;
public static void main(String args[]){
new Scheduler(5000);
public Scheduler(int seconds) {
client = new FTPClient();
timer = new Timer();
timer.schedule(new fileTransferTask(), seconds*1000);
timer.scheduleAtFixedRate(new FileTransferTask(client), seconds, seconds);
public class FileTransferTask extends TimerTask{
private FTPClient client = null;
public FileTransferTask(FTPClient client){
this.client = client;
public void run(){
client.sendFile();
public class FTPClient{
public void sendFile(){
// code to send the file by FTP
}the timer will will schedule the "task": scheduleAtFixRate( TimerTask, long delay, long interval)
It basically spawn a thread (this thread is the class that you
implements TimerTask..which in this example is the FileTransferTask)
The thread will then sleep until the time specified and once it wake..it
will execute the code in the the run() method. This is why you want to
pass a reference of any class that this TimerTask will use (that's why
we pass the FTPClient reference..so we can invoke the object's
sendFile method). -
How can I open a file with a REM format on my PC ?
Hi!I wanted to open a picture on my PC, but it has a REM format and my PC can't support it. I have red that this type of formats are an encryption of BB and I can open the picture if I desencrypt my media card....but now the main problem is that I don't find the options for my media card!It doesn't appears on my BB options! So,I need help please! Thanks!
"not supported, or might have been damaged."
That's key. If you're using Safari to download PDFs, it can do this.
Trash the SPD file. It can't be repaired.
Download the Adobe Reader FULL installer here: http://get.adobe.com/reader/enterprise/
Save the DMG to your downloads folder.
Go to: Mac HD/Library/Internet Plugins
Trash the AdobePDFViewer.plugin and AdobePDFViewerNPAPI.plugin files.
Empty the trash.
Download AppZapper (it's a free trial) and install it.
Launch AppZapper, and drag the Adobe Reader app to the window.
"Zap" it and anything else in the window to the trash.
Empty the trash.
Install Reader from the downloaded DMG and re-download the SPD file. -
Javax.crypto.BadPaddingException: Given final block not properly padded
import java.security.*;
import javax.crypto.*;
public class Cryptographer
private final String DEFAULT_KEY="1111111111111111";
private String KEY;
public Cryptographer(String key)
if((key==null)||key.equals(""))
this.KEY = DEFAULT_KEY;
else
this.KEY = key;
public byte[] encrypt(String toEncrypt)
if((toEncrypt==null)||(toEncrypt.trim().equals("")))
return null;
try
return DESEncrypt(toEncrypt,KEY);
catch(Exception e)
e.printStackTrace();
return null;
public String decrypt(byte[] bytes)
if(bytes==null)
return null;
try
return DESDecrypt(bytes,KEY);
catch(Exception e)
e.printStackTrace();
return null+"hi";
public String ToMac(byte[] bytes,String key)
if(bytes==null)
return null;
try
return getMac(bytes,KEY);
catch(Exception e)
return null;
private byte[] DESEncrypt(String toEncrypt, String key)
throws Exception
// create a binary key from the argument key (seed)
SecureRandom sr = new SecureRandom(key.getBytes("UTF-8"));
KeyGenerator kg = KeyGenerator.getInstance("DES");
kg.init(56,sr);
SecretKey sk = kg.generateKey();
// do the encryption with that key
Cipher cipher = Cipher.getInstance("DES");
//DES/CFB8/NOPadding;DES/OFB32/PKCS5Padding;DESEDE/ECB/PKCS5Padding;DES/ECB/NOPadding==DES
cipher.init(Cipher.ENCRYPT_MODE, sk);
byte[] encrypted = cipher.doFinal(toEncrypt.getBytes("UTF-8"));
return new sun.misc.BASE64Encoder().encode(encrypted).toUpperCase().getBytes();
//return encrypted;
private String DESDecrypt(byte[] toDecrypt, String key)
throws Exception
// create a binary key from the argument key (seed)
SecureRandom sr = new SecureRandom(key.getBytes("UTF-8"));
KeyGenerator kg = KeyGenerator.getInstance("DES");
kg.init(56,sr);
SecretKey sk = kg.generateKey();
// do the decryption with that key
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, sk);
byte[] decrypted = cipher.doFinal(toDecrypt);
return new sun.misc.BASE64Encoder().encode(decrypted).toUpperCase();
//return new String(decrypted,"UTF-8");
//create mac String; byte[] to be maced
private String getMac(byte[] bytes,String key)
byte[] bmac =null;
try
// create a binary key from the argument key (seed)
SecureRandom sr = new SecureRandom(key.getBytes());
KeyGenerator kg = KeyGenerator.getInstance("DES");
kg.init(56,sr);
SecretKey sk = kg.generateKey();
Mac mac = Mac.getInstance("HmacMD5");
//HmacMD5;HmacSHA1;PBEWith<mac> e.g PBEWithHmacSHA1
mac.init(sk);
bmac = mac.doFinal(bytes);
catch(Exception e)
e.printStackTrace();
return new String(bmac);
public String byte2hex(byte[] b) //��������������
String hs="";
String stmp="";
for (int n=0;n<b.length;n++)
stmp=(java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length()==1) hs=hs+"0"+stmp;
else hs=hs+stmp;
if (n<b.length-1) hs=hs+"";
return hs.toUpperCase();
public static void main(String args[])
throws Exception
String key = new String("1111111111111111");
Cryptographer c = new Cryptographer(key); //use key to initialize the class
String str = new String("4A6C98EAEF14EAB6");
byte[] b = c.encrypt(str); //to encrypt data
System.out.println(b.length);
System.out.println("Encrypted data:"+new String(b)+":"+new String(c.byte2hex(b))); //println Encrypt data
String st = c.decrypt(str.getBytes()); //to decrypt data
System.out.println(st.getBytes().length);
System.out.println(st.length());
System.out.println("Decrypted data:"+st+":"+c.byte2hex(st.getBytes())); //println decrypt data
please help me! thaxOne: Use the [ code ] tags. Please. It'll only help you get answers.
Two: encrypt() is returning the getBytes() of the result of Base64'ing the ciphertext. Bad. The whole POINT to Base64 is to produce Strings from byte[]'s. Don't use Base64 to produce a byte[]. Change encrypt() to return the byte[] directly.
Three: Given that encrypt() is returning the byte[] from the Base64 - decrypt() needs to be ready to UNDO that. It isn't. decrypt() assumes the byte[] it's getting is the ciphertext. That's not what you're giving to it. It's very, very unhappy.
Four: your main() isn't even handing decrypt() the (bogus) return from encrypt(). Your main() is asking decrypt() to decrypt your plaintext. That trick never works...
Five: your choice of variable names in your main() is...suboptimal. If you'd chosen names that reflected the purpose of the variable (things like, say, 'plaintext' and 'ciphertext'), some of this would have been obvious.
Try the following:import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
public class Cryptographer {
private final String DEFAULT_KEY = "1111111111111111";
private String KEY;
public Cryptographer(String key) {
if ((key == null) || key.equals("")) {
this.KEY = DEFAULT_KEY;
} else {
this.KEY = key;
public byte[] encrypt(String toEncrypt) {
if ((toEncrypt == null) || (toEncrypt.trim().equals("")))
return null;
try {
return DESEncrypt(toEncrypt, KEY);
} catch (Exception e) {
e.printStackTrace();
return null;
public String decrypt(byte[] bytes) {
if (bytes == null)
return null;
try {
return DESDecrypt(bytes, KEY);
} catch (Exception e) {
e.printStackTrace();
return null +"hi";
public String ToMac(byte[] bytes, String key) {
if (bytes == null)
return null;
try {
return getMac(bytes, KEY);
} catch (Exception e) {
return null;
private byte[] DESEncrypt(String toEncrypt, String key) throws Exception {
// create a binary key from the argument key (seed)
SecureRandom sr = new SecureRandom(key.getBytes("UTF-8"));
KeyGenerator kg = KeyGenerator.getInstance("DES");
kg.init(56, sr);
SecretKey sk = kg.generateKey();
// do the encryption with that key
Cipher cipher = Cipher.getInstance("DES");
//DES/CFB8/NOPadding;DES/OFB32/PKCS5Padding;DESEDE/ECB/PKCS5Padding;DES/ECB/NOPadding==DES
cipher.init(Cipher.ENCRYPT_MODE, sk);
byte[] encrypted = cipher.doFinal(toEncrypt.getBytes("UTF-8"));
return encrypted;
private String DESDecrypt(byte[] toDecrypt, String key) throws Exception {
// create a binary key from the argument key (seed)
SecureRandom sr = new SecureRandom(key.getBytes("UTF-8"));
KeyGenerator kg = KeyGenerator.getInstance("DES");
kg.init(56, sr);
SecretKey sk = kg.generateKey();
// do the decryption with that key
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, sk);
byte[] decrypted = cipher.doFinal(toDecrypt);
return new String(decrypted,"UTF-8");
//create mac String; byte[] to be maced
private String getMac(byte[] bytes, String key) {
byte[] bmac = null;
try {
// create a binary key from the argument key (seed)
SecureRandom sr = new SecureRandom(key.getBytes());
KeyGenerator kg = KeyGenerator.getInstance("DES");
kg.init(56, sr);
SecretKey sk = kg.generateKey();
Mac mac = Mac.getInstance("HmacMD5");
//HmacMD5;HmacSHA1;PBEWith<mac> e.g PBEWithHmacSHA1
mac.init(sk);
bmac = mac.doFinal(bytes);
} catch (Exception e) {
e.printStackTrace();
return new String(bmac);
public String byte2hex(byte[] b) //��������������
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1)
hs = hs + "0" + stmp;
else
hs = hs + stmp;
if (n < b.length - 1)
hs = hs + "";
return hs.toUpperCase();
public static void main(String args[]) throws Exception {
String key = new String("1111111111111111");
Cryptographer c = new Cryptographer(key); //use key to initialize the class
String str = new String("Hello world!");
byte[] ciphertext = c.encrypt(str); //to encrypt data
System.out.println(ciphertext.length);
System.out.println("Encrypted data:" + new String(c.byte2hex(ciphertext )));
String plaintext = c.decrypt(ciphertext ); //to decrypt data
System.out.println(plaintext.getBytes().length);
System.out.println(plaintext.length());
System.out.println("Decrypted data:" + plaintext ); //println decrypt data
}And please, please, PLEASE use the [ code ] tags...
Grant
Maybe you are looking for
-
Please help! I have two separate email addresses -my old mobile me and the new icloud and now nothing is syncing with my iphone. I'm not sure how to get everything back to syncing the way it was before I changed everything over to icloud.
-
How to generate a customized report with a table
I have a table with two columns: month, count. The values are like the following: Jan-2007 50 Feb-2007 46 Mar-2007 55 Apr-2007 76 Jan-2009 67 Feb-2009 86 Mar-2009 55 I want to generate a report like this: Month 2007 2008 2009 January 50 76 67 Febuary
-
Trouble With External Authentication!
Hello all! I have been trying to experiment with external authentication with PHP using the samples provided with the LCCS SDK Navigator. I have changed the "index.php" page to include all my account info. and have double checked it! However, when I
-
All flash videos are playing in a split screen since updating
I just updated flashplayer to the latest version (10.2.152.32) and now all videos play in a split screen. The videos get scrunched vertically, and it plays twice one ontop of the other, with a green bar in the middle. I use Opera primarily however
-
Shared memory problem : MaxDB
Hi I am using SAP ABAP trial version. It was working well but now when i start server. it gives the error: =================================================== ============== Starting System NSP ================ =======================================