您的位置:首页 > 其它

URL编码解码以及常见压缩算法和加密

2015-10-17 09:34 946 查看
1) 将客户端在进行网址请求的时候,如果网址中使用了非ASCII码形式的内。比如百度可以使用中文搜索但是sougou搜索那么就需要进行编码

2)URLEncoding:在编码的时候保留所有的英文字母、数字、下划线、以及特定的字符,这些字符全都是ASCII中的,除此之外将会转换成十六进制,并且将会在每一个十六进制之前加上%。

3)内容中的“ ”空格全都采用“+” 代替

4)URLEncoding就是为了将网址中的非ASCII的内容转换成可以传输的字符;

5)注意多有的GET请求的网址中的参数。以及post请求中的请求参数都要进行Decoding

@Override
public void run() {
try {
String word = URLEncoder.encode("T am a变形金刚","utf-8");

Log.d("De",word);
//---------------------------------
//URLEncoder的解码
String query = URLDecoder.decode(word, "utf-8");
Log.d("DE","解码  "+ query);

URL url = new URL("http://news.baidu.com/ns?word="+word);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

int code = conn.getResponseCode();
Log.d("De", "联网的状态码: "+code);

if(code == 200){
//TODO 进行内容的获取
byte[] bytes = StreamUtil.readStream(conn.getInputStream());
String str = new String (bytes,"utf-8");
Log.d("De", "联网的状态码: "+str);

}

conn.disconnect();

} catch (Exception e) {
e.printStackTrace();
}
}


==所有的大于1K的JSON是数据从服务器传递过来之后就会经过压缩这样我们解析出来的数据是不正确的。==

回顾知识:
1)FileInputStream fin = new FileInputStream(..);
2)DataInputStream din = new DataInputStream(fin);
相当于DataINputStream封装了FileInputStream,每次都想到DIN读字节的时候,都会直接调用FIS的读取方法,当Din需要读取特定格式/内容的时候,同样,会在内部通过Fis来读取,并且在自身的方法中,进行数据的处理。
当din.readInt() 的时候将会拼接成一个整数,叫作处理留


GZIP压缩算法:

注意 :如果输入流没有经过压缩,那么就不能使用GZIPinputStream 。因为没有压缩会抛出异常。

主要应用于IO的操作。只要使用GZIP封装了相应的IO流,就会自动实现压缩。


如何判断网络数据是不是经过压缩

1)服务器能搞都客户端,返回的数据是不是经过压缩的
2)服务器会通过网络放回一个HTTP头,名称叫做Content-Encoding字段,就会告诉你是不是经过压缩的。
加上这段:

//TODO 进行内容的获取
InputStream inputStream = conn.getInputStream();
//如何判断
String encoding = conn.getContentEncoding();

//判断是不是经过GZIP压缩的
if("gzip".equals(encoding)){
inputStream = new GZIPInputStream(inputStream);
}
这就能实现解压缩


加密

什么叫做加密:只有有密码的才叫加密,分为对称加密和非对称加密.
1.Cipher:


最后上今天的源码

package com.bluezhang.base64test_1016_class;

import EncryptUtil.EncryptUtil;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.bluezhang.bitmapdisplay_1012_class.imagesutil.ImageUtils;
import com.google.gson.Gson;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.io.*;
import java.math.BigInteger;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class SythEncriptActivity extends AppCompatActivity {

private EditText txtContent ;
private EditText txtpass ;
private EditText txtResoul ;
private EditText jiemi ;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_syth_encript);

txtContent = (EditText) findViewById(R.id.txt_content);
txtpass = (EditText) findViewById(R.id.txt_password);
txtResoul = (EditText) findViewById(R.id.txt_resout);
jiemi = (EditText) findViewById(R.id.txt_resoutafter);

}

/**
* 对称加密
* DES加密
* @param view
*/
public void btnDESEncriypt(View view) {

String content = txtContent.getText().toString();
String password = txtpass.getText().toString();
byte [] keyData = password.getBytes();

byte[] contentData = content.getBytes();//需要加密的内容

//DES 加密
//所有的加密解密都用到Cipher
if(keyData.length==8) {
try {
byte[] encryptData = EncryptUtil.desEncrypt(contentData, keyData);
String str = Base64.encodeToString(encryptData,Base64.NO_WRAP);
txtResoul.setText(str);

} catch (InvalidKeyException e) {
e.printStackTrace();
}
}
}

/**
* Des解密
* @param view
*/
public void btnDESDeEncripe(View view) {
String encriptedStr = txtResoul.getText().toString();
if(encriptedStr.length()>0){
String password = txtpass.getText().toString();
//因为加密方法使用那个Base64对加密的内容进行编码,解密的时候
//要进行Base64 的解码
byte[] encrryptedData = Base64.decode(encriptedStr, Base64.NO_WRAP);

byte[] keyData = password.getBytes();

//DES 要求八个字节
if(keyData.length==8){
//2.创建解密引擎Cipher
try {
Cipher cipher = Cipher.getInstance("DES");

//4准备key对象
DESKeySpec keySpec = new DESKeySpec(keyData);
//4.2 SecretKeyFactory
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
//生成key对象
SecretKey key = keyFactory.generateSecret(keySpec);

//3初始化
cipher.init(Cipher.DECRYPT_MODE,key);

//Cipher doFinal 就是将制定的参数 进行转换生成的结果

byte[] data  = cipher.doFinal(encrryptedData);

String str = new String (data);

Toast.makeText(this, "str = " + str, Toast.LENGTH_SHORT).show();
jiemi.setText(str);
} catch (Exception e) {
e.printStackTrace();
}
}

}
}

public void clear(View view) {
txtResoul.setText("");
txtContent.setText("");
jiemi.setText("");
}

public void createKey(View view) {
//生成密钥 包含了 公钥和私钥
SharedPreferences sharedPreferences = getSharedPreferences("key", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
KeyPair keyPair = EncryptUtil.generateRSAKeyPir(1024);
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
byte[] keypri = privateKey.getEncoded();
byte[] keypub = publicKey.getEncoded();
String strBasePri = Base64.encodeToString(keypri, Base64.NO_WRAP);
String strBasePub = Base64.encodeToString(keypub,Base64.NO_WRAP);

Log.d("pri",strBasePri);
Toast.makeText(this, "存储成功", Toast.LENGTH_SHORT).show();
editor.putString("pri", strBasePri);
editor.putString("pub", strBasePub);
editor.commit();

}

public void jiamizifuchuan(View view) {
//生成密钥 包含了 公钥和私钥
SharedPreferences sharedPreferences = getSharedPreferences("key", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
if(sharedPreferences.getString("pri",null)!=null&&sharedPreferences.getString("pub",null)!=null) {

try {
String pub = sharedPreferences.getString("pub", null);
String pri = sharedPreferences.getString("pri", null);

Log.d("pri",pri);

byte[] keypri = Base64.decode(pri.getBytes(), Base64.NO_WRAP);
byte[] keypub = Base64.decode(pub.getBytes(), Base64.NO_WRAP);

KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(keypri));
PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(keypub));

String a = "我是张凡";
byte[] p = EncryptUtil.rsaEncrypt(a.getBytes(), privateKey);
Gson gson = new Gson();

byte[] n = EncryptUtil.rsaEncrypt(p, publicKey);
String s = new String (n);
Toast.makeText(getApplicationContext(),"啊哈哈!! 出来了"+s,Toast.LENGTH_SHORT).show();

} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
}

}
}


Hex的工具类:

package com.bluezhang.bitmapdisplay_1012_class.imagesutil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.os.Environment;

public class ImageUtils {
public static final String CACHEDIR = Environment
.getExternalStorageDirectory() + "/blueZhang/images";

public static boolean isMounted() {
return Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState());
}

/**
* 将Bitmap图片保存到存储卡中
*
* @param url
* @param bitmap
* @throws IOException
*/
public static void saveImg(String url, Bitmap bitmap) throws IOException {
if (!isMounted())
return;

File dir = new File(CACHEDIR);
if (!dir.exists())
dir.mkdirs();

// 将图片对象写入到指定输出流中
FileOutputStream fos = new FileOutputStream(new File(dir, getName(url)));
bitmap.compress(getFormat(url), 100, fos);

}

/**
* 获取图片的格式
*
* @param url
*/
public static CompressFormat getFormat(String url) {
String fileName = getName(url);
if (fileName.endsWith("png")) {
return CompressFormat.PNG;
}
return CompressFormat.JPEG;
}

public static void saveImg(String url, byte[] bytes) throws IOException {
if (!isMounted())
return;

File dir = new File(CACHEDIR);
if (!dir.exists())
dir.mkdirs();

FileOutputStream fos = new FileOutputStream(new File(dir, getName(url)));
fos.write(bytes);
fos.close();

}

public static Bitmap getImg(String url) {
if (!isMounted())
return null;

File imgFile = new File(CACHEDIR, getName(url));
if (imgFile.exists()) {
return BitmapFactory.decodeFile(imgFile.getAbsolutePath());
}

return null;
}

public static String getName(String url) {
String a = url.substring(0,url.lastIndexOf("/"));

return a.substring(a.lastIndexOf("/") + 1)+".jpg";
}

public String getName(String url, int end) {
return url.substring(url.lastIndexOf("/") + 1, end);
}

}


测试类的创建:

import java.util.Arrays;

/**
* Author: blueZhang
* DATE:2015/10/16
* Time: 11:54
* AppName:Base64Test_1016_Class
* PckageName:com.bluezhang.base64test_1016_class.EncryptUtilTest
*/
public class EncryptUtilTest extends TestCase {
public void testToHex(){
byte [] data = new byte[]{20,20};

String hex = EncryptUtil.toHex(data);
//检查Hex是不是0102
//参数1代表期望的值 2 实际参数
assertEquals("1414", hex);

byte [] d1 = EncryptUtil.fromHex(hex);

//比较数组返回是不是相同的相同返回True false抛出异常

assertTrue(Arrays.equals(d1, data));

}

public void testFromHex(){
byte[] data = EncryptUtil.fromHex("abab");
byte [] d2 = new byte[]{(byte)0xab,(byte)0xab};
assertTrue(Arrays.equals(d2, data));

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: