Skip to content

Commit

Permalink
代码优化
Browse files Browse the repository at this point in the history
  • Loading branch information
闫逍旭 committed Mar 8, 2016
1 parent 39742bc commit 2458ea7
Show file tree
Hide file tree
Showing 9 changed files with 106 additions and 46 deletions.
Expand Up @@ -21,41 +21,37 @@ public abstract class BaseMessage implements Message {
protected final Connection connection; protected final Connection connection;


public BaseMessage(Packet packet, Connection connection) { public BaseMessage(Packet packet, Connection connection) {
Profiler.enter("start decode message"); this.packet = packet;
try{ this.connection = connection;
this.packet = packet; Profiler.enter("start decode message");
this.connection = connection; try {
this.decodeBody(); decodeBody();
}finally{ } finally {
Profiler.release(); Profiler.release();
} }
} }


protected void decodeBody() { protected void decodeBody() {

if (packet.body != null && packet.body.length > 0) { if (packet.body != null && packet.body.length > 0) {
//1.解密 //1.解密
byte[] tmp = packet.body; byte[] tmp = packet.body;
if (packet.hasFlag(Packet.FLAG_CRYPTO)) { if (packet.hasFlag(Packet.FLAG_CRYPTO)) {
SessionContext info = connection.getSessionContext(); if (connection.getSessionContext().cipher != null) {
if (info.cipher != null) { tmp = connection.getSessionContext().cipher.decrypt(tmp);
tmp = info.cipher.decrypt(tmp);
} }
} }
//2.解压 //2.解压
if (packet.hasFlag(Packet.FLAG_COMPRESS)) { if (packet.hasFlag(Packet.FLAG_COMPRESS)) {
byte[] result = IOUtils.uncompress(tmp); tmp = IOUtils.uncompress(tmp);
if (result.length > 0) {
tmp = result;
}
} }

if (tmp.length == 0) { if (tmp.length == 0) {
throw new RuntimeException("message decode ex"); throw new RuntimeException("message decode ex");
} }

packet.body = tmp; packet.body = tmp;
decode(packet.body); decode(packet.body);
} }

} }


protected void encodeBody() { protected void encodeBody() {
Expand Down
17 changes: 8 additions & 9 deletions mpush-tools/src/main/java/com/shinemo/mpush/tools/IOUtils.java
Expand Up @@ -26,10 +26,9 @@ public static void close(Closeable closeable) {
} }
} }



public static byte[] compress(byte[] data) { public static byte[] compress(byte[] data) {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(data.length / 4);
DeflaterOutputStream zipOut = new DeflaterOutputStream(byteStream); DeflaterOutputStream zipOut = new DeflaterOutputStream(out);
try { try {
zipOut.write(data); zipOut.write(data);
zipOut.finish(); zipOut.finish();
Expand All @@ -40,23 +39,23 @@ public static byte[] compress(byte[] data) {
} finally { } finally {
close(zipOut); close(zipOut);
} }
return byteStream.toByteArray(); return out.toByteArray();
} }


public static byte[] uncompress(byte[] data) { public static byte[] uncompress(byte[] data) {
InflaterInputStream in = new InflaterInputStream(new ByteArrayInputStream(data)); InflaterInputStream zipIn = new InflaterInputStream(new ByteArrayInputStream(data));
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(data.length * 4);
byte[] buffer = new byte[data.length * 2]; byte[] buffer = new byte[1024];
int length; int length;
try { try {
while ((length = in.read(buffer)) != -1) { while ((length = zipIn.read(buffer)) != -1) {
out.write(buffer, 0, length); out.write(buffer, 0, length);
} }
} catch (IOException e) { } catch (IOException e) {
LOGGER.error("uncompress ex", e); LOGGER.error("uncompress ex", e);
return Constants.EMPTY_BYTES; return Constants.EMPTY_BYTES;
} finally { } finally {
close(in); close(zipIn);
} }
return out.toByteArray(); return out.toByteArray();
} }
Expand Down
Expand Up @@ -3,7 +3,7 @@
/** /**
* Created by ohun on 2015/12/23. * Created by ohun on 2015/12/23.
*/ */
public class Strings { public final class Strings {
public static final String EMPTY = ""; public static final String EMPTY = "";


public static boolean isBlank(CharSequence text) { public static boolean isBlank(CharSequence text) {
Expand Down
Expand Up @@ -24,7 +24,7 @@ public interface ConfigCenter extends Config {
int maxPacketSize(); int maxPacketSize();


@Key("compress_limit") @Key("compress_limit")
@DefaultValue("10240") @DefaultValue("1024")
int compressLimit(); int compressLimit();


@Key("min_heartbeat") @Key("min_heartbeat")
Expand Down
Expand Up @@ -25,7 +25,7 @@ public final class AESUtils {
* <p> * <p>
* 生成密钥 * 生成密钥
* </p> * </p>
* *
* @param seed 密钥种子 * @param seed 密钥种子
* @return * @return
* @throws Exception * @throws Exception
Expand All @@ -36,7 +36,7 @@ public static SecretKey getSecretKey(byte[] seed) throws Exception {
keyGenerator.init(secureRandom); keyGenerator.init(secureRandom);
return keyGenerator.generateKey(); return keyGenerator.generateKey();
} }

public static byte[] encrypt(byte[] data, byte[] encryptKey, byte[] iv) { public static byte[] encrypt(byte[] data, byte[] encryptKey, byte[] iv) {
IvParameterSpec zeroIv = new IvParameterSpec(iv); IvParameterSpec zeroIv = new IvParameterSpec(iv);
SecretKeySpec key = new SecretKeySpec(encryptKey, KEY_ALGORITHM); SecretKeySpec key = new SecretKeySpec(encryptKey, KEY_ALGORITHM);
Expand All @@ -49,8 +49,6 @@ public static byte[] encrypt(byte[] data, byte[] encryptKey, byte[] iv) {
throw new RuntimeException("AES encrypt ex", e); throw new RuntimeException("AES encrypt ex", e);
} }
} }




public static byte[] decrypt(byte[] data, byte[] decryptKey, byte[] iv) { public static byte[] decrypt(byte[] data, byte[] decryptKey, byte[] iv) {
IvParameterSpec zeroIv = new IvParameterSpec(iv); IvParameterSpec zeroIv = new IvParameterSpec(iv);
Expand Down
Expand Up @@ -14,13 +14,13 @@
/** /**
* Created by ohun on 2015/12/25. * Created by ohun on 2015/12/25.
*/ */
public class MD5Utils { public final class MD5Utils {
public static String encrypt(File file) { public static String encrypt(File file) {
InputStream in = null; InputStream in = null;
try { try {
MessageDigest digest = MessageDigest.getInstance("MD5"); MessageDigest digest = MessageDigest.getInstance("MD5");
in = new FileInputStream(file); in = new FileInputStream(file);
byte[] buffer = new byte[10240];//10k byte[] buffer = new byte[1024];//10k
int readLen; int readLen;
while ((readLen = in.read(buffer)) != -1) { while ((readLen = in.read(buffer)) != -1) {
digest.update(buffer, 0, readLen); digest.update(buffer, 0, readLen);
Expand Down Expand Up @@ -55,7 +55,7 @@ public static String encrypt(byte[] bytes) {
} }


private static String toHex(byte[] bytes) { private static String toHex(byte[] bytes) {
StringBuffer buffer = new StringBuffer(bytes.length * 2); StringBuilder buffer = new StringBuilder(bytes.length * 2);


for (int i = 0; i < bytes.length; ++i) { for (int i = 0; i < bytes.length; ++i) {
buffer.append(Character.forDigit((bytes[i] & 240) >> 4, 16)); buffer.append(Character.forDigit((bytes[i] & 240) >> 4, 16));
Expand Down
Expand Up @@ -25,7 +25,7 @@
* 由于非对称加密速度极其缓慢,一般文件不使用它来加密而是使用对称加密,<br/> * 由于非对称加密速度极其缓慢,一般文件不使用它来加密而是使用对称加密,<br/>
* 非对称加密算法可以用来对对称加密的密钥加密,这样保证密钥的安全也就保证了数据的安全 * 非对称加密算法可以用来对对称加密的密钥加密,这样保证密钥的安全也就保证了数据的安全
*/ */
public class RSAUtils { public final class RSAUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(RSAUtils.class); private static final Logger LOGGER = LoggerFactory.getLogger(RSAUtils.class);


/** /**
Expand Down Expand Up @@ -237,7 +237,7 @@ public static byte[] decryptByPrivateKey(byte[] data, RSAPrivateKey privateKey)
return doFinal(cipher, data, key_len); return doFinal(cipher, data, key_len);
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("decryptByPrivateKey ex", e); LOGGER.error("decryptByPrivateKey ex", e);
throw new RuntimeException("RSA encrypt ex", e); throw new RuntimeException("RSA decrypt ex", e);
} }
} }


Expand All @@ -253,9 +253,9 @@ public static byte[] decryptByPrivateKey(byte[] data, RSAPrivateKey privateKey)
* @throws IllegalBlockSizeException * @throws IllegalBlockSizeException
*/ */
private static byte[] doFinal(Cipher cipher, byte[] data, int key_len) throws BadPaddingException, IllegalBlockSizeException { private static byte[] doFinal(Cipher cipher, byte[] data, int key_len) throws BadPaddingException, IllegalBlockSizeException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int inputLen = data.length, offSet = 0; int inputLen = data.length, offSet = 0;
byte[] tmp; byte[] tmp;
ByteArrayOutputStream out = new ByteArrayOutputStream(getTmpArrayLength(inputLen));
while (inputLen > 0) { while (inputLen > 0) {
tmp = cipher.doFinal(data, offSet, Math.min(key_len, inputLen)); tmp = cipher.doFinal(data, offSet, Math.min(key_len, inputLen));
out.write(tmp, 0, tmp.length); out.write(tmp, 0, tmp.length);
Expand All @@ -265,6 +265,12 @@ private static byte[] doFinal(Cipher cipher, byte[] data, int key_len) throws Ba
return out.toByteArray(); return out.toByteArray();
} }


private static int getTmpArrayLength(int L) {
int S = MAX_DECRYPT_BLOCK;
while (S < L) S <<= 1;
return S;
}

/** /**
* 私钥解密 * 私钥解密
* *
Expand Down
61 changes: 61 additions & 0 deletions mpush-tools/src/test/java/com/shinemo/mpush/tools/IOUtilsTest.java
@@ -0,0 +1,61 @@
package com.shinemo.mpush.tools;

import org.junit.Test;

import static org.junit.Assert.*;

/**
* Created by ohun on 2016/3/8.
*/
public class IOUtilsTest {

@Test
public void testCompress() throws Exception {
byte[] s = ("士大夫士大大啊实打实大苏打撒" +
"阿斯顿撒大苏打实打实的苏打似的啊实" +
"打实大苏打实打实大苏打水水" +
"打实大苏打实打实大苏打水水" +
"打实大苏打实打实大苏打水水" +
"打实大苏打实打实大苏打水水" +
"打实大苏打实打实大苏打水水" +
"打实大苏打实打实大苏打水水" +
"打实大苏打实打实大苏打水水" +
"打实大苏打实打实大苏打水水" +
"打实大苏打实打实大苏打水水" +
"打实大苏打实打实大苏打水水" +
"打实大苏打实打实大苏打水水" +
"打实大苏打实打实大苏打水水" +
"打实大苏打实打实大苏打水水" +
"打实大苏打实打实大苏打水水" +
"打实大苏打实打实大苏打水水" +
"打实大苏打实打实大苏打水水" +
"打实大苏打实打实大苏打水水" +
"打实大苏打实打实大苏打水水" +
"打实大苏打实打实大苏打水水" +
"打实大苏打实打实大苏打水水" +
"打实大苏打实打实大苏打水水" +
"打实大苏打实打实大苏打水水" +
"打实大苏打实打实大苏打水水" +
"打实大苏打实打实大苏打水水" +
"打实大苏打实打实大苏打水水" +
"打实大苏打实打实大苏打水水" +
"打实大苏打实打实大苏打水水" +
"打实大苏打实打实大苏打水水" +
"水水水水夫").getBytes();
long t1 = System.currentTimeMillis();
for (int i = 0; i < 100; i++) {
IOUtils.compress(s);
}
System.out.println((System.currentTimeMillis()-t1));
System.out.println("src:" + s.length);
byte[] out = IOUtils.compress(s);
System.out.println("compress:" + out.length);
byte[] ss = IOUtils.uncompress(out);
System.out.println("uncompress:" + ss.length);
}

@Test
public void testUncompress() throws Exception {

}
}
Expand Up @@ -15,7 +15,7 @@
public class RSAUtilsTest { public class RSAUtilsTest {
String publicKey; String publicKey;
String privateKey; String privateKey;

String publicKey2; String publicKey2;
String privateKey2; String privateKey2;


Expand All @@ -27,7 +27,7 @@ public void setUp() throws Exception {
privateKey = RSAUtils.encodeBase64(pair.value); privateKey = RSAUtils.encodeBase64(pair.value);
System.out.println("公钥: \n\r" + publicKey); System.out.println("公钥: \n\r" + publicKey);
System.out.println("私钥: \n\r" + privateKey); System.out.println("私钥: \n\r" + privateKey);

pair = RSAUtils.genKeyPair(); pair = RSAUtils.genKeyPair();
publicKey2 = RSAUtils.encodeBase64(pair.key); publicKey2 = RSAUtils.encodeBase64(pair.key);
privateKey2 = RSAUtils.encodeBase64(pair.value); privateKey2 = RSAUtils.encodeBase64(pair.value);
Expand All @@ -38,23 +38,23 @@ public void setUp() throws Exception {


@Test @Test
public void testGetKeys() throws Exception { public void testGetKeys() throws Exception {
String source = "这是一行测试RSA数字签名的无意义文字"; String source = "这是一行测试RSA数字签名的无意义文字";
byte[] data = source.getBytes(); byte[] data = source.getBytes();
byte[] encodedData = RSAUtils.encryptByPublicKey(data, publicKey); byte[] encodedData = RSAUtils.encryptByPublicKey(data, publicKey);
System.out.println("加密后:\n" + new String(encodedData)); System.out.println("加密后:\n" + new String(encodedData));
byte[] decodedData = RSAUtils.decryptByPrivateKey(encodedData, privateKey); byte[] decodedData = RSAUtils.decryptByPrivateKey(encodedData, privateKey);
String target = new String(decodedData); String target = new String(decodedData);
System.out.println("解密后:\n" + target); System.out.println("解密后:\n" + target);

decodedData = RSAUtils.decryptByPrivateKey(encodedData, privateKey2); decodedData = RSAUtils.decryptByPrivateKey(encodedData, privateKey2);
target = new String(decodedData); target = new String(decodedData);
System.out.println("解密后2:\n" + target); System.out.println("解密后2:\n" + target);

} }


@Test @Test
public void testGetPrivateKey() throws Exception { public void testGetPrivateKey() throws Exception {
System.out.println("公钥: \n\r" + publicKey); System.out.println("公钥: \n\r" + publicKey);
System.out.println("私钥: \n\r" + privateKey); System.out.println("私钥: \n\r" + privateKey);
} }


Expand Down Expand Up @@ -91,7 +91,7 @@ public void test1() throws Exception {
System.out.println("加密后文字:\r\n" + new String(encodedData)); System.out.println("加密后文字:\r\n" + new String(encodedData));
byte[] decodedData = RSAUtils.decryptByPrivateKey(encodedData, privateKey); byte[] decodedData = RSAUtils.decryptByPrivateKey(encodedData, privateKey);
String target = new String(decodedData); String target = new String(decodedData);
System.out.println("解密后文字: \r\n" + target); System.out.println("解密后文字: \r\n" + target + ", 明文长度:" + data.length + ", 密文长度:" + encodedData.length);
} }


@Test @Test
Expand Down

0 comments on commit 2458ea7

Please sign in to comment.