您的位置:首页 > 移动开发 > Android开发

Android加密方式的实现代码MD5-RSA-DES

2016-03-18 17:28 393 查看
一、MD5算法首先MD5是不可逆的,只能加密而不能解密。import java.security.MessageDigest; public class MD5Util { public final static String getMD5String(String s) { char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; try { byte[] btInput
= s.getBytes(); //获得MD5摘要算法的 MessageDigest 对象 MessageDigest mdInst = MessageDigest.getInstance("MD5"); //使用指定的字节更新摘要 mdInst.update(btInput); //获得密文 byte[] md = mdInst.digest(); //把密文转换成十六进制的字符串形式 int j = md.length; char str[] = new char[j * 2]; int k = 0;
for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str); } catch (Exception e) { e.printStackTrace(); return null; } } }二、RSA加密RSA是可逆的,一个字符串可以经rsa加密后,经加密后的字符串传到对端如服务器上,再进行解密即可。前提是服务器知道解密的私钥,当然这个私钥最好不要再网络传输。RSA算法描述中需要以下几个变量:1、p和q
是不相等的,足够大的两个质数。 p和q是保密的2、n = p*q n是公开的3、f(n) = (p-1)*(q-1)4、e 是和f(n)互质的质数5、计算参数d 6、经过上面5步计算得到公钥KU=(e,n) 私钥KR=(d,n)下面两篇文章对此有清晰的描述:http://wenku.baidu.com/view/e53fbe36a32d7375a417801b.htmlhttp://bank.hexun.com/2009-06-24/118958531.html下面是java实现RSAUtil.java类:[java]
view plain copy print?在CODE上查看代码片派生到我的代码片package org.rsa.util; import javax.crypto.Cipher; import java.security.*; import java.security.spec.RSAPublicKeySpec; import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.InvalidKeySpecException; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.io.*; import java.math.BigInteger; /** * RSA 工具类。提供加密,解密,生成密钥对等方法。 * 需要到http://www.bouncycastle.org下载bcprov-jdk14-123.jar。
* RSA加密原理概述 * RSA的安全性依赖于大数的分解,公钥和私钥都是两个大素数(大于100的十进制位)的函数。 * 据猜测,从一个密钥和密文推断出明文的难度等同于分解两个大素数的积 * =================================================================== * (该算法的安全性未得到理论的证明) * =================================================================== *
密钥的产生: * 1.选择两个大素数 p,q ,计算 n=p*q; * 2.随机选择加密密钥 e ,要求 e 和 (p-1)*(q-1)互质 * 3.利用 Euclid 算法计算解密密钥 d , 使其满足 e*d = 1(mod(p-1)*(q-1)) (其中 n,d 也要互质) * 4:至此得出公钥为 (n,e) 私钥为 (n,d) * =================================================================== * 加解密方法: * 1.首先将要加密的信息
m(二进制表示) 分成等长的数据块 m1,m2,...,mi 块长 s(尽可能大) ,其中 2^s<n * 2:对应的密文是: ci = mi^e(mod n) * 3:解密时作如下计算: mi = ci^d(mod n) * =================================================================== * RSA速度 * 由于进行的都是大数计算,使得RSA最快的情况也比DES慢上100倍,无论 是软件还是硬件实现。 * 速度一直是RSA的缺陷。一般来说只用于少量数据
加密。 *文件名:RSAUtil.java

*@author 董利伟

*版本:

*描述:

*创建时间:2008-9-23 下午09:58:16

*文件描述:

*修改者:

*修改日期:

*修改描述:

*/ public class RSAUtil { //密钥对 private KeyPair keyPair = null; /** * 初始化密钥对 */ public RSAUtil(){ try { this.keyPair = this.generateKeyPair(); } catch (Exception e) { e.printStackTrace(); } } /** * 生成密钥对 * @return KeyPair * @throws Exception */ private KeyPair
generateKeyPair() throws Exception { try { KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA",new org.bouncycastle.jce.provider.BouncyCastleProvider()); //这个值关系到块加密的大小,可以更改,但是不要太大,否则效率会低 final int KEY_SIZE = 1024; keyPairGen.initialize(KEY_SIZE,
new SecureRandom()); KeyPair keyPair = keyPairGen.genKeyPair(); return keyPair; } catch (Exception e) { throw new Exception(e.getMessage()); } } /** * 生成公钥 * @param modulus * @param publicExponent * @return RSAPublicKey * @throws Exception */ private RSAPublicKey
generateRSAPublicKey(byte[] modulus, byte[] publicExponent) throws Exception { KeyFactory keyFac = null; try { keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider()); } catch (NoSuchAlgorithmException ex) { throw new
Exception(ex.getMessage()); } RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(modulus), new BigInteger(publicExponent)); try { return (RSAPublicKey) keyFac.generatePublic(pubKeySpec); } catch (InvalidKeySpecException ex) { throw new Exception(ex.getMessage());
} } /** * 生成私钥 * @param modulus * @param privateExponent * @return RSAPrivateKey * @throws Exception */ private RSAPrivateKey generateRSAPrivateKey(byte[] modulus, byte[] privateExponent) throws Exception { KeyFactory keyFac = null; try { keyFac = KeyFactory.getInstance("RSA",
new org.bouncycastle.jce.provider.BouncyCastleProvider()); } catch (NoSuchAlgorithmException ex) { throw new Exception(ex.getMessage()); } RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(modulus), new BigInteger(privateExponent)); try {
return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec); } catch (InvalidKeySpecException ex) { throw new Exception(ex.getMessage()); } } /** * 加密 * @param key 加密的密钥 * @param data 待加密的明文数据 * @return 加密后的数据 * @throws Exception */ public byte[] encrypt(Key
key, byte[] data) throws Exception { try { Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider()); cipher.init(Cipher.ENCRYPT_MODE, k
a53d
ey); //获得加密块大小,如:加密前数据为128个byte,而key_size=1024 加密块大小为127 byte,加密后为128个byte; //因此共有2个加密块,第一个127
byte第二个为1个byte int blockSize = cipher.getBlockSize(); int outputSize = cipher.getOutputSize(data.length);//获得加密块加密后块大小 int leavedSize = data.length % blockSize; int blocksSize = leavedSize != 0 ? data.length / blockSize + 1 : data.length / blockSize; byte[]
raw = new byte[outputSize * blocksSize]; int i = 0; while (data.length - i * blockSize > 0) { if (data.length - i * blockSize > blockSize) cipher.doFinal(data, i * blockSize, blockSize, raw, i * outputSize); else cipher.doFinal(data, i * blockSize, data.length
- i * blockSize, raw, i * outputSize); //这里面doUpdate方法不可用,查看源代码后发现每次doUpdate后并没有什么实际动作除了把byte[]放到ByteArrayOutputStream中 //,而最后doFinal的时候才将所有的byte[]进行加密,可是到了此时加密块大小很可能已经超出了OutputSize所以只好用dofinal方法。 i++; } return raw; } catch (Exception e) { throw new Exception(e.getMessage());
} } /** * 解密 * @param key 解密的密钥 * @param raw 已经加密的数据 * @return 解密后的明文 * @throws Exception */ public byte[] decrypt(Key key, byte[] raw) throws Exception { try { Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
cipher.init(cipher.DECRYPT_MODE, key); int blockSize = cipher.getBlockSize(); ByteArrayOutputStream bout = new ByteArrayOutputStream(64); int j = 0; while (raw.length - j * blockSize > 0) { bout.write(cipher.doFinal(raw, j * blockSize, blockSize)); j++; }
return bout.toByteArray(); } catch (Exception e) { throw new Exception(e.getMessage()); } } /** * 返回公钥 * @return * @throws Exception */ public RSAPublicKey getRSAPublicKey() throws Exception{ //获取公钥 RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic();
//获取公钥系数(字节数组形式) byte[] pubModBytes = pubKey.getModulus().toByteArray(); //返回公钥公用指数(字节数组形式) byte[] pubPubExpBytes = pubKey.getPublicExponent().toByteArray(); //生成公钥 RSAPublicKey recoveryPubKey = this.generateRSAPublicKey(pubModBytes,pubPubExpBytes); return
recoveryPubKey; } /** * 获取私钥 * @return * @throws Exception */ public RSAPrivateKey getRSAPrivateKey() throws Exception{ //获取私钥 RSAPrivateKey priKey = (RSAPrivateKey) keyPair.getPrivate(); //返回私钥系数(字节数组形式) byte[] priModBytes = priKey.getModulus().toByteArray();
//返回私钥专用指数(字节数组形式) byte[] priPriExpBytes = priKey.getPrivateExponent().toByteArray(); //生成私钥 RSAPrivateKey recoveryPriKey = this.generateRSAPrivateKey(priModBytes,priPriExpBytes); return recoveryPriKey; } }
Des 64位加密解密算法。Java代码 收藏代码package com.itaoo.utils; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.*;
import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.CipherOutputStream; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; public class DESCoder { // a weak key private static String encoding = "UTF-8";
// 密钥 private String sKey = ""; public DESCoder(String sKey) { this.sKey = sKey; } /** * 加密字符串 */ public String ebotongEncrypto(String str) { String result = str; if (str != null && str.length() > 0) { try { byte[] encodeByte = symmetricEncrypto(str.getBytes(encoding));
result = Base64.encode(encodeByte); } catch (Exception e) { e.printStackTrace(); } } return result; } /** * 解密字符串 */ public String ebotongDecrypto(String str) { String result = str; if (str != null && str.length() > 0) { try { byte[] encodeByte = Base64.decode(str);
byte[] decoder = symmetricDecrypto(encodeByte); result = new String(decoder, encoding); } catch (Exception e) { e.printStackTrace(); } } return result; } /** * 加密byte[] */ public byte[] ebotongEncrypto(byte[] str) { byte[] result = null; if (str != null &&
str.length > 0) { try { byte[] encodeByte = symmetricEncrypto(str); result = Base64.encode(encodeByte).getBytes(); } catch (Exception e) { e.printStackTrace(); } } return result; } /** * 解密byte[] */ public byte[] ebotongDecrypto(byte[] str) { byte[] result
= null; if (str != null && str.length > 0) { try { byte[] encodeByte = Base64.decode(new String(str, encoding)); //byte[] encodeByte = base64decoder.decodeBuffer(new String(str)); byte[] decoder = symmetricDecrypto(encodeByte); result = new String(decoder).getBytes(encoding);
result = new String(decoder).getBytes(); } catch (Exception e) { e.printStackTrace(); } } return result; } /** * 对称加密字节数组并返回 * * @param byteSource 需要加密的数据 * @return 经过加密的数据 * @throws Exception */ public byte[] symmetricEncrypto(byte[] byteSource) throws Exception
{ try { int mode = Cipher.ENCRYPT_MODE; SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); byte[] keyData = sKey.getBytes(); DESKeySpec keySpec = new DESKeySpec(keyData); Key key = keyFactory.generateSecret(keySpec); Cipher cipher = Cipher.getInstance("DES");
cipher.init(mode, key); byte[] result = cipher.doFinal(byteSource); return result; } catch (Exception e) { throw e; } finally { } } /** * 对称解密字节数组并返回 * * @param byteSource 需要解密的数据 * @return 经过解密的数据 * @throws Exception */ public byte[] symmetricDecrypto(byte[]
byteSource) throws Exception { try { int mode = Cipher.DECRYPT_MODE; SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); byte[] keyData = sKey.getBytes(); DESKeySpec keySpec = new DESKeySpec(keyData); Key key = keyFactory.generateSecret(keySpec);
Cipher cipher = Cipher.getInstance("DES"); cipher.init(mode, key); byte[] result = cipher.doFinal(byteSource); return result; } catch (Exception e) { throw e; } finally { } } /** * 散列算法 * * @param byteSource * 需要散列计算的数据 * @return 经过散列计算的数据 * @throws Exception
*/ public static byte[] hashMethod(byte[] byteSource) throws Exception { try { MessageDigest currentAlgorithm = MessageDigest.getInstance("SHA-1"); currentAlgorithm.reset(); currentAlgorithm.update(byteSource); return currentAlgorithm.digest(); } catch (Exception
e) { throw e; } } /** * 对文件srcFile进行加密输出到文件distFile * @param srcFile 明文文件 * @param distFile 加密后的文件 * @throws Exception */ public void EncryptFile(String srcFile,String distFile) throws Exception{ InputStream is=null; OutputStream out = null; CipherInputStream
cis =null; try { int mode = Cipher.ENCRYPT_MODE; SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); byte[] keyData = sKey.getBytes(); DESKeySpec keySpec = new DESKeySpec(keyData); Key key = keyFactory.generateSecret(keySpec); Cipher cipher
= Cipher.getInstance("DES"); cipher.init(mode, key); is= new FileInputStream(srcFile); out = new FileOutputStream(distFile); cis = new CipherInputStream(is,cipher); byte[] buffer = new byte[1024]; int r; while((r=cis.read(buffer))>0){ out.write(buffer, 0,
r); } } catch (Exception e) { throw e; } finally { cis.close(); is.close(); out.close(); } } /** * 解密文件srcFile到目标文件distFile * @param srcFile 密文文件 * @param distFile 解密后的文件 * @throws Exception */ public void DecryptFile(String srcFile,String distFile) throws
Exception{ InputStream is=null; OutputStream out = null; CipherOutputStream cos =null; try { int mode = Cipher.DECRYPT_MODE; SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); byte[] keyData = sKey.getBytes(); DESKeySpec keySpec = new DESKeySpec(keyData);
Key key = keyFactory.generateSecret(keySpec); Cipher cipher = Cipher.getInstance("DES"); cipher.init(mode, key); byte[] buffer = new byte[1024]; is= new FileInputStream(srcFile); out = new FileOutputStream(distFile); cos = new CipherOutputStream(out,cipher);
int r; while((r=is.read(buffer))>=0){ cos.write(buffer, 0, r); } } catch (Exception e) { throw e; } finally { cos.close(); is.close(); out.close(); } } /** * 对文件进行加密64位编码 * @param srcFile 源文件 * @param distFile 目标文件 */ public void BASE64EncoderFile(String srcFile,String
distFile){ InputStream inputStream =null; OutputStream out = null; try { inputStream = new FileInputStream(srcFile); out = new FileOutputStream(distFile); byte[] buffer = new byte[1024]; while(inputStream.read(buffer)>0){ out.write(ebotongEncrypto(buffer));
} } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { out.close(); inputStream.close(); } catch (IOException e) { // TODO
Auto-generated catch block e.printStackTrace(); } } } /** * 对文件进行解密64位解码 * @param srcFile 源文件 * @param distFile 目标文件 */ public void BASE64DecoderFile(String srcFile,String distFile){ InputStream inputStream =null; OutputStream out = null; try { inputStream
= new FileInputStream(srcFile); out = new FileOutputStream(distFile); byte[] buffer = new byte[1412]; while(inputStream.read(buffer)>0){ out.write(ebotongDecrypto(buffer)); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace();
} catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { out.close(); inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: