[pycrypto] Ask help for java2python rewrite for AES decrypto

steve.yi steve.yi at 139.com
Fri Dec 28 01:15:53 PST 2012





Hi Pycryptors,




I got some requests from my clients, his requests are xml formatted encrypted by AES with Java.




I decide to use pycrypto to decrypt these xml requests. But i am not familiar with Java.




Someone can help? Thanks a lot. Java codes as follows,








Encrypt.java

============







import java.io.UnsupportedEncodingException;

import java.security.SecureRandom;




import javax.crypto.Cipher;

import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;

import javax.crypto.spec.SecretKeySpec;




public class Encrypt {

	public password = "123456";

	

    public Encrypt(String password) {

		super();

		this.password = password;

	}

	/** 

     * 加密 

     *  

     * @param content 需要加密的内容 

     * @param password  加密密码 

     * @return 

     */  

    public static byte[] encrypt(String content, String password) {  

            try {             

            	

                    KeyGenerator kgen = KeyGenerator.getInstance("AES"); //AES密钥生成器

                    //128是密钥的长度  SecureRandom是随机生成数  但是我们需要摄入确定的值

                    kgen.init(128, new SecureRandom(password.getBytes()));//初始化密钥

                    SecretKey secretKey = kgen.generateKey(); //分组秘密密钥(并为其提供类型安全)

                    byte[] enCodeFormat = secretKey.getEncoded();  

                    SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); //对产生的密钥再进行封装 

                    Cipher cipher = Cipher.getInstance("AES");// 创建密码器   

                    byte[] byteContent = content.getBytes("utf-8");  //获得原文utf-8编码格式的字节数

                    cipher.init(Cipher.ENCRYPT_MODE, key);// 加密初始化   Cipher.ENCRYPT_MODE为加密

                    byte[] result = cipher.doFinal(byteContent);  //密码器执行加密 并生成加密字节数组

                    return result; // 加密   

            } catch (Exception e) {  

                    e.printStackTrace();  

            } 

            return null;  

    }  

    /**解密 

     * @param content  待解密内容 

     * @param password 解密密钥 

     * @return 

     */  

    public static String decrypt(byte[] content, String password) {  

            try {  

                     KeyGenerator kgen = KeyGenerator.getInstance("AES");  //AES密钥生成器

                     //128是密钥的长度  SecureRandom是随机生成数  但是我们需要摄入确定的值

                     kgen.init(128, new SecureRandom(password.getBytes()));  //初始化密钥

                     SecretKey secretKey = kgen.generateKey();  //分组秘密密钥(并为其提供类型安全)

                     byte[] enCodeFormat = secretKey.getEncoded();  

                     SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");  //对产生的密钥再进行封装             

                     Cipher cipher = Cipher.getInstance("AES");// 创建密码器   

                    cipher.init(Cipher.DECRYPT_MODE, key);// 解密初始化   Cipher.DECRYPT_MODE为解密

                    byte[] result = cipher.doFinal(content);  //密码器执行解密密 并生成解密密字节数组

                    return new String(result); // 解密   

            } catch (Exception e) {  

                    e.printStackTrace();  

            } 

            return null;  

    }  

    




    public static String parseByte2HexStr(byte buf[]){

    	StringBuffer sb=new StringBuffer();

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

    		String hex=Integer.toHexString(buf[i]&0xFF);

    		if(hex.length()==1){

    			hex='0' + hex;

    		}

    		sb.append(hex.toUpperCase());

    		}

    	return sb.toString();

    }

    




    public static byte[] parseHexStr2Byte(String hexStr){

    	if(hexStr.length()<1)

    		return null;

    	byte[]result=new byte[hexStr.length()/2];

    	for(int i=0;i<hexStr.length()/2;i++){

    		int high=Integer.parseInt(hexStr.substring(i*2,i*2+1),16);

    		int low=Integer.parseInt(hexStr.substring(i*2+1,i*2+2),16);

    		result[i]=(byte)(high*16+low);

    		}

    	return result;

    	}

     

    public static void main(String args[]) throws UnsupportedEncodingException {

    	String content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+

    	"<request>"+

    	  "<company>1</company>"+

    		"<requestId>2</requestId>"+

    		"<Create>"+

    			"<CreateHost>"+

    				"<userId>3</userId>"+

    				"<transactionId>4</transactionId>"+

    				"<timestamp>5</timestamp>"+

    				"<core>6</core>"+

    				"<memory>7</memory>"+

    				"<os>4</os>"+

    				"<groupName>5</groupName>"+

    				"<hostSpecId>5</hostSpecId>"+

    				"<path>6</path>"+

    			"</CreateHost>"+

    			"<CreateIp>"+

    				"<transactionId>6</transactionId>"+

    				"<netSpeed>6</netSpeed>"+

    				"<ip>7</ip>"+

    			"</CreateIp >"+

    			"<CreateDisk>"+

    				"<transactionId>7</transactionId>"+

    				"<disk>7</disk>"+

    			"</CreateDisk>"+

    		"</Create>"+

    	"</request>";

    	System.out.println("content:"+content);

    	System.out.println("encrypted:"+(parseByte2HexStr(Encrypt.encrypt(content, "123456"))));

    	System.out.println("decrypted:"+Encrypt.decrypt(parseHexStr2Byte(parseByte2HexStr(Encrypt.encrypt(content, "123456"))),"123456"));

    }

    




}




-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.dlitz.net/pipermail/pycrypto/attachments/20121228/c0202dac/attachment-0001.html>


More information about the pycrypto mailing list