Decryption of Blowfish key

All,
I have a Blowfish key that was originally generated elsewhere, I assume with PHP. I need to use this key like so:
1. Do mysql query from db for username and password.
2. Decrypt username and password.
I am new to encryption. Not sure of a key is a keystore, a key a certifcate, etc..?
How can I load this baby and use it? I am doing my own research, but I am new to encryption, so this will take a while : (
M

I have adjusted my method, there are no exceptions, but my decrypted string looks funny:
1kgZslMOZl6M9A7AW0OpzeReMeedZ4iUqEdIw4r8zAQ=
Also, when I try to decrypt field from mysql in the same row, with the same key, I get invalid padding errors.
I get the encrypted data from mysql using:
public static Hashtable<String,String> Info(String coId)throws Exception {
          boolean isConnected = false;
        // TODO Auto-generated method stub
        Hashtable<String, String> Info = new Hashtable<String,String>();
        if (!isConnected) {
              // Makes connection
              try {
                    Class.forName("com.mysql.jdbc.Driver");
                    Connection connect = DriverManager.getConnection("fdfsdfdfsd","sdasd","sdad");
              isConnected = true;
              PreparedStatement s = connect.prepareStatement("SELECT ID, PASSWORD FROM  WHERE CoID=? AND ID IS NOT NULL AND PASSWORD IS NOT NULL;");
              s.setString(1, coId);
              BASE64Decoder base64 = new BASE64Decoder();
              ResultSet rs = s.executeQuery();
              int keyIndex = 0;
              while (rs.next()) {
                   Blob idBlob = rs.getBlob("ID");
                   Blob passBlob = rs.getBlob("PASSWORD");
                  (int)passBlob.length());
                   InputStream inP = passBlob.getBinaryStream();
                   InputStream inID = idBlob.getBinaryStream();
                   byte[] p = base64.decodeBuffer(inP);
                   byte[] id = base64.decodeBuffer(inID);
                   String pp = new String(p, "UTF8");
                   String idid = new String(id, "UTF8");
                  Info.put("ID", idid);
                  Info.put("PASSWORD", pp);Main Method:
public static void main(String[] args)throws Exception{
          BlowfishWorker blowfish = new BlowfishWorker();
          Hashtable<String, String> login = new Hashtable<String, String>();
          login =  blowfish.salesForceInfo("Company");
          String id = login.get("ID");
          //System.out.println("print id"+id);
          String password = login.get("PASSWORD");
          //System.out.println("Before decryption");
          //String passwordDB = new String(password);
          System.out.println("----------------------------");
          System.out.println("After decryption");
          String p = blowfish.decrypt(password);
          //I get1kgZslMOZl6M9A7AW0OpzeReMeedZ4iUqEdIw4r8zAQ= for p
          System.out.println("Pass: "+p);
          System.out.println("------------------------------------");
          }Method:
public String decrypt(String item)throws Exception{
          FileReader fileReader = new FileReader("C:\\Documents and Settings\\mike\\Desktop\\key");
          BufferedReader reader = new BufferedReader(fileReader);
          String line="";
          String actualKey = null;
          String[] parts;
          Hashtable<String, String> keyLine = new Hashtable<String, String>();
          int rowCount =0;
          while((line = reader.readLine())!= null){
               //System.out.println(line);
               keyLine.put("key"+rowCount, line);
               rowCount++;
          for(int i =0;i<keyLine.size();i++){
               if(i==1){
                    parts = keyLine.get("key"+i).split("=");
                    actualKey = parts[1];
          //System.out.println("key:"+actualKey);
          Cipher cipher = Cipher.getInstance("Blowfish/CBC/NoPadding");
          byte[] keyBytes = actualKey.getBytes("UTF8");
          byte[] incomingBytes = item.getBytes("UTF8");
          Key myKey = new SecretKeySpec(keyBytes, "Blowfish");
          String keyAlg = myKey.getAlgorithm();
          System.out.println("Algorithm:"+keyAlg);
          String keyFormat = myKey.getFormat();
          System.out.println(keyFormat);
          AlgorithmParameterSpec iv = new IvParameterSpec(new byte[8]); // Create an IV of all zeros.
          cipher.init(Cipher.DECRYPT_MODE, myKey,iv);
          BASE64Encoder encoder = new BASE64Encoder();
          byte[] result = cipher.doFinal(incomingBytes);
          String finalResult = encoder.encode(result);
          return finalResult;
     }Edited by: ink86 on Jan 18, 2008 11:46 AM
Edited by: ink86 on Jan 18, 2008 11:50 AM

Similar Messages

  • Problem crypting/decrypting with Blowfish algorithm

    Hi,
    I'm doing an application which encrypt decrypt which blowfish algorithm.
    It works well, but not at all, when I crypt/decrypt a text file, the last line on the textfile disapear...
    The crypting class is this :
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import javax.crypto.Cipher;
    import javax.crypto.CipherOutputStream;
    import javax.crypto.KeyGenerator;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;
    public class Encrypteur {
    private Cipher blowfish;
    private SecretKeySpec key;
    public Encrypteur(byte[] key) {
    this.key = new SecretKeySpec(key, "Blowfish");
    loadBlowfish();
    public Encrypteur(){
    loadBlowfish();
    private void loadBlowfish(){
    try{
    blowfish = Cipher.getInstance("Blowfish");
    }catch(NoSuchAlgorithmException e){
    System.out.println("[Encrypteur][loadBlowfish] NoSuchAlgorithmException : "+e);
    }catch(NoSuchPaddingException e){
    System.out.println("[Encrypteur][loadBlowfish] NoSuchAlgorithmException : "+e);
    public static byte[] generateKey(){
    byte[] raw = null;
    try{
    KeyGenerator kgen = KeyGenerator.getInstance("Blowfish");
    SecretKey skey = kgen.generateKey();
    raw = skey.getEncoded();
    }catch(NoSuchAlgorithmException e){
    System.out.println("[Encrypteur][generateKey]" + e);
    e.printStackTrace();
    return raw;
    public void setKey(byte[] key){
    this.key = new SecretKeySpec(key, "Blowfish");
    public void encryptFile(File inputFile, File outputFile){
    try{
    blowfish.init(Cipher.ENCRYPT_MODE, key);
    FileOutputStream fOS = new FileOutputStream(outputFile);
    OutputStream oS = new CipherOutputStream( fOS, blowfish);
    InputStream iS = new FileInputStream(inputFile);
    int numRead = 0;
    while((numRead = iS.read()) != -1 ){
    oS.write(numRead);
    iS.close();
    fOS.close();
    oS.close();
    }catch(FileNotFoundException e){
    System.out.println("[Encrypteur][encryptFile] FileNotFoundException : " + e);
    e.printStackTrace();
    }catch(InvalidKeyException e){
    System.out.println("[Encrypteur][encryptFile] InvalidKeyException : " + e);
    e.printStackTrace();
    }catch(IOException e){
    System.out.println("[Encrypteur][encryptFile] IOException : " + e);
    e.printStackTrace();
    public void decryptFile(File inputFile, File outputFile){
    try{
    blowfish.init(Cipher.DECRYPT_MODE, key);
    FileOutputStream fOS = new FileOutputStream(outputFile);
    OutputStream oS = new CipherOutputStream( fOS, blowfish);
    InputStream iS = new FileInputStream(inputFile);
    int numRead = 0;
    while((numRead = iS.read()) != -1 ){
    oS.write(numRead);
    iS.close();
    fOS.close();
    oS.close();
    }catch(FileNotFoundException e){
    System.out.println("[Encrypteur][encryptFile] FileNotFoundException : " + e);
    e.printStackTrace();
    }catch(InvalidKeyException e){
    System.out.println("[Encrypteur][encryptFile] InvalidKeyException : " + e);
    e.printStackTrace();
    }catch(IOException e){
    System.out.println("[Encrypteur][encryptFile] IOException : " + e);
    e.printStackTrace();
    And don't from where it can come... Perhaps from the reading of files ?
    or perhaps from Cipher class ?
    thanks of your solutions :)

    I find from where it come :)
    To decrypt the file I had to use a CipherInputStream and not a CipherOutputStream.
    not it works well.

  • Is it true that FileVault can be decrypted without a key?

    Hello,
    I just turned on my FileVault 2 like 3-4 hours back and was just web-searching how secure it was.
    I happen to come accross a Youtube video and a website that says it can be decrypted without any key.
    The software: http://www.lostpassword.com/news/pnl61.htm
    Could anyone please tell me if this is true?
    Thanks,
    Graham Miranda
    <Link Edited By Host>

    I would not turn on FileVault unless my Macs were in a "hostile" environment. I also do not trust 90% of YouTube's content. You can test this yourself - no need for a second computer: clone your hard drive to an external drive so you have a bootable copy. Then follow the steps shown. If it works, fine. If not, wipe your drive and clone back your system.

  • Getting Error while decrypt a file using Blowfish algorithm

    I am using blowfish algorithm for encrypt and decrypt my file. this is my code for encrypting decrypting .
    while i am running program i am getting an Exception
    Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded
    at com.sun.crypto.provider.SunJCE_h.b(DashoA6275)
    at com.sun.crypto.provider.SunJCE_h.b(DashoA6275)
    at com.sun.crypto.provider.BlowfishCipher.engineDoFinal(DashoA6275)
    at javax.crypto.Cipher.doFinal(DashoA12275)
    at Blowfishexe.main(Blowfishexe.java:65)
    import java.security.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.io.*;
    import org.bouncycastle.crypto.CryptoException;
    import org.bouncycastle.crypto.KeyGenerationParameters;
    import org.bouncycastle.crypto.engines.DESedeEngine;
    import org.bouncycastle.crypto.generators.DESedeKeyGenerator;
    import org.bouncycastle.crypto.modes.CBCBlockCipher;
    import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
    import org.bouncycastle.crypto.params.DESedeParameters;
    import org.bouncycastle.crypto.params.KeyParameter;
    import org.bouncycastle.util.encoders.Hex;
    public class Blowfishexe {
    public static void main(String[] args) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("Blowfish");
              kgen.init(128);
              String keyfile="C:\\Encryption\\BlowfishKey.dat";
    SecretKey skey = kgen.generateKey();
    byte[] raw = skey.getEncoded();
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "Blowfish");
              System.out.println("key"+raw);
                   byte[] keyBytes = skey.getEncoded();
                   byte[] keyhex = Hex.encode(keyBytes);
                   BufferedOutputStream keystream =
    new BufferedOutputStream(new FileOutputStream(keyfile));
                        keystream.write(keyhex, 0, keyhex.length);
    keystream.flush();
    keystream.close();
    Cipher cipher = Cipher.getInstance("Blowfish");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
              System.out.println("secretKey"+skeySpec);
    FileOutputStream fos=new FileOutputStream("C:\\Encryption\\credit11.txt");
              BufferedReader br=new BufferedReader(new FileReader("C:\\Encryption\\credit.txt"));
              String text=null;
              byte[] plainText=null;
              byte[] cipherText=null;
              while((text=br.readLine())!=null)
              System.out.println(text);
              plainText = text.getBytes();
              cipherText = cipher.doFinal(plainText);
              fos.write(cipherText);
              br.close();
              fos.close();
              cipher.init(Cipher.DECRYPT_MODE, skeySpec);
              FileOutputStream fos1=new FileOutputStream("C:\\Encryption\\BlowfishOutput.txt");
              BufferedReader br1=new BufferedReader(new FileReader("C:\\Encryption\\credit11.txt"));
              String text1=null;
              /*while((text1=br1.readLine())!=null)
                   System.out.println("text is"+text1);
                   plainText=text1.getBytes("UTF8");
                   cipherText=cipher.doFinal(plainText);
                   fos1.write(cipherText);
              br1.close();
              fos1.close();
    //byte[] encrypted = cipher.doFinal("This is just an example".getBytes());
              //System.out.println("encrypted value"+encrypted);*/
    Any one pls tell me how to slove my problem
    thanks in advance

    hi
    i got the solution. its working now
    but blowfish key ranges from 56 to448
    while i am writing the code as
    KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
    keyGenerator.init(448);
    this code is generating the key upto 448 bits
    but coming to encoding or decode section key length is not accepting
    cipher.init(Cipher.ENCRYPT_MODE, key);
    Exception in thread "main" java.security.InvalidKeyException: Illegal key size or default parameters
    at javax.crypto.Cipher.a(DashoA12275)
    at javax.crypto.Cipher.a(DashoA12275)
    at javax.crypto.Cipher.a(DashoA12275)
    at javax.crypto.Cipher.init(DashoA12275)
    at javax.crypto.Cipher.init(DashoA12275)
    at Blowfish1.main(Blowfish1.java:46)
    i am getting this error
    what is the solution for this type of exception.
    thank you

  • Problem with storing key into database and decrypting the password.....

    Hi every one, i have prob with this code
    import java.security.NoSuchAlgorithmException;
    import java.sql.Blob;
    import java.sql.ResultSet;
    import javax.crypto.KeyGenerator;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.SecretKey;
    import java.security.Key;
    import java.io.*;
    import java.security.InvalidKeyException;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    public class SecurityUtil {
    public static final String ALGORITHM ="DES";
    public static Cipher cipher;
    SecurityUtil() throws NoSuchAlgorithmException, NoSuchPaddingException {
    cipher = Cipher.getInstance(ALGORITHM);}
    public static void serializeKey(Key key, File file) {
    //serializing
    try {     FileOutputStream fos = new FileOutputStream(file);
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(key);
    oos.flush();
    oos.close(); } catch (Exception e) { System.out.println("Exception during serialization: " + e);
    System.exit(0); } }
    public static SecretKey deserializeKey(File file) {   //deserializing
    SecretKey key1 = null;
    try {  FileInputStream fis = new FileInputStream(file);
    ObjectInputStream ois = new ObjectInputStream(fis);
    key1 = (SecretKey) ois.readObject();
    ois.close();
    System.out.println("object2: " + key1); } catch (Exception e) {
    System.out.println("Exception during deserialization: " + e);
    System.exit(0);}
    return key1;
    public static byte[] encrypt(String input, SecretKey key) throws InvalidKeyException, BadPaddingException,
    IllegalBlockSizeException {
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] inputBytes = input.getBytes();
    return cipher.doFinal(inputBytes);
    public static String decrypt(byte[] encryptionBytes, SecretKey key) throws InvalidKeyException,
    BadPaddingException, IllegalBlockSizeException {
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] recoveredBytes = cipher.doFinal(encryptionBytes);
    String recovered = new String(recoveredBytes);
    return recovered;
    public static void main(String[] args) throws Exception {
    SecurityUtil su = new SecurityUtil();
    // SecurityUtil.testUsingSerialization();
    SecurityUtil.testWithDatabase();
    public static void testUsingSerialization() throws Exception {
    KeyGenerator kg = KeyGenerator.getInstance("DES");
    kg.init(56); // 56 is the keysize. Fixed for DES
    SecretKey key = kg.generateKey();
    File file1 = new File("root:/testKey.key");
    serializeKey(key, file1);
    SecretKey deserializedKey = deserializeKey(file1);
    byte[] encryptionBytes = encrypt("input", key);
    System.out.println("Recovered: " + decrypt(encryptionBytes, deserializedKey));
    public static void testWithDatabase() throws Exception {
    KeyGenerator kg = KeyGenerator.getInstance("DES");
    kg.init(56); // 56 is the keysize. Fixed for DES
    SecretKey key = kg.generateKey();
    boolean insertResult = insert("prasunay","prasunay",key);
    System.out.println("<<======= insert result: " + insertResult);
    boolean validateAuthenticationDetails = validateAuthenticationDetails("prasunay","prasunay");
    System.out.println("<<======= right values:" + validateAuthenticationDetails);
    boolean validateAuthenticationDetails1 = validateAuthenticationDetails("prasunay","prasun");
    System.out.println("<<======= WRONG values:" + validateAuthenticationDetails1);
    System.out.print("done!"); }
    public static boolean insert(String username,String password,SecretKey key) throws Exception {
    // mysql> CREATE TABLE myusers (user_name VARCHAR(20), pass_word VARCHAR(20), my_key BLOB);
    // Query OK, 0 rows affected (0.03 sec)
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost/users?user=root&password=");
    PreparedStatement ps = con.prepareStatement("INSERT INTO myusers VALUES (?, ?, ?)");
    ps.setString(1,username);
    byte[] encryptionBytes = encrypt(password, key);
    ps.setString(2, new String(encryptionBytes));
    ByteArrayInputStream ois = getStreamFromKey(key);
    byte[] keyBytes = getBytesFromKey(key);
    System.out.println("Key Length" + keyBytes.length);
    ps.setBinaryStream(3, ois, keyBytes.length);
    int result = ps.executeUpdate();
    System.out.println(result);
    ps.close();
    con.close();
    if (result > 0) {
    return true;
    } else {
    return false; } }

    code continuation.......
    public static boolean validateAuthenticationDetails(String username, String password) throws Exception {
    boolean result = false;
    // mysql> CREATE TABLE myusers (user_name VARCHAR(20), pass_word VARCHAR(20), my_key BLOB);
    // Query OK, 0 rows affected (0.03 sec)
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost/users?user=root&password=");
    PreparedStatement ps = con.prepareStatement("select my_key,pass_word from myusers where user_name = ?");
    ps.setString(1, username);
    ResultSet resultSet = ps.executeQuery();
    if (resultSet.next()) {
    String passwordFromDB = resultSet.getString("pass_word");
    Blob keyBlob = resultSet.getBlob("my_key");
    System.out.println(keyBlob);
    System.out.println("key" + resultSet.getBinaryStream("my_key").read());
    InputStream keyInputBinaryStream = keyBlob.getBinaryStream();
    System.out.println("keyInputBinaryStream: " + keyInputBinaryStream);
    System.out.println("keyInputBinaryStream: " + keyInputBinaryStream.available());
    ObjectInputStream ois = new ObjectInputStream(keyInputBinaryStream);
    SecretKey key = (SecretKey) ois.readObject();
    System.out.println(key);
    String decryptedPwd = decrypt(passwordFromDB.getBytes(), key);
    System.out.println("Decrypted pwd : " + decryptedPwd);
    System.out.println("pwd sent for authorization : " + password);
    if (password.equals(decryptedPwd)) {
    result = true;
    } else {result = false;   }
    } else {
    System.out.println("Invalid user!!"); }
    ps.close();
    con.close();
    return result; }
    public static ByteArrayInputStream getStreamFromKey(SecretKey key) throws Exception {
    ByteArrayOutputStream o = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(o);
    out.writeObject(key);
    byte[] keyBytes = o.toByteArray();
    ByteArrayInputStream bis = new ByteArrayInputStream(keyBytes);
    return bis;}
    public static byte[] getBytesFromKey(SecretKey key) throws Exception {
    ByteArrayOutputStream o = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(o);
    out.writeObject(key);
    byte[] keyBytes = o.toByteArray();
    return keyBytes; } }
    but it is giving following run-time error: Key Length263
    1
    <<======= insert result: true
    com.mysql.jdbc.Blob@1ea0252
    key172
    keyInputBinaryStream: java.io.ByteArrayInputStream@3e89c3
    keyInputBinaryStream: 263
    javax.crypto.spec.SecretKeySpec@fffe7a51
    Exception in thread "main" javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher
    plzz suggest some solution...

  • Very urgent : please help !!!! Blowfish problem

    Greetings people,
    I have devised an application which reads the value from file and encrypts it (using Blowfish)......The file is then read and decrypted accordingly..............
    Problem : I seem to be able to encrypt and further decrypt file(s) which size is below 100 bytes. Anything beyond that will trigger the following :
    javax.crypto.IllegalBlockSizeException: Input length (with padding) not multiple of 8 bytes
    at com.sun.crypto.provider.SunJCE_h.a(DashoA6275)
    at com.sun.crypto.provider.SunJCE_h.b(DashoA6275)
    at com.sun.crypto.provider.SunJCE_h.b(DashoA6275)
    at com.sun.crypto.provider.BlowfishCipher.engineDoFinal(DashoA6275)
    at javax.crypto.Cipher.doFinal(DashoA6275)
    at LockDownBase.decrypt(LockDownBase.java:144)
    Could someone please help me with this dilemma as time is of the essence at this point and I really need to get this thing up and running. (ps. It is necessary for me to retain the usage of the Base64 Encoder as I am conducting a study on the usage of this Encoder).
    Thank you for the help
    <code>
    import java.io.*;
    import java.math.*;
    import java.security.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import sun.misc.*;
    public class LockDownBase {
    private static String keyFile = "c:\\encode\\blowfishbase.txt";
    public static String new_key (String me) throws Exception {
    //Get a blowfish key
    KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
    keyGenerator.init(128);
    SecretKey key = keyGenerator.generateKey();
    System.out.println("OK");
    byte [] encoded = key.getEncoded();
    FileOutputStream fos = new FileOutputStream(keyFile);
    fos.write(encoded);
    fos.close();
    return me;
    //initKey
    public static Key initKey() throws Exception{
    FileInputStream in = new FileInputStream(keyFile);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int i;
    while((i=in.read()) != -1){
    baos.write(i);
    in.close();
    byte [] keys = baos.toByteArray();
    SecretKeySpec key = new SecretKeySpec(keys,"Blowfish");
    Key keyword = key;
    return key;
    public static String encrypt (String location) throws Exception{
    //PrintStream is deprecated, but works fine in jdk1.1.7b
    //PrintStream output1 = new PrintStream(outFile1);
    //get_key
    String testme = "dummy";
    Key key = initKey();
    Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    // read in the input file
    String line;
    StringBuffer buffer = new StringBuffer();
    FileInputStream fis = new FileInputStream(location);
    InputStreamReader isr = new InputStreamReader(fis);
    Reader in = new BufferedReader(isr);
    int ch;
    while ((ch = in.read()) > -1) {
    buffer.append((char)ch);
    in.close();
    line = buffer.toString();
    byte [] cipherText = cipher.doFinal(line.getBytes("UTF8"));
    //output1.print(" ");
    // output1.println("ciphertext.length = " + cipherText.length);
    // print out representation of ciphertext to general output file
    BASE64Encoder encoding = new BASE64Encoder();
    String feed = encoding.encode(cipherText);
    FileOutputStream outFile2 = new FileOutputStream(location);
    PrintStream output2 = new PrintStream(outFile2);
    output2.close();
    String dir = location;
    FileOutputStream outFile3 = new FileOutputStream(dir);
    PrintStream output3 = new PrintStream(outFile3);
    output3.println(feed);
    output3.close();
    return location;
    public static String decrypt (String location) throws Exception{
    Key key = initKey();
    String line;
    String dir = location;
    FileReader far = new FileReader (dir);
    BufferedReader stdin = new BufferedReader(far,8192);
    String line = null;
    while ((line = stdin.readLine()) != null){
    BASE64Decoder decoding = new BASE64Decoder();
    byte[] decrypted = decoding.decodeBuffer(line);
    Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte [] decryptedtext = cipher.doFinal(decrypted);
    String output = new String (decryptedtext,"UTF8");
    System.out.println(output);
    FileOutputStream outFile1 = new FileOutputStream(location);
    PrintStream output1 = new PrintStream(outFile1);
    output1.println(output);
    output1.close();
    return location;
    </code>

    The error message says it all.
    Input length (with padding) not multiple of 8 bytes
    As you are using PKCS5Padding you will have an output data whose length is padded with 1 a 8 bytes. For instance, if your original data have 1023 bytes, it is padded with 1 byte - total length = 1024. It your original data have 1024 bytes, it will be padded with 8 bytes (not 0 as you could think).
    You have some problem encoding and decoding Base-64 - it is not yielding the original encrypted results. Your best friend is System.out.println of the length of the original and encrypted data.

  • Password and Blowfish? (Much closer but still need help)

    I'm still trying to decrypt a file encoded with a password-based (PBKDF2) Blowfish cipher. I'm bit further now but starting to run out of ideas. Here is what I have so far:
    // 1. Given a password, build a password-based key and from that build a Blowfish key
    PBEKeySpec kspec = new PBEKeySpec( pwd.toCharArray(), salt, iterationCount, keySize );
    SecretKeyFactory kfact = SecretKeyFactory.getInstance( "PBKDF2WithHmacSHA1" );
    SecretKey sKey = kfact.generateSecret( kspec );
    byte[] keyBytes = sKey.getEncoded(); // Is this right?
    Key bfKey = new SecretKeySpec( keyBytes, "Blowfish" );
    // 2. Given Blowfish key and initialization vector, decrypt the cipherText into plainText
    Cipher cipher = Cipher.getInstance("Blowfish/CFB/NoPadding");
    IvParameterSpec iv = new IvParameterSpec( initVector );
    cipher.init( Cipher.DECRYPT_MODE, bfKey, iv );
    byte[] plainText = cipher.doFinal( cipherText );In a full test bed, this compiles and runs just fine, except that it doesn't appear to decrypt the data as expected.
    More specifically, when I use Cipher.ENCRYPT_MODE to encrypt something like "This-is-a-test" and then decrypt the result with the code above only the first 8 bytes of the result return to plain text, the rest are garbage ("This-is-XXXX...").
    The simple test case, at least, should work perfectly but I'm still missing something crucial. The fact that the first 8 bytes decode fine but not the rest feels like a hint to me, but I'm just not getting what the issue might be as I used the same password, initialization vector, key-, and cipher-types in both directions (encode/decode).
    Help?

    Umm, mea culpa on the encrypt/decrypt test; that part works now (yay!) My core issue remains, however, and that involves getting the OOo document component (content.xml) to decrypt:
    The document meta-data definitely indicates "Blowfish CFB" which I take to mean "Blowfish/CFB/NoPadding".
    What would help me greatly is if someone (perhaps even you, Sabre) could take a look at the following code fragment and tell me if I'm (a) doing something fundamentally wrong here (specifically with the key conversion from PBKDF2 to Blowfish), or (b) if there is an alternative way of doing what I think(hope) I'm doing, which may have different/better results. My trouble is that the decrypt step on the document produces merely binary data (not compressed data which was to come out of the decryption):
    // 1. Create a password-based ("PBKDF2") key, then build a "Blowfish" key from that
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance( "PBKDF2WithHmacSHA1" );
        PBEKeySpec pbKeySpec = new PBEKeySpec( password.toCharArray(), salt, 1024, 128 );
        SecretKey pbKey = keyFactory.generateSecret( pbKeySpec );
        byte[] encoded = pbKey.getEncoded();
        Key bfKey = new SecretKeySpec( encoded, "Blowfish" );
    // 2. Initialize a specific cipher with the key, and initialization vector
        Cipher bfCipher = Cipher.getInstance( "Blowfish/CFB/NoPadding" );
        IvParameterSpec iv = new IvParameterSpec( initVector );
        bfCipher.init( Cipher.DECRYPT_MODE, bfKey, iv );
    // 3. Decrypt it
        byte[] plainText = bfCipher.doFinal( cipherText );If full code would help, I'll gladly post it, but the above is the distilled core of the thing and probably easier to grok. Thanks!

  • Easy way to exchange Keys?

    Hi, i got a message crypted with a blowfish algorythm and i want to send it with my key to another people. How can i do that easily. Are there functions in JCE that i can use to do it or must i use a Diffie-hellman exchange key scheme?
    Thanks a lot.

    Hi, i got a message crypted with a blowfish algorythm
    and i want to send it with my key to another people.
    How can i do that easily. Are there functions in JCE
    that i can use to do it or must i use a Diffie-hellman
    exchange key scheme?
    Thanks a lot.Hi,
    You'll obviously need some kind of asymmetric (public key) algorithm for key exchange, and the sender needs the recipient's key. If you don't want to use Diffie-Hellman, you might try RSA. You simply use the Cipher object in WRAP_MODE, initialized with the recipient's public key, and pass in the Blowfish key. The recipient then uses UNWRAP_MODE to pull out the Blowfish key and decrypt the message. Good luck.

  • System encryption using LUKS and GPG encrypted keys for arch linux

    Update: As of 2012-03-28, arch changed from gnupg 1.4 to 2.x which uses pinentry for the password dialog. The "etwo" hook described here doesn't work with gnupg 2. Either use the openssl hook below or use a statically compiled version of gnupg 1.4.
    Update: As of 2012-12-19, the mkinitcpio is not called during boot, unless the "install" file for the hook contains "add_runscript". This resulted in an unbootable system for me. Also, the method name was changed from install () to build ().
    Update: 2013-01-13: Updated the hook files using the corrections by Deth.
    Note: This guide is a bit dated now, in particular the arch installation might be different now. But essentially, the approach stays the same. Please also take a look at the posts further down, specifically the alternative hooks that use openssl.
    I always wanted to set up a fully encrypted arch linux server that uses gpg encrypted keyfiles on an external usb stick and luks for root filesystem encryption. I already did it once in gentoo using this guide. For arch, I had to play alot with initcpio hooks and after one day of experimentation, I finally got it working. I wrote a little guide for myself which I'm going to share here for anyone that might be interested. There might be better or easier ways, like I said this is just how I did it. I hope it might help someone else. Constructive feedback is always welcome
    Intro
    Using arch linux mkinitcpio's encrypt hook, one can easily use encrypted root partitions with LUKS. It's also possible to use key files stored on an external drive, like an usb stick. However, if someone steals your usb stick, he can just copy the key and potentially access the system. I wanted to have a little extra security by additionally encrypting the key file with gpg using a symmetric cipher and a passphrase.
    Since the encrypt hook doesn't support this scenario, I created a modifed hook called “etwo” (silly name I know, it was the first thing that came to my mind). It will simply look if the key file has the extension .gpg and, if yes, use gpg to decrypt it, then pipe the result into cryptsetup.
    Conventions
    In this short guide, I use the following disk/partition names:
    /dev/sda: is the hard disk that will contain an encrypted swap (/dev/sda1), /var (/dev/sda2) and root (/dev/sda3) partition.
    /dev/sdb is the usb stick that will contain the gpg encrypted luks keys, the kernel and grub. It will have one partition /dev/sdb1 formatted with ext2.
    /dev/mapper/root, /dev/mapper/swap and /dev/mapper/var will be the encrypted devices.
    Credits
    Thanks to the authors of SECURITY_System_Encryption_DM-Crypt_with_LUKS (gentoo wiki), System Encryption with LUKS (arch wiki), mkinitcpio (arch wiki) and Early Userspace in Arch Linux (/dev/brain0 blog)!
    Guide
    1. Boot the arch live cd
    I had to use a newer testing version, because the 2010.05 cd came with a broken gpg. You can download one here: http://releng.archlinux.org/isos/. I chose the “core“ version. Go ahead and boot the live cd, but don't start the setup yet.
    2. Set keymap
    Use km to set your keymap. This is important for non-qwerty keyboards to avoid suprises with passphrases...
    3. Wipe your discs
    ATTENTION: this will DELETE everything on /dev/sda and /dev/sdb forever! Do not blame me for any lost data!
    Before encrypting the hard disc, it has to be completely wiped and overwritten with random data. I used shred for this. Others use badblocks or dd with /dev/urandom. Either way, this will take a long time, depending on the size of your disc. I also wiped my usb stick just to be sure.
    shred -v /dev/sda
    shred -v /dev/sdb
    4. Partitioning
    Fire up fdisk and create the following partitions:
    /dev/sda1, type linux swap.
    /dev/sda2: type linux
    /dev/sda3: type linux
    /dev/sdb1, type linux
    Of course you can choose a different layout, this is just how I did it. Keep in mind that only the root filesystem will be decrypted by the initcpio. The rest will be decypted during normal init boot using /etc/crypttab, the keys being somewhere on the root filesystem.
    5. Format  and mount the usb stick
    Create an ext2 filesystem on /dev/sdb1:
    mkfs.ext2 /dev/sdb1
    mkdir /root/usb
    mount /dev/sdb1 /root/usb
    cd /root/usb # this will be our working directory for now.
    Do not mount anything to /mnt, because the arch installer will use that directory later to mount the encrypted root filesystem.
    6. Configure the network (if not already done automatically)
    ifconfig eth0 192.168.0.2 netmask 255.255.255.0
    route add default gw 192.168.0.1
    echo "nameserver 192.168.0.1" >> /etc/resolv.conf
    (this is just an example, your mileage may vary)
    7. Install gnupg
    pacman -Sy
    pacman -S gnupg
    Verify that gnupg works by launching gpg.
    8. Create the keys
    Just to be sure, make sure swap is off:
    cat /proc/swaps
    should return no entries.
    Create gpg encrypted keys (remember, we're still in our working dir /root/usb):
    dd if=/dev/urandom bs=512 count=4 | gpg -v --cipher-algo aes256 --digest-algo sha512 -c -a > root.gpg
    dd if=/dev/urandom bs=512 count=4 | gpg -v --cipher-algo aes256 --digest-algo sha512 -c -a > var.gpg
    Choose a strong password!!
    Don't do this in two steps, e.g don't do dd to a file and then gpg on that file. The key should never be stored in plain text on an unencrypted device, except if that device is wiped on system restart (ramfs)!
    Note that the default cipher for gpg is cast5, I just chose to use a different one.
    9. Create the encrypted devices with cryptsetup
    Create encrypted swap:
    cryptsetup -c aes-cbc-essiv:sha256 -s 256 -h whirlpool -d /dev/urandom create swap /dev/sda1
    You should see /dev/mapper/swap now. Don't format nor turn it on for now. This will be done by the arch installer.
    Important: From the Cryptsetup 1.1.2 Release notes:
    Cryptsetup can accept passphrase on stdin (standard input). Handling of new line (\n) character is defined by input specification:
        if keyfile is specified as "-" (using --key-file=- or by positional argument in luksFormat and luksAddKey, like cat file | cryptsetup --key-file=- <action> ), input is processed
          as normal binary file and no new line is interpreted.
        if there is no key file specification (with default input from stdin pipe like echo passphrase | cryptsetup <action> ) input is processed as input from terminal, reading will
          stop after new line is detected.
    If I understand this correctly, since the randomly generated key can contain a newline early on, piping the key into cryptsetup without specifying --key-file=- could result in a big part of the key to be ignored by cryptsetup. Example: if the random key was "foo\nandsomemorebaratheendofthekey", piping it directly into cryptsetup without --key-file=- would result in cryptsetup using only "foo" as key which would have big security implications. We should therefor ALWAYS pipe the key into cryptsetup using --key-file=- which ignores newlines.
    gpg -q -d root.gpg 2>/dev/null | cryptsetup -v -–key-file=- -c aes-cbc-essiv:sha256 -s 256 -h whirlpool luksFormat /dev/sda3
    gpg -q -d var.gpg 2>/dev/null | cryptsetup -v –-key-file=- -c aes-cbc-essiv:sha256 -s 256 -h whirlpool -v luksFormat /dev/sda2
    Check for any errors.
    10. Open the luks devices
    gpg -d root.gpg 2>/dev/null | cryptsetup -v –-key-file=- luksOpen /dev/sda3 root
    gpg -d var.gpg 2>/dev/null | cryptsetup -v –-key-file=- luksOpen /dev/sda2 var
    If you see /dev/mapper/root and /dev/mapper/var now, everything is ok.
    11. Start the installer /arch/setup
    Follow steps 1 to 3.
    At step 4 (Prepare hard drive(s), select “3 – Manually Configure block devices, filesystems and mountpoints. Choose /dev/sdb1 (the usb stick) as /boot, /dev/mapper/swap for swap, /dev/mapper/root for / and /dev/mapper/var for /var.
    Format all drives (choose “yes” when asked “do you want to have this filesystem (re)created”) EXCEPT for /dev/sdb1, choose “no”. Choose the correct filesystem for /dev/sdb1, ext2 in my case. Use swap for /dev/mapper/swap. For the rest, I chose ext4.
    Select DONE to start formatting.
    At step 5 (Select packages), select grub as boot loader. Select the base group. Add mkinitcpio.
    Start step 6 (Install packages).
    Go to step 7 (Configure System).
    By sure to set the correct KEYMAP, LOCALE and TIMEZONE in /etc/rc.conf.
    Edit /etc/fstab:
    /dev/mapper/root / ext4 defaults 0 1
    /dev/mapper/swap swap swap defaults 0 0
    /dev/mapper/var /var ext4 defaults 0 1
    # /dev/sdb1 /boot ext2 defaults 0 1
    Configure the rest normally. When you're done, setup will launch mkinitcpio. We'll manually launch this again later.
    Go to step 8 (install boot loader).
    Be sure to change the kernel line in menu.lst:
    kernel /vmlinuz26 root=/dev/mapper/root cryptdevice=/dev/sda3:root cryptkey=/dev/sdb1:ext2:/root.gpg
    Don't forget the :root suffix in cryptdevice!
    Also, my root line was set to (hd1,0). Had to change that to
    root (hd0,0)
    Install grub to /dev/sdb (the usb stick).
    Now, we can exit the installer.
    12. Install mkinitcpio with the etwo hook.
    Create /mnt/lib/initcpio/hooks/etwo:
    #!/usr/bin/ash
    run_hook() {
    /sbin/modprobe -a -q dm-crypt >/dev/null 2>&1
    if [ -e "/sys/class/misc/device-mapper" ]; then
    if [ ! -e "/dev/mapper/control" ]; then
    /bin/mknod "/dev/mapper/control" c $(cat /sys/class/misc/device-mapper/dev | sed 's|:| |')
    fi
    [ "${quiet}" = "y" ] && CSQUIET=">/dev/null"
    # Get keyfile if specified
    ckeyfile="/crypto_keyfile"
    usegpg="n"
    if [ "x${cryptkey}" != "x" ]; then
    ckdev="$(echo "${cryptkey}" | cut -d: -f1)"
    ckarg1="$(echo "${cryptkey}" | cut -d: -f2)"
    ckarg2="$(echo "${cryptkey}" | cut -d: -f3)"
    if poll_device "${ckdev}" ${rootdelay}; then
    case ${ckarg1} in
    *[!0-9]*)
    # Use a file on the device
    # ckarg1 is not numeric: ckarg1=filesystem, ckarg2=path
    if [ "${ckarg2#*.}" = "gpg" ]; then
    ckeyfile="${ckeyfile}.gpg"
    usegpg="y"
    fi
    mkdir /ckey
    mount -r -t ${ckarg1} ${ckdev} /ckey
    dd if=/ckey/${ckarg2} of=${ckeyfile} >/dev/null 2>&1
    umount /ckey
    # Read raw data from the block device
    # ckarg1 is numeric: ckarg1=offset, ckarg2=length
    dd if=${ckdev} of=${ckeyfile} bs=1 skip=${ckarg1} count=${ckarg2} >/dev/null 2>&1
    esac
    fi
    [ ! -f ${ckeyfile} ] && echo "Keyfile could not be opened. Reverting to passphrase."
    fi
    if [ -n "${cryptdevice}" ]; then
    DEPRECATED_CRYPT=0
    cryptdev="$(echo "${cryptdevice}" | cut -d: -f1)"
    cryptname="$(echo "${cryptdevice}" | cut -d: -f2)"
    else
    DEPRECATED_CRYPT=1
    cryptdev="${root}"
    cryptname="root"
    fi
    warn_deprecated() {
    echo "The syntax 'root=${root}' where '${root}' is an encrypted volume is deprecated"
    echo "Use 'cryptdevice=${root}:root root=/dev/mapper/root' instead."
    if poll_device "${cryptdev}" ${rootdelay}; then
    if /sbin/cryptsetup isLuks ${cryptdev} >/dev/null 2>&1; then
    [ ${DEPRECATED_CRYPT} -eq 1 ] && warn_deprecated
    dopassphrase=1
    # If keyfile exists, try to use that
    if [ -f ${ckeyfile} ]; then
    if [ "${usegpg}" = "y" ]; then
    # gpg tty fixup
    if [ -e /dev/tty ]; then mv /dev/tty /dev/tty.backup; fi
    cp -a /dev/console /dev/tty
    while [ ! -e /dev/mapper/${cryptname} ];
    do
    sleep 2
    /usr/bin/gpg -d "${ckeyfile}" 2>/dev/null | cryptsetup --key-file=- luksOpen ${cryptdev} ${cryptname} ${CSQUIET}
    dopassphrase=0
    done
    rm /dev/tty
    if [ -e /dev/tty.backup ]; then mv /dev/tty.backup /dev/tty; fi
    else
    if eval /sbin/cryptsetup --key-file ${ckeyfile} luksOpen ${cryptdev} ${cryptname} ${CSQUIET}; then
    dopassphrase=0
    else
    echo "Invalid keyfile. Reverting to passphrase."
    fi
    fi
    fi
    # Ask for a passphrase
    if [ ${dopassphrase} -gt 0 ]; then
    echo ""
    echo "A password is required to access the ${cryptname} volume:"
    #loop until we get a real password
    while ! eval /sbin/cryptsetup luksOpen ${cryptdev} ${cryptname} ${CSQUIET}; do
    sleep 2;
    done
    fi
    if [ -e "/dev/mapper/${cryptname}" ]; then
    if [ ${DEPRECATED_CRYPT} -eq 1 ]; then
    export root="/dev/mapper/root"
    fi
    else
    err "Password succeeded, but ${cryptname} creation failed, aborting..."
    exit 1
    fi
    elif [ -n "${crypto}" ]; then
    [ ${DEPRECATED_CRYPT} -eq 1 ] && warn_deprecated
    msg "Non-LUKS encrypted device found..."
    if [ $# -ne 5 ]; then
    err "Verify parameter format: crypto=hash:cipher:keysize:offset:skip"
    err "Non-LUKS decryption not attempted..."
    return 1
    fi
    exe="/sbin/cryptsetup create ${cryptname} ${cryptdev}"
    tmp=$(echo "${crypto}" | cut -d: -f1)
    [ -n "${tmp}" ] && exe="${exe} --hash \"${tmp}\""
    tmp=$(echo "${crypto}" | cut -d: -f2)
    [ -n "${tmp}" ] && exe="${exe} --cipher \"${tmp}\""
    tmp=$(echo "${crypto}" | cut -d: -f3)
    [ -n "${tmp}" ] && exe="${exe} --key-size \"${tmp}\""
    tmp=$(echo "${crypto}" | cut -d: -f4)
    [ -n "${tmp}" ] && exe="${exe} --offset \"${tmp}\""
    tmp=$(echo "${crypto}" | cut -d: -f5)
    [ -n "${tmp}" ] && exe="${exe} --skip \"${tmp}\""
    if [ -f ${ckeyfile} ]; then
    exe="${exe} --key-file ${ckeyfile}"
    else
    exe="${exe} --verify-passphrase"
    echo ""
    echo "A password is required to access the ${cryptname} volume:"
    fi
    eval "${exe} ${CSQUIET}"
    if [ $? -ne 0 ]; then
    err "Non-LUKS device decryption failed. verify format: "
    err " crypto=hash:cipher:keysize:offset:skip"
    exit 1
    fi
    if [ -e "/dev/mapper/${cryptname}" ]; then
    if [ ${DEPRECATED_CRYPT} -eq 1 ]; then
    export root="/dev/mapper/root"
    fi
    else
    err "Password succeeded, but ${cryptname} creation failed, aborting..."
    exit 1
    fi
    else
    err "Failed to open encryption mapping: The device ${cryptdev} is not a LUKS volume and the crypto= paramater was not specified."
    fi
    fi
    rm -f ${ckeyfile}
    fi
    Create /mnt/lib/initcpio/install/etwo:
    #!/bin/bash
    build() {
    local mod
    add_module dm-crypt
    if [[ $CRYPTO_MODULES ]]; then
    for mod in $CRYPTO_MODULES; do
    add_module "$mod"
    done
    else
    add_all_modules '/crypto/'
    fi
    add_dir "/dev/mapper"
    add_binary "cryptsetup"
    add_binary "dmsetup"
    add_binary "/usr/bin/gpg"
    add_file "/usr/lib/udev/rules.d/10-dm.rules"
    add_file "/usr/lib/udev/rules.d/13-dm-disk.rules"
    add_file "/usr/lib/udev/rules.d/95-dm-notify.rules"
    add_file "/usr/lib/initcpio/udev/11-dm-initramfs.rules" "/usr/lib/udev/rules.d/11-dm-initramfs.rules"
    add_runscript
    help ()
    cat<<HELPEOF
    This hook allows for an encrypted root device with support for gpg encrypted key files.
    To use gpg, the key file must have the extension .gpg and you have to install gpg and add /usr/bin/gpg
    to your BINARIES var in /etc/mkinitcpio.conf.
    HELPEOF
    Edit /mnt/etc/mkinitcpio.conf (only relevant sections displayed):
    MODULES=”ext2 ext4” # not sure if this is really nessecary.
    BINARIES=”/usr/bin/gpg” # this could probably be done in install/etwo...
    HOOKS=”base udev usbinput keymap autodetect pata scsi sata usb etwo filesystems” # (usbinput is only needed if you have an usb keyboard)
    Copy the initcpio stuff over to the live cd:
    cp /mnt/lib/initcpio/hooks/etwo /lib/initcpio/hooks/
    cp /mnt/lib/initcpio/install/etwo /lib/initcpio/install/
    cp /mnt/etc/mkinitcpio.conf /etc/
    Verify your LOCALE, KEYMAP and TIMEZONE in /etc/rc.conf!
    Now reinstall the initcpio:
    mkinitcpio -g /mnt/boot/kernel26.img
    Make sure there were no errors and that all hooks were included.
    13. Decrypt the "var" key to the encrypted root
    mkdir /mnt/keys
    chmod 500 /mnt/keys
    gpg –output /mnt/keys/var -d /mnt/boot/var.gpg
    chmod 400 /mnt/keys/var
    14. Setup crypttab
    Edit /mnt/etc/crypttab:
    swap /dev/sda1 SWAP -c aes-cbc-essiv:sha256 -s 256 -h whirlpool
    var /dev/sda2 /keys/var
    15. Reboot
    We're done, you may reboot. Make sure you select the usb stick as the boot device in your bios and hope for the best. . If it didn't work, play with grub's settings or boot from the live cd, mount your encrypted devices and check all settings. You might also have less trouble by using uuid's instead of device names.  I chose device names to keep things as simple as possible, even though it's not the optimal way to do it.
    Make backups of your data and your usb stick and do not forget your password(s)! Or you can say goodbye to your data forever...
    Last edited by fabriceb (2013-01-15 22:36:23)

    I'm trying to run my install script that is based on https://bbs.archlinux.org/viewtopic.php?id=129885
    Decrypting the gpg key after grub works, but then "Devce root already exists." appears every second.
    any idea ?
    #!/bin/bash
    # This script is designed to be run in conjunction with a UEFI boot using Archboot intall media.
    # prereqs:
    # EFI "BIOS" set to boot *only* from EFI
    # successful EFI boot of Archboot USB
    # mount /dev/sdb1 /src
    set -o nounset
    #set -o errexit
    # Host specific configuration
    # this whole script needs to be customized, particularly disk partitions
    # and configuration, but this section contains global variables that
    # are used during the system configuration phase for convenience
    HOSTNAME=daniel
    USERNAME=user
    # Globals
    # We don't need to set these here but they are used repeatedly throughout
    # so it makes sense to reuse them and allow an easy, one-time change if we
    # need to alter values such as the install target mount point.
    INSTALL_TARGET="/install"
    HR="--------------------------------------------------------------------------------"
    PACMAN="pacman --noconfirm --config /tmp/pacman.conf"
    TARGET_PACMAN="pacman --noconfirm --config /tmp/pacman.conf -r ${INSTALL_TARGET}"
    CHROOT_PACMAN="pacman --noconfirm --cachedir /var/cache/pacman/pkg --config /tmp/pacman.conf -r ${INSTALL_TARGET}"
    FILE_URL="file:///packages/core-$(uname -m)/pkg"
    FTP_URL='ftp://mirrors.kernel.org/archlinux/$repo/os/$arch'
    HTTP_URL='http://mirrors.kernel.org/archlinux/$repo/os/$arch'
    # Functions
    # I've avoided using functions in this script as they aren't required and
    # I think it's more of a learning tool if you see the step-by-step
    # procedures even with minor duplciations along the way, but I feel that
    # these functions clarify the particular steps of setting values in config
    # files.
    SetValue () {
    # EXAMPLE: SetValue VARIABLENAME '\"Quoted Value\"' /file/path
    VALUENAME="$1" NEWVALUE="$2" FILEPATH="$3"
    sed -i "s+^#\?\(${VALUENAME}\)=.*$+\1=${NEWVALUE}+" "${FILEPATH}"
    CommentOutValue () {
    VALUENAME="$1" FILEPATH="$2"
    sed -i "s/^\(${VALUENAME}.*\)$/#\1/" "${FILEPATH}"
    UncommentValue () {
    VALUENAME="$1" FILEPATH="$2"
    sed -i "s/^#\(${VALUENAME}.*\)$/\1/" "${FILEPATH}"
    # Initialize
    # Warn the user about impending doom, set up the network on eth0, mount
    # the squashfs images (Archboot does this normally, we're just filling in
    # the gaps resulting from the fact that we're doing a simple scripted
    # install). We also create a temporary pacman.conf that looks for packages
    # locally first before sourcing them from the network. It would be better
    # to do either *all* local or *all* network but we can't for two reasons.
    # 1. The Archboot installation image might have an out of date kernel
    # (currently the case) which results in problems when chrooting
    # into the install mount point to modprobe efivars. So we use the
    # package snapshot on the Archboot media to ensure our kernel is
    # the same as the one we booted with.
    # 2. Ideally we'd source all local then, but some critical items,
    # notably grub2-efi variants, aren't yet on the Archboot media.
    # Warn
    timer=9
    echo -e "\n\nMAC WARNING: This script is not designed for APPLE MAC installs and will potentially misconfigure boot to your existing OS X installation. STOP NOW IF YOU ARE ON A MAC.\n\n"
    echo -n "GENERAL WARNING: This procedure will completely format /dev/sda. Please cancel with ctrl-c to cancel within $timer seconds..."
    while [[ $timer -gt 0 ]]
    do
    sleep 1
    let timer-=1
    echo -en "$timer seconds..."
    done
    echo "STARTING"
    # Get Network
    echo -n "Waiting for network address.."
    #dhclient eth0
    dhcpcd -p eth0
    echo -n "Network address acquired."
    # Mount packages squashfs images
    umount "/packages/core-$(uname -m)"
    umount "/packages/core-any"
    rm -rf "/packages/core-$(uname -m)"
    rm -rf "/packages/core-any"
    mkdir -p "/packages/core-$(uname -m)"
    mkdir -p "/packages/core-any"
    modprobe -q loop
    modprobe -q squashfs
    mount -o ro,loop -t squashfs "/src/packages/archboot_packages_$(uname -m).squashfs" "/packages/core-$(uname -m)"
    mount -o ro,loop -t squashfs "/src/packages/archboot_packages_any.squashfs" "/packages/core-any"
    # Create temporary pacman.conf file
    cat << PACMANEOF > /tmp/pacman.conf
    [options]
    Architecture = auto
    CacheDir = ${INSTALL_TARGET}/var/cache/pacman/pkg
    CacheDir = /packages/core-$(uname -m)/pkg
    CacheDir = /packages/core-any/pkg
    [core]
    Server = ${FILE_URL}
    Server = ${FTP_URL}
    Server = ${HTTP_URL}
    [extra]
    Server = ${FILE_URL}
    Server = ${FTP_URL}
    Server = ${HTTP_URL}
    #Uncomment to enable pacman -Sy yaourt
    [archlinuxfr]
    Server = http://repo.archlinux.fr/\$arch
    PACMANEOF
    # Prepare pacman
    [[ ! -d "${INSTALL_TARGET}/var/cache/pacman/pkg" ]] && mkdir -m 755 -p "${INSTALL_TARGET}/var/cache/pacman/pkg"
    [[ ! -d "${INSTALL_TARGET}/var/lib/pacman" ]] && mkdir -m 755 -p "${INSTALL_TARGET}/var/lib/pacman"
    ${PACMAN} -Sy
    ${TARGET_PACMAN} -Sy
    # Install prereqs from network (not on archboot media)
    echo -e "\nInstalling prereqs...\n$HR"
    #sed -i "s/^#S/S/" /etc/pacman.d/mirrorlist # Uncomment all Server lines
    UncommentValue S /etc/pacman.d/mirrorlist # Uncomment all Server lines
    ${PACMAN} --noconfirm -Sy gptfdisk btrfs-progs-unstable libusb-compat gnupg
    # Configure Host
    # Here we create three partitions:
    # 1. efi and /boot (one partition does double duty)
    # 2. swap
    # 3. our encrypted root
    # Note that all of these are on a GUID partition table scheme. This proves
    # to be quite clean and simple since we're not doing anything with MBR
    # boot partitions and the like.
    echo -e "format\n"
    # shred -v /dev/sda
    # disk prep
    sgdisk -Z /dev/sda # zap all on disk
    #sgdisk -Z /dev/mmcb1k0 # zap all on sdcard
    sgdisk -a 2048 -o /dev/sda # new gpt disk 2048 alignment
    #sgdisk -a 2048 -o /dev/mmcb1k0
    # create partitions
    sgdisk -n 1:0:+200M /dev/sda # partition 1 (UEFI BOOT), default start block, 200MB
    sgdisk -n 2:0:+4G /dev/sda # partition 2 (SWAP), default start block, 200MB
    sgdisk -n 3:0:0 /dev/sda # partition 3, (LUKS), default start, remaining space
    #sgdisk -n 1:0:1800M /dev/mmcb1k0 # root.gpg
    # set partition types
    sgdisk -t 1:ef00 /dev/sda
    sgdisk -t 2:8200 /dev/sda
    sgdisk -t 3:8300 /dev/sda
    #sgdisk -t 1:0700 /dev/mmcb1k0
    # label partitions
    sgdisk -c 1:"UEFI Boot" /dev/sda
    sgdisk -c 2:"Swap" /dev/sda
    sgdisk -c 3:"LUKS" /dev/sda
    #sgdisk -c 1:"Key" /dev/mmcb1k0
    echo -e "create gpg file\n"
    # create gpg file
    dd if=/dev/urandom bs=512 count=4 | gpg -v --cipher-algo aes256 --digest-algo sha512 -c -a > /root/root.gpg
    echo -e "format LUKS on root\n"
    # format LUKS on root
    gpg -q -d /root/root.gpg 2>/dev/null | cryptsetup -v --key-file=- -c aes-xts-plain -s 512 --hash sha512 luksFormat /dev/sda3
    echo -e "open LUKS on root\n"
    gpg -d /root/root.gpg 2>/dev/null | cryptsetup -v --key-file=- luksOpen /dev/sda3 root
    # NOTE: make sure to add dm_crypt and aes_i586 to MODULES in rc.conf
    # NOTE2: actually this isn't required since we're mounting an encrypted root and grub2/initramfs handles this before we even get to rc.conf
    # make filesystems
    # following swap related commands not used now that we're encrypting our swap partition
    #mkswap /dev/sda2
    #swapon /dev/sda2
    #mkfs.ext4 /dev/sda3 # this is where we'd create an unencrypted root partition, but we're using luks instead
    echo -e "\nCreating Filesystems...\n$HR"
    # make filesystems
    mkfs.ext4 /dev/mapper/root
    mkfs.vfat -F32 /dev/sda1
    #mkfs.vfat -F32 /dev/mmcb1k0p1
    echo -e "mount targets\n"
    # mount target
    #mount /dev/sda3 ${INSTALL_TARGET} # this is where we'd mount the unencrypted root partition
    mount /dev/mapper/root ${INSTALL_TARGET}
    # mount target
    mkdir ${INSTALL_TARGET}
    # mkdir ${INSTALL_TARGET}/key
    # mount -t vfat /dev/mmcb1k0p1 ${INSTALL_TARGET}/key
    mkdir ${INSTALL_TARGET}/boot
    mount -t vfat /dev/sda1 ${INSTALL_TARGET}/boot
    # Install base, necessary utilities
    mkdir -p ${INSTALL_TARGET}/var/lib/pacman
    ${TARGET_PACMAN} -Sy
    ${TARGET_PACMAN} -Su base
    # curl could be installed later but we want it ready for rankmirrors
    ${TARGET_PACMAN} -S curl
    ${TARGET_PACMAN} -S libusb-compat gnupg
    ${TARGET_PACMAN} -R grub
    rm -rf ${INSTALL_TARGET}/boot/grub
    ${TARGET_PACMAN} -S grub2-efi-x86_64
    # Configure new system
    SetValue HOSTNAME ${HOSTNAME} ${INSTALL_TARGET}/etc/rc.conf
    sed -i "s/^\(127\.0\.0\.1.*\)$/\1 ${HOSTNAME}/" ${INSTALL_TARGET}/etc/hosts
    SetValue CONSOLEFONT Lat2-Terminus16 ${INSTALL_TARGET}/etc/rc.conf
    #following replaced due to netcfg
    #SetValue interface eth0 ${INSTALL_TARGET}/etc/rc.conf
    # write fstab
    # You can use UUID's or whatever you want here, of course. This is just
    # the simplest approach and as long as your drives aren't changing values
    # randomly it should work fine.
    cat > ${INSTALL_TARGET}/etc/fstab <<FSTAB_EOF
    # /etc/fstab: static file system information
    # <file system> <dir> <type> <options> <dump> <pass>
    tmpfs /tmp tmpfs nodev,nosuid 0 0
    /dev/sda1 /boot vfat defaults 0 0
    /dev/mapper/cryptswap none swap defaults 0 0
    /dev/mapper/root / ext4 defaults,noatime 0 1
    FSTAB_EOF
    # write etwo
    mkdir -p /lib/initcpio/hooks/
    mkdir -p /lib/initcpio/install/
    cp /src/etwo_hooks /lib/initcpio/hooks/etwo
    cp /src/etwo_install /lib/initcpio/install/etwo
    mkdir -p ${INSTALL_TARGET}/lib/initcpio/hooks/
    mkdir -p ${INSTALL_TARGET}/lib/initcpio/install/
    cp /src/etwo_hooks ${INSTALL_TARGET}/lib/initcpio/hooks/etwo
    cp /src/etwo_install ${INSTALL_TARGET}/lib/initcpio/install/etwo
    # write crypttab
    # encrypted swap (random passphrase on boot)
    echo cryptswap /dev/sda2 SWAP "-c aes-xts-plain -h whirlpool -s 512" >> ${INSTALL_TARGET}/etc/crypttab
    # copy configs we want to carry over to target from install environment
    mv ${INSTALL_TARGET}/etc/resolv.conf ${INSTALL_TARGET}/etc/resolv.conf.orig
    cp /etc/resolv.conf ${INSTALL_TARGET}/etc/resolv.conf
    mkdir -p ${INSTALL_TARGET}/tmp
    cp /tmp/pacman.conf ${INSTALL_TARGET}/tmp/pacman.conf
    # mount proc, sys, dev in install root
    mount -t proc proc ${INSTALL_TARGET}/proc
    mount -t sysfs sys ${INSTALL_TARGET}/sys
    mount -o bind /dev ${INSTALL_TARGET}/dev
    echo -e "umount boot\n"
    # we have to remount /boot from inside the chroot
    umount ${INSTALL_TARGET}/boot
    # Create install_efi script (to be run *after* chroot /install)
    touch ${INSTALL_TARGET}/install_efi
    chmod a+x ${INSTALL_TARGET}/install_efi
    cat > ${INSTALL_TARGET}/install_efi <<EFI_EOF
    # functions (these could be a library, but why overcomplicate things
    SetValue () { VALUENAME="\$1" NEWVALUE="\$2" FILEPATH="\$3"; sed -i "s+^#\?\(\${VALUENAME}\)=.*\$+\1=\${NEWVALUE}+" "\${FILEPATH}"; }
    CommentOutValue () { VALUENAME="\$1" FILEPATH="\$2"; sed -i "s/^\(\${VALUENAME}.*\)\$/#\1/" "\${FILEPATH}"; }
    UncommentValue () { VALUENAME="\$1" FILEPATH="\$2"; sed -i "s/^#\(\${VALUENAME}.*\)\$/\1/" "\${FILEPATH}"; }
    echo -e "mount boot\n"
    # remount here or grub et al gets confused
    mount -t vfat /dev/sda1 /boot
    # mkinitcpio
    # NOTE: intel_agp drm and i915 for intel graphics
    SetValue MODULES '\\"dm_mod dm_crypt aes_x86_64 ext2 ext4 vfat intel_agp drm i915\\"' /etc/mkinitcpio.conf
    SetValue HOOKS '\\"base udev pata scsi sata usb usbinput keymap consolefont etwo encrypt filesystems\\"' /etc/mkinitcpio.conf
    SetValue BINARIES '\\"/usr/bin/gpg\\"' /etc/mkinitcpio.conf
    mkinitcpio -p linux
    # kernel modules for EFI install
    modprobe efivars
    modprobe dm-mod
    # locale-gen
    UncommentValue de_AT /etc/locale.gen
    locale-gen
    # install and configure grub2
    # did this above
    #${CHROOT_PACMAN} -Sy
    #${CHROOT_PACMAN} -R grub
    #rm -rf /boot/grub
    #${CHROOT_PACMAN} -S grub2-efi-x86_64
    # you can be surprisingly sloppy with the root value you give grub2 as a kernel option and
    # even omit the cryptdevice altogether, though it will wag a finger at you for using
    # a deprecated syntax, so we're using the correct form here
    # NOTE: take out i915.modeset=1 unless you are on intel graphics
    SetValue GRUB_CMDLINE_LINUX '\\"cryptdevice=/dev/sda3:root cryptkey=/dev/sda1:vfat:/root.gpg add_efi_memmap i915.i915_enable_rc6=1 i915.i915_enable_fbc=1 i915.lvds_downclock=1 pcie_aspm=force quiet\\"' /etc/default/grub
    # set output to graphical
    SetValue GRUB_TERMINAL_OUTPUT gfxterm /etc/default/grub
    SetValue GRUB_GFXMODE 960x600x32,auto /etc/default/grub
    SetValue GRUB_GFXPAYLOAD_LINUX keep /etc/default/grub # comment out this value if text only mode
    # install the actual grub2. Note that despite our --boot-directory option we will still need to move
    # the grub directory to /boot/grub during grub-mkconfig operations until grub2 gets patched (see below)
    grub_efi_x86_64-install --bootloader-id=grub --no-floppy --recheck
    # create our EFI boot entry
    # bug in the HP bios firmware (F.08)
    efibootmgr --create --gpt --disk /dev/sda --part 1 --write-signature --label "ARCH LINUX" --loader "\\\\grub\\\\grub.efi"
    # copy font for grub2
    cp /usr/share/grub/unicode.pf2 /boot/grub
    # generate config file
    grub-mkconfig -o /boot/grub/grub.cfg
    exit
    EFI_EOF
    # Install EFI using script inside chroot
    chroot ${INSTALL_TARGET} /install_efi
    rm ${INSTALL_TARGET}/install_efi
    # Post install steps
    # anything you want to do post install. run the script automatically or
    # manually
    touch ${INSTALL_TARGET}/post_install
    chmod a+x ${INSTALL_TARGET}/post_install
    cat > ${INSTALL_TARGET}/post_install <<POST_EOF
    set -o errexit
    set -o nounset
    # functions (these could be a library, but why overcomplicate things
    SetValue () { VALUENAME="\$1" NEWVALUE="\$2" FILEPATH="\$3"; sed -i "s+^#\?\(\${VALUENAME}\)=.*\$+\1=\${NEWVALUE}+" "\${FILEPATH}"; }
    CommentOutValue () { VALUENAME="\$1" FILEPATH="\$2"; sed -i "s/^\(\${VALUENAME}.*\)\$/#\1/" "\${FILEPATH}"; }
    UncommentValue () { VALUENAME="\$1" FILEPATH="\$2"; sed -i "s/^#\(\${VALUENAME}.*\)\$/\1/" "\${FILEPATH}"; }
    # root password
    echo -e "${HR}\\nNew root user password\\n${HR}"
    passwd
    # add user
    echo -e "${HR}\\nNew non-root user password (username:${USERNAME})\\n${HR}"
    groupadd sudo
    useradd -m -g users -G audio,lp,optical,storage,video,games,power,scanner,network,sudo,wheel -s /bin/bash ${USERNAME}
    passwd ${USERNAME}
    # mirror ranking
    echo -e "${HR}\\nRanking Mirrors (this will take a while)\\n${HR}"
    cp /etc/pacman.d/mirrorlist /etc/pacman.d/mirrorlist.orig
    mv /etc/pacman.d/mirrorlist /etc/pacman.d/mirrorlist.all
    sed -i "s/#S/S/" /etc/pacman.d/mirrorlist.all
    rankmirrors -n 5 /etc/pacman.d/mirrorlist.all > /etc/pacman.d/mirrorlist
    # temporary fix for locale.sh update conflict
    mv /etc/profile.d/locale.sh /etc/profile.d/locale.sh.preupdate || true
    # yaourt repo (add to target pacman, not tmp pacman.conf, for ongoing use)
    echo -e "\\n[archlinuxfr]\\nServer = http://repo.archlinux.fr/\\\$arch" >> /etc/pacman.conf
    echo -e "\\n[haskell]\\nServer = http://www.kiwilight.com/\\\$repo/\\\$arch" >> /etc/pacman.conf
    # additional groups and utilities
    pacman --noconfirm -Syu
    pacman --noconfirm -S base-devel
    pacman --noconfirm -S yaourt
    # sudo
    pacman --noconfirm -S sudo
    cp /etc/sudoers /tmp/sudoers.edit
    sed -i "s/#\s*\(%wheel\s*ALL=(ALL)\s*ALL.*$\)/\1/" /tmp/sudoers.edit
    sed -i "s/#\s*\(%sudo\s*ALL=(ALL)\s*ALL.*$\)/\1/" /tmp/sudoers.edit
    visudo -qcsf /tmp/sudoers.edit && cat /tmp/sudoers.edit > /etc/sudoers
    # power
    pacman --noconfirm -S acpi acpid acpitool cpufrequtils
    yaourt --noconfirm -S powertop2
    sed -i "/^DAEMONS/ s/)/ @acpid)/" /etc/rc.conf
    sed -i "/^MODULES/ s/)/ acpi-cpufreq cpufreq_ondemand cpufreq_powersave coretemp)/" /etc/rc.conf
    # following requires my acpi handler script
    echo "/etc/acpi/handler.sh boot" > /etc/rc.local
    # time
    pacman --noconfirm -S ntp
    sed -i "/^DAEMONS/ s/hwclock /!hwclock @ntpd /" /etc/rc.conf
    # wireless (wpa supplicant should already be installed)
    pacman --noconfirm -S iw wpa_supplicant rfkill
    pacman --noconfirm -S netcfg wpa_actiond ifplugd
    mv /etc/wpa_supplicant.conf /etc/wpa_supplicant.conf.orig
    echo -e "ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=network\nupdate_config=1" > /etc/wpa_supplicant.conf
    # make sure to copy /etc/network.d/examples/wireless-wpa-config to /etc/network.d/home and edit
    sed -i "/^DAEMONS/ s/)/ @net-auto-wireless @net-auto-wired)/" /etc/rc.conf
    sed -i "/^DAEMONS/ s/ network / /" /etc/rc.conf
    echo -e "\nWIRELESS_INTERFACE=wlan0" >> /etc/rc.conf
    echo -e "WIRED_INTERFACE=eth0" >> /etc/rc.conf
    echo "options iwlagn led_mode=2" > /etc/modprobe.d/iwlagn.conf
    # sound
    pacman --noconfirm -S alsa-utils alsa-plugins
    sed -i "/^DAEMONS/ s/)/ @alsa)/" /etc/rc.conf
    mv /etc/asound.conf /etc/asound.conf.orig || true
    #if alsamixer isn't working, try alsamixer -Dhw and speaker-test -Dhw -c 2
    # video
    pacman --noconfirm -S base-devel mesa mesa-demos
    # x
    #pacman --noconfirm -S xorg xorg-xinit xorg-utils xorg-server-utils xdotool xorg-xlsfonts
    #yaourt --noconfirm -S xf86-input-wacom-git # NOT NEEDED? input-wacom-git
    #TODO: cut down the install size
    #pacman --noconfirm -S xorg-server xorg-xinit xorg-utils xorg-server-utils
    # TODO: wacom
    # environment/wm/etc.
    #pacman --noconfirm -S xfce4 compiz ccsm
    #pacman --noconfirm -S xcompmgr
    #yaourt --noconfirm -S physlock unclutter
    #pacman --noconfirm -S rxvt-unicode urxvt-url-select hsetroot
    #pacman --noconfirm -S gtk2 #gtk3 # for taffybar?
    #pacman --noconfirm -S ghc
    # note: try installing alex and happy from cabal instead
    #pacman --noconfirm -S haskell-platform haskell-hscolour
    #yaourt --noconfirm -S xmonad-darcs xmonad-contrib-darcs xcompmgr
    #yaourt --noconfirm -S xmobar-git
    # TODO: edit xfce to use compiz
    # TODO: xmonad, but deal with video tearing
    # TODO: xmonad-darcs fails to install from AUR. haskell dependency hell.
    # switching to cabal
    # fonts
    pacman --noconfirm -S terminus-font
    yaourt --noconfirm -S webcore-fonts
    yaourt --noconfirm -S fontforge libspiro
    yaourt --noconfirm -S freetype2-git-infinality
    # TODO: sed infinality and change to OSX or OSX2 mode
    # and create the sym link from /etc/fonts/conf.avail to conf.d
    # misc apps
    #pacman --noconfirm -S htop openssh keychain bash-completion git vim
    #pacman --noconfirm -S chromium flashplugin
    #pacman --noconfirm -S scrot mypaint bc
    #yaourt --noconfirm -S task-git stellarium googlecl
    # TODO: argyll
    POST_EOF
    # Post install in chroot
    #echo "chroot and run /post_install"
    chroot /install /post_install
    rm /install/post_install
    # copy grub.efi file to the default HP EFI boot manager path
    mkdir -p ${INSTALL_TARGET}/boot/EFI/Microsoft/BOOT/
    mkdir -p ${INSTALL_TARGET}/boot/EFI/BOOT/
    cp ${INSTALL_TARGET}/boot/grub/grub.efi ${INSTALL_TARGET}/boot/EFI/Microsoft/BOOT/bootmgfw.efi
    cp ${INSTALL_TARGET}/boot/grub/grub.efi ${INSTALL_TARGET}/boot/EFI/BOOT/BOOTX64.EFI
    cp /root/root.gpg ${INSTALL_TARGET}/boot/
    # NOTES/TODO

  • Encrypt/decrypt streams with same password

    Hi all!
    I'would like to know if I can encrypt/decrypt streams using key's which are hardwired in my application. By a hardwired key I understand a key which is generated using the same seed; practically I don't keep the key, but the minimum info to regenerate it.
    Is this possible and if yes, how? Where can I find some more info about regenerating a key?
    Stefan.
    PS: I'm a newbie in field of cryptography, so...

    You can use password-based encryption. See an example
    of such a thing in:
    http://javaalmanac.com/egs/javax.crypto/PassKey.html
    Erm, what sort of encryption isn't password-based ?

  • Encrypting a vote with a servers public key...HELP!

    Hey, I really need some help( online voting application)....what I want to do it allow a voter to be able to submit a ballot(vote) via servlets, they encrypt the ballot with the servers public key and then the ballot is stored in a database, where at another time the administrator may decrypt the ballot(s) using the servers private key. I have already sorted the voters authentication(MD5), and at the moment the servlet submits the ballot in an unencrypted form....so I just need a little help from here. I enclose my code and I would be truly grateful of someone could give me a hand.
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.* ;
    public class CastVote extends HttpServlet{
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException,IOException{
    try {
    String jmulligan= request.getParameter("jmulligan");
    String pkelly=request.getParameter("pkelly");
    String mjones=request.getParameter("mjones");
    response.setContentType("text/html");
    PrintWriter out=response.getWriter();
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection ("jdbc:odbc:evoting");
    Statement stmt = con.createStatement();
    stmt.executeUpdate(
    "INSERT INTO Ballot (JMulligan, PKelly, MJones)"
    + "VALUES ('"+jmulligan+"','"+pkelly+"','"+mjones+"') ");
    stmt.close();
    out.println("<HTML>\n"+
    "<HEAD><TITLE>EVoting</TITLE></HEAD>\n"+
    "<BODY BGCOLOR=\"127734\">\n"+
    "<H1>Your Ballot has been entered as follows</H1>\n"+
    "<H1>J Mulligan got "+ jmulligan +"</H1>\n"+
    "<H1> M Jones got "+ mjones +"</H1>\n"+
    "<H1> P Kelly got "+ pkelly +"</H1>\n"+
    "</BODY></HTML>");
    catch( Exception e ) {
    System.out.println(e.getMessage());
    e.printStackTrace();
    thanks
    Jacinta
    PS I have ssl configured, with a self signed cert.

    Hey!
    I am also in the middle of doing an en=voting application as part of my thesis! Its interesting to see the way other people do the voting. Well, my experience so far is that I cannot get public/private key encryption to work. I have posted many topics on this forum regarding it and the reason it wont work is that the ballot that I am trying to enctypt is too large for the ballot object . I used the RSA algoithm and it wasn't able to handle my large object. So instead I have just used a symmetric algorithm and that works fine. I think its the DES algorithm. The only problem with this is that you are using the same key to encrypt and decrypt the ballot. I dont think this is secure. It has been reccomended to me that I use this symmetric algorithm as it is, but that I then use public/private key to encrypt the symmetric key! I still have a problem with this because if the key is still encrypted with public key, the user must have acces to the private key to decrypt the symmetric key to decryt the ballot. See where I'm going?
    I would love to know of an asymmetric algorithm that can encrypt large objects. That would solve the whole security issue. I will post a replyhere if I find out the answer.
    By the way, how is your project going?
    All the best,
    Chris Moltisanti

  • Encrypt/decrypt same file with two different passwords

    Hi everyone:
    I'm quite new to Java and cryptography in general and have a theoretical question. Is the following scenario possible and how would it be implemented:
    Two users with two passwords (say, a regular user and a superuser) encrypt, decrypt, read from and write to the same file. The secret key for encryption and decryption should be based on their passwords (generated from their passwords), i.e. not stored anywhere on the system.
    I've been racking my brains but can't think of a way. Am I missing an obvious solution?
    Can it be done?
    Thanks,
    Michael

    I don't think you can avoid having more than just a password hash stored on the system. Using a combination of my approach and Jeff's approach I can implement this as long as you allow a password protected key store to be stored on each system. A given user's key store would contain his RSA private key and associated public key together with the admin user's RSA certificate (thought the admin user's public key could be stored in the program since it does not have to be kept private). The admin user's key store would contain only his RSA private and public keys.
    Assume that the data file is to be create by a standard non-admin user. His code performs the following actions -
    1) Generates a random symmetric algorithm key. Say a 128 bit AES key.
    2) He write a digest of this to the output file.
    3) He writes the random key encrypted with his public key to the file.
    4) He writes his public key (or certificate) to the file.
    5) He writes the random key encrypted with the admin users public key to the file.
    6) He encrypts the data using the random key writes the result to the file.
    This user can then update the file by
    1) reading from the file the digest of the random key.
    2) reading the random key encrypted with his public key.
    3) Decrypting this encrypted random key using his private key extracted from his keystore.
    4) Check the digest of this key to make sure he has the correct random key.
    5) skipping his certificate and the random key encrypted using the admin user's public key.
    5) Decrypting the data using the random key.
    6) Update the data.
    7) Re-encrypt the file as described in the first part using a new random key.
    The admin user can
    1) read from the file the digest of the random key.
    2) skip the random key encrypted using the user's public key.
    3) reading the user's public key from the file (for use later if the file needs to be updated).
    4) read the random key encrypted using the admin's public key.
    5) decrypting the random key using the admin's private key obtained from his key store.
    6) check the digest of the random key to make sure it is correct.
    7) decrypt the the data.
    The admin can edit the data since he can re-encrypt the data in a similar manner to the way it was created in the first place.

  • "Length is too big" IOException when using OpenSSL key/certs

    Using WLS 5.1, SP6, Solaris
    Hello one and all:
    I am trying to test WLS with SSL. I am using the OpenSSL package to act as my
    own CA and generate and sign my own server certs. I don't have any problem
    with this part.
    However, when I try to use my private key with WLS, I get this
    error upon startup:
    Java.io.IOException: Length is too big: takes 56 bytes
    at weblogic.security.ASN1.ASN1Header.inputLength(ASN1Header.java:133)
    at weblogic.security.ASN1.ASN1Header.input(ASN1Header.java:105)
    at weblogic.security.RSAPrivateKey.input(RSAPrivateKey.java:107)
    at weblogic.security.RSAPrivateKey.<init>(RSAPrivateKey.java:85)
    at weblogic.t3.srvr.SSLListenThread.<init>(SSLListenThread.java:285)
    at weblogic.t3.srvr.SSLListenThread.<init>(SSLListenThread.java:214)
    at weblogic.t3.srvr.T3Srvr.start(T3Srvr.java:1180)
    at weblogic.t3.srvr.T3Srvr.main(T3Srvr.java:827)
    at java.lang.reflect.Method.invoke(Native Method)
    at weblogic.Server.startServerDynamically(Server.java:99)
    at weblogic.Server.main(Server.java:65)
    at weblogic.NmsIpServer.main(NmsIpServer.java:13)
    Thu Mar 22 16:02:25 EET 2001:<E> <SSLListenThread> Security
    Configuration Problem with SSL server encryption Key
    (<path-to-key hidden for publication --scott>),
    java.io.IOException: Length is too big: takes 56 bytesI have read many messages on this group that indicate this same
    problem. Some of the suggestions included checking the formatting
    of the server key file for extra linefeeds, etc. I have done this.
    I even tried the OpenSSL "asn1-kludge" option. It didn't work
    either.
    So, I hope to hear from someone who has successfully used OpenSSL
    keys and certs with WLS.
    Thanks,
    --scott

    Hi.
    I had the same problem when i specified a cakey.pem file that was encrypted. For
    some reason, WLS doesnt seem to support a scheme where it prompts for a password
    to use for decryption of the private key. Try to decrypt the private key:
    openssl rsa -in cakey.pem -out ca_unsafe.pem and deploy this certificate instead,
    then it will work ;-)
    [email protected] (Scott Andrew Borton) wrote:
    Using WLS 5.1, SP6, Solaris
    Hello one and all:
    I am trying to test WLS with SSL. I am using the OpenSSL package to act
    as my
    own CA and generate and sign my own server certs. I don't have any problem
    with this part.
    However, when I try to use my private key with WLS, I get this
    error upon startup:
    Java.io.IOException: Length is too big: takes 56 bytes
    at weblogic.security.ASN1.ASN1Header.inputLength(ASN1Header.java:133)
    at weblogic.security.ASN1.ASN1Header.input(ASN1Header.java:105)
    at weblogic.security.RSAPrivateKey.input(RSAPrivateKey.java:107)
    at weblogic.security.RSAPrivateKey.<init>(RSAPrivateKey.java:85)
    at weblogic.t3.srvr.SSLListenThread.<init>(SSLListenThread.java:285)
    at weblogic.t3.srvr.SSLListenThread.<init>(SSLListenThread.java:214)
    at weblogic.t3.srvr.T3Srvr.start(T3Srvr.java:1180)
    at weblogic.t3.srvr.T3Srvr.main(T3Srvr.java:827)
    at java.lang.reflect.Method.invoke(Native Method)
    at weblogic.Server.startServerDynamically(Server.java:99)
    at weblogic.Server.main(Server.java:65)
    at weblogic.NmsIpServer.main(NmsIpServer.java:13)
    Thu Mar 22 16:02:25 EET 2001:<E> <SSLListenThread> Security
    Configuration Problem with SSL server encryption Key
    (<path-to-key hidden for publication --scott>),
    java.io.IOException: Length is too big: takes 56 bytesI have read many messages on this group that indicate this same
    problem. Some of the suggestions included checking the formatting
    of the server key file for extra linefeeds, etc. I have done this.
    I even tried the OpenSSL "asn1-kludge" option. It didn't work
    either.
    So, I hope to hear from someone who has successfully used OpenSSL
    keys and certs with WLS.
    Thanks,
    --scott

  • Why are Symmetric keys shorter than ASyemmetric keys and provide the same level of security.

    Hello
    Can someone please help me with the following question.
    Can someone please give me a brief (if possible) why Symmetric Keys which are much shorter than Asymmetric keys provide a similar level of security (e.g. take as long to crack).
    I understand RSA and can to the math with a piece of paper and the Windows advanced calculator (e.g. encrypt and decrypt a sort message using a couple of small prims likes 53 and 59).
    I also understand ( to a very basic level) AES e.g. 128bit block cypher (I believe a CBC cypher using an unpredictable IV)
    Is there a simple answer if someone says why are Symmetric keys shorted and just as secure or it is just how it is? due to the different math?
    Thank you
    AAnoterUser__
    AAnotherUser__

    Symmetric Key is used for same key for encrypsion & decryption but ASyemmetric key is used two keys (Public & private key) for
    encrysion & decryption.
    ASyemmetric
    1. If Public key is used for  encrypsion then private key is used for decryption
    2. If private key is is used for  encrypsion then public key is used for decryption.
    3. It is more secure than Syemmetric
    Regards,
    Biswajit
    MCTS, MCP 2003,MCSA 2003, MCSA:M 2003, CCNA, Enterprise Admin, ITIL F 2011
    Blog:
      Script Gallary:
      LinkedIn:
    Note: Disclaimer: This posting is provided & with no warranties or guarantees and confers no rights..

  • Safest storage of secret keys

    In the process of developing our intranet, we are storing SSN
    information as well. Since this is confidential, I want to make
    sure I take the best practices in safe-guarding it. So how would
    you go about doing it?
    I was thinking I could use GenerateSecretKey() and then use
    Encrypt with AES, but my problem arises from, "do we store the
    generated secret key in the database?) Or is it better to use a
    value in the DB we hold on that individual person for a key?
    I understand that if I store it in the DB, then additional
    security measures include having to close off who gets access to
    reading data from database tables, and that's understandable, I'm
    just trying to devise the best COLDFUSION-related practices for
    storing confidential data.
    Cause in the same manner, if someone had access to read CF
    page code, they could see something like:
    <cfset mySSN = Decrypt( strHashedValue, users.key, "AES" )
    />
    And figure out what was being done (so I have to ensure FILE
    based security as well, but again, just within the realm of CF,
    what's the best thing to do?

    Here is how I have done this in the past - but there might be
    better methods with CF8.
    Yes you have to have a key. It is vulnerable. It should be
    stored off the web root in a file (with locked down permissions) or
    on a separate database preferably on a separate server. I use a
    file. CFinclude (or otherwise externally reference) the key into
    your encryption / decryption code. You don't want to hard code the
    key into your encryption / decryption routines directly because if
    that code somehow gets exposed in an error message (which shouldn't
    happen with catch/try but.....) then your key would be exposed.
    Make sense?
    You are banking on the idea that it is very unlikely,
    assuming you have good security practices, that a hacker is going
    to crack your DB AND the file you have the key stored in.
    No security is perfect.

Maybe you are looking for