package com.imchooser.map.util;


import java.awt.p_w_picpath.BufferedImage;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.security.KeyPair;

import java.security.KeyPairGenerator;

import java.security.NoSuchAlgorithmException;

import java.security.interfaces.RSAPrivateKey;

import java.security.interfaces.RSAPublicKey;

import java.util.Hashtable;


import javax.crypto.Cipher;

import javax.p_w_picpathio.ImageIO;


import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;


import com.google.zxing.BarcodeFormat;

import com.google.zxing.BinaryBitmap;

import com.google.zxing.DecodeHintType;

import com.google.zxing.LuminanceSource;

import com.google.zxing.MultiFormatReader;

import com.google.zxing.MultiFormatWriter;

import com.google.zxing.ReaderException;

import com.google.zxing.Result;

import com.google.zxing.client.j2se.BufferedImageLuminanceSource;

import com.google.zxing.common.ByteMatrix;

import com.google.zxing.common.HybridBinarizer;

import com.imchooser.framework.util.DBUtil;

import com.imchooser.framework.util.SeqFactory;

import com.imchooser.map.Constants;

import com.imchooser.sys.util.Util;

/**

* 二维码生成与解析(包含信息加密解密)

* @author wangxianchao datetime 2010-6-10

*/

public class barcodeUtil {

private static Log LOG = LogFactory.getLog(barcodeUtil.class);


private static final int BLACK = 0xff000000;

private static final int WHITE = 0xFFFFFFFF;

/**

* 生成密钥

* @return

*/

public static String scKeyT(){

KeyPairGenerator keyPairGen;

String wjj = SeqFactory.getNewSequenceAlone();

try {

keyPairGen = KeyPairGenerator.getInstance("RSA");

keyPairGen.initialize(3200);

KeyPair keyPair = keyPairGen.generateKeyPair();

RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

File file = new File(Util.getAppRootPath()+Constants.MY_LJ+"/"+wjj);


if (!file.exists()) {

file.mkdirs();

}

FileOutputStream fos1;

FileOutputStream fos2;

try {

fos1 = new FileOutputStream(Util.getAppRootPath()+Constants.MY_LJ+"/"+wjj+"/"+Constants.MY_SYMC);

fos2 = new FileOutputStream(Util.getAppRootPath()+Constants.MY_LJ+"/"+wjj+"/"+Constants.MY_GYMC);

ObjectOutputStream oos1;

ObjectOutputStream oos2;

try {

oos1 = new ObjectOutputStream(fos1);

oos1.writeObject(privateKey);

oos2 = new ObjectOutputStream(fos2);

oos2.writeObject(publicKey);

} catch (IOException e) {

LOG.error(e);

}

} catch (FileNotFoundException e) {

LOG.error(e);

}

} catch (NoSuchAlgorithmException e) {

LOG.error(e);

}

return wjj;

}

/**

* 删除密钥

* @param wjj

*/

public static void deletefile(String wjj) {

//删除密钥

File file = new File(Util.getAppRootPath()+Constants.MY_LJ+"/"+wjj+"/"+Constants.MY_SYMC);

File file1 = new File(Util.getAppRootPath()+Constants.MY_LJ+"/"+wjj+"/"+Constants.MY_GYMC);

// 如果文件路径所对应的文件存在,并且是一个文件,则直接删除

file.delete();

file1.delete();

}

/**

* 加密

* @param str

* @return

*/

public static void jm(String ycpwid,String str2,String wjj,String path){

//byte[] e = encrypt(publicKey, str.getBytes());

String wid = SeqFactory.getNewSequenceAlone()+BhGenerator.getJmmPrev();

DBUtil.executeSQL("update t_ticket_ycqy_ycpxx set ypzd='"+wid+"' where wid='"+ycpwid+"'");

String str = wid.substring(0,14) + BhGenerator.getJmmPrev() + wid.substring(14) + "," + str2.split(";")[0];

encode(str,path);

}

/**

* 解密

* @param str

* @return

*/

public static String jem(String str,String wjj,String path){

FileInputStream fos1;

try {

fos1 = new FileInputStream(Util.getAppRootPath()+Constants.MY_LJ+"/"+wjj+"/"+Constants.MY_SYMC);

ObjectInputStream oos1;

try {

oos1 = new ObjectInputStream(fos1);

try {

RSAPrivateKey privateKey = (RSAPrivateKey)oos1.readObject();

byte[] de = decrypt(privateKey, stringToBytes(str));

str = unescape(bytesToString(de));

} catch (ClassNotFoundException e) {

LOG.error(e);

}

} catch (IOException e) {

LOG.error(e);

}

} catch (FileNotFoundException e) {

LOG.error(e);

}

return str;

}

/**

* 将字节数组转换成字符串

* @param encrytpString

* @return

*/

protected static String bytesToString(byte[] encrytpByte) {

String result = "";

for (Byte bytes : encrytpByte) {

result += (char) bytes.intValue();

}

return result;

}

/**

* 将字符串转换成字节数组

* @param encrytpByte

* @return

*/

protected static byte[] stringToBytes(String encrytpString) {

char[] chs = encrytpString.toCharArray();

byte[] result = new byte[chs.length];

for (int i = 0;i<chs.length;i++) {

result[i] = (byte)chs[i];

}

return result;

}


/**

* 加密字符串(参数--字节数组)

* @param publicKey

* @param obj

* @return

*/

protected static byte[] encrypt(RSAPublicKey publicKey, byte[] obj) {

if (publicKey != null) {

try {

Cipher cipher = Cipher.getInstance("RSA");

cipher.init(Cipher.ENCRYPT_MODE, publicKey);

return cipher.doFinal(obj);

} catch (Exception e) {

e.printStackTrace();

}

}

return null;

}


/**

* 解密字符串(参数--字节数组)

* @param privateKey

* @param obj

* @return

*/

protected static byte[] decrypt(RSAPrivateKey privateKey, byte[] obj) {

if (privateKey != null) {

try {

Cipher cipher = Cipher.getInstance("RSA");

cipher.init(Cipher.DECRYPT_MODE, privateKey);

return cipher.doFinal(obj);

} catch (Exception e) {

e.printStackTrace();

}

}

return null;

}

/**

* 对字符串转换成二维码

* @param str

*/

public static void encode(String str,String path) {

try {

ByteMatrix byteMatrix;

byteMatrix = new MultiFormatWriter().encode(str,

BarcodeFormat.QR_CODE, 100, 100);

File file = new File(path);

writeToFile(byteMatrix, "png", file);

} catch (Exception e) {

e.printStackTrace();

}

}


/**

* 将文件已图片形式输出

* @param matrix

* @param format 输出的图片格式

* @param file 输出图片文件地址

* @throws IOException

*/

public static void writeToFile(ByteMatrix matrix, String format, File file)

throws IOException {

BufferedImage p_w_picpath = toBufferedImage(matrix);

ImageIO.write(p_w_picpath, format, file);

}


/**

* 生成图片流

* @param matrix

*/

public static BufferedImage toBufferedImage(ByteMatrix matrix) {

int width = matrix.getWidth();

int height = matrix.getHeight();

BufferedImage p_w_picpath = new BufferedImage(width, height,

BufferedImage.TYPE_INT_ARGB);

for (int x = 0; x < width; x++) {

for (int y = 0; y < height; y++) {

p_w_picpath.setRGB(x, y, matrix.get(x, y) == 0 ? BLACK : WHITE);

}

}

return p_w_picpath;

}

/**

* 将二维码图片解析成字符串返回

* @return

*/

@SuppressWarnings("unchecked")

public static String decode(){

try{

  String imgPath = "E:\\20110815132847104881.png";

  File file = new File(imgPath);

  BufferedImage p_w_picpath;

  try {

   p_w_picpath = ImageIO.read(file);

   if (p_w_picpath == null) {

   System.out.println("Could not decode p_w_picpath");

   }

   LuminanceSource source = new BufferedImageLuminanceSource(p_w_picpath);

   BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

   Result result;

   Hashtable hints= new Hashtable();

   hints.put(DecodeHintType.CHARACTER_SET, "utf-8");

   //解码设置编码方式为:utf-8,

   result = new MultiFormatReader().decode(bitmap,hints);

   String resultStr = result.getText();

   System.out.println("解析后内容:"+resultStr);

   return resultStr;


  } catch (IOException ioe) {

   System.out.println(ioe.toString());

  } catch (ReaderException re) {

   System.out.println(re.toString());

  }


 }catch(Exception ex){

  System.out.println(ex.toString());

 }

 return null;

}

/**

* 转码

*

* @param src

* @return

*/

public static String escape(String src) {

int i;

char j;

StringBuffer tmp = new StringBuffer();

tmp.ensureCapacity(src.length() * 6);

// 遍历,对源字符串每一位进行转码

for (i = 0; i < src.length(); i++) {

j = src.charAt(i);

// 数字,字符不需要转码

if (Character.isDigit(j) || Character.isLowerCase(j)

|| Character.isUpperCase(j))

tmp.append(j);

// ascil码转码

else if (j < 256) {

tmp.append("%");

if (j < 16)

tmp.append("0");

tmp.append(Integer.toString(j, 16));

} else

// 其他转码

{

tmp.append("%u");

tmp.append(Integer.toString(j, 16));

}

}

return tmp.toString();

}


/**

* 解码

*

* @param src

* @return

*/

public static String unescape(String src) {

StringBuffer tmp = new StringBuffer();

tmp.ensureCapacity(src.length());

int lastPos = 0, pos = 0;

char ch;

// 查找%,进行解码

while (lastPos < src.length()) {

pos = src.indexOf("%", lastPos);

// 是经过转玛的字符

if (pos == lastPos) {

if (src.charAt(pos + 1) == 'u')// 是中文

{

ch = (char) Integer.parseInt(src

.substring(pos + 2, pos + 6), 16);

tmp.append(ch);

lastPos = pos + 6;

} else

// 是ascil码

{

ch = (char) Integer.parseInt(src

.substring(pos + 1, pos + 3), 16);

tmp.append(ch);

lastPos = pos + 3;

}

} else

// 不需要解码

{

if (pos == -1) {

tmp.append(src.substring(lastPos));

lastPos = src.length();

} else {

tmp.append(src.substring(lastPos, pos));

lastPos = pos;

}

}

}

return tmp.toString();

}

public static void main(String[] args) {

decode();

//encode("121","E:\\test1.png");

//String str= "12345";

//System.out.println(str.substring(0,3)+BhGenerator.getJmmPrev()+str.substring(3));

}

}