Package pojo.util

Source Code of pojo.util.EncDecHelper

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pojo.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
*
* @author Andy
*/
public class EncDecHelper {

   

    private final Cipher cipher;
    private final SecretKey key;
    final File f = new File(System.getProperty("user.dir") + File.separator + "test.math");

    public EncDecHelper(byte[] in) throws InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException {
        //byte[] in = keyP.getBytes("UTF8");
        //System.err.println(in.length);
//        if(in.length  24){
//            in = new byte[];
//
//        }
        final DESKeySpec keySpec = new DESKeySpec(in);
        final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        key = keyFactory.generateSecret(keySpec);

        cipher = Cipher.getInstance("DES");//"DES/ECB/PKCS5Padding");//"DES"); // cipher is not thread safe


    }

    public String add(String name, String value) {
        try {
            cipher.init(Cipher.ENCRYPT_MODE, key);

            final sun.misc.BASE64Encoder base64encoder = new BASE64Encoder();

//            I think that we should pull out everything from the file, decrypt it,
//             append the new text to it, then encrypt it all and save it
            final String readText = readText();
            //final String fullText = readText() + name + "\t" + value + "\n";

            // ENCODE plainTextPassword String
            byte[] cleartext = base64encoder.encode((readText + name + "\t" + value + "\n").getBytes("UTF8")).getBytes("UTF8");

//            String junk = "";
//            while(cleartext.length % 8 != 0){
//                junk += "-";
//                cleartext = (readText + name + "\t" + value + junk + "\n").getBytes("UTF8");
//            }

            for(byte b : cleartext){
                System.out.println("-" + b + "-");
            }

            System.out.println("length of clearText: " + cleartext.length);

            //byte[] bIn = cipher.doFinal(fullText.getBytes("UTF-8"));
            final String encrypedPwd = base64encoder.encode(cipher.doFinal(cleartext));

            // now you can store it
            writeText(encrypedPwd);

            return encrypedPwd;


            //System.out.println("EncDecHelper.test(...): " + encrypedPwd);

        } catch (Exception e) {
            System.err.println("exception in add(...): " + e);
        }

        //this is too bad:
        return "";
    }

    private void mkFile() throws Exception {
        if(!f.exists() && !f.createNewFile()){
            throw new Exception("file doesn't exist and can't create it: " + f.getAbsolutePath());
        }
    }

    public String readText() {

      

        final sun.misc.BASE64Decoder base64decoder = new BASE64Decoder();
        // DECODE encryptedPwd String
        //what about encoding of scanner (utf8?) - maybe we should just open a file stream and read bytes, sounds safer
        final Scanner s;
        try {
             mkFile();
            s = new Scanner(f, "UTF-8");
            final StringBuffer t = new StringBuffer();

            while (s.hasNext()) {
                t.append(s.next());
            }

            final byte[] encrypedPwdBytes = base64decoder.decodeBuffer(t.toString());

            cipher.init(Cipher.DECRYPT_MODE, key);

            byte[] plainTextPwdBytes = (cipher.doFinal(encrypedPwdBytes));

            //System.out.println("EncDecHelper.test(...): " + encrypedPwd + " - ");
           
            final StringBuffer o = new StringBuffer();
            for (byte b : plainTextPwdBytes) {
                o.append(b);
            }
            return o.toString();
        } catch (Exception ex) {
            Logger.getLogger(EncDecHelper.class.getName()).log(Level.SEVERE, null, ex);
        }

        //bad news:
        return "";

    }

    private void writeText(String encrypedPwd) throws Exception {
       
        if(f.exists()){
            if(!f.delete()){
                throw new Exception("file not deleted");
            }
        }

        mkFile();
       

        final BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF-8"));
       
        try{
            bufferedWriter.write(encrypedPwd);
        }finally{
            bufferedWriter.close();
        }

    }


//    private Cipher rc4;
//private SecretKey rc4key;
//public EncDecHelper(String key) {
//    try {
//    rc4 = Cipher.getInstance("RC4");
//    rc4key = new SecretKeySpec(key.getBytes(), "RC4");
//    } catch(Exception e) {
//    e.printStackTrace();
//    }
//
//    //rc4key.toString();
//    //rc4.
//}
//    public void testEncryptsUsingDesEde() throws Exception {
//        String stringToEncrypt = "test";
//        String encryptionKey = "123456789012345678901234567890";
//
//        EncryptionScheme encryptionScheme = DesEdeEncryptionScheme.INSTANCE;
//
//        StringEncrypter encrypter =
//                new StringEncrypter(encryptionScheme, encryptionKey);
//        String encryptedString = encrypter.encrypt(stringToEncrypt);
//
//        assertEquals("Ni2Bih3nCUU=", encryptedString);
//    }
//
//    public void testDecryptsUsingDesEde() throws Exception {
//        String string = "Ni2Bih3nCUU=";
//        String encryptionKey = "123456789012345678901234567890";
//        EncryptionScheme encryptionScheme = DesEdeEncryptionScheme.INSTANCE;
//
//        StringEncrypter encrypter =
//                new StringEncrypter(encryptionScheme, encryptionKey);
//        String decryptedString = encrypter.decrypt(string);
//
//        assertEquals("test", decryptedString);
//    }
}
TOP

Related Classes of pojo.util.EncDecHelper

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.