标签:数字转换 .exe ide content dll auto cto 命令行 mba
ONE Goal , ONE Passion !
MD5即Message-Digest Algorithm 5(信息-摘要算法5),用于确保信息传输完整一致。是计算机广泛使用的杂凑算法之一(又译摘要算法、哈希算法),主流编程语言普遍已有MD5实现。将数据(如汉字)运算为另一固定长度值,是杂凑算法的基础原理,MD5的前身有MD2、MD3和MD4
public static String getMD5(String str) {
byte[] source = str.getBytes()
String s = null;
char hexDigits[] = { ‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘,
‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘ };// 用来将字节转换成16进制表示的字符
try {
java.security.MessageDigest md = java.security.MessageDigest
.getInstance("MD5");
md.update(source);
byte tmp[] = md.digest();// MD5 的计算结果是一个 128 位的长整数,
// 用字节表示就是 16 个字节
char str0[] = new char[16 * 2];// 每个字节用 16 进制表示的话,使用两个字符, 所以表示成 16
// 进制需要 32 个字符
int k = 0;// 表示转换结果中对应的字符位置
for (int i = 0; i < 16; i++) {// 从第一个字节开始,对 MD5 的每一个字节// 转换成 16
// 进制字符的转换
byte byte0 = tmp[i];// 取第 i 个字节
str0[k++] = hexDigits[byte0 >>> 4 & 0xf];// 取字节中高 4 位的数字转换,// >>>
// 为逻辑右移,将符号位一起右移
str0[k++] = hexDigits[byte0 & 0xf];// 取字节中低 4 位的数字转换
}
s = new String(str0);// 换后的结果转换为字符串
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return s;
}
现在由于网络MD5数据库比较大,如果直接使用md5加密的话,很容易被破译出来.这是在加密的过程中”加盐”就可以大大避免直接被破译的危险.
RSA的安全性依赖于大数的分解,公钥和私钥都是两个大素数(大于100的十进制位)的函数。从一个密钥和密文推断出明文的难度等同于分解两个大素数的积
RSA速度:
由于进行的都是大数计算,使得RSA最快的情况也比DES慢上100倍,无论 是软件还是硬件实现。 速度一直是RSA的缺陷。一般来说只用于少量数据 加密。
OpenSSl工具下载:OpenSSl工具 (64位的也可使用)使用OpenSSl工具生成密钥对的过程如下:
首先双击打开bin文件夹下的openssl.exe,打开之后是一个命令行窗口,执行下面窗口:
生成RSA私钥:
genrsa -out rsa_private_key.pem 1024
这条命令是让openssl随机生成了一份私钥,加密长度是1024位, 密钥长度,范围:512~2048。执行完命令后就可在bin文件夹下看到rsa_private_key.pem文件了。
用文本类工具打开可看到里面的内容:
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQC8rPqGGsar+BWI7vAtaaDOqphy41j5186hCU9DcchV4HWiv0Hv
Q3KXAEqHfZiAHZSyMSRMmDZVnqJwCVWFvKUPqU1RsCPZ9Imk+9ZXVkM3DDdw74v/
s6YMNx8cTuxybRCJUfOKbyC79cnHgmQqqkODv+EnprBtNKE4k8g90jNmbwIDAQAB
AoGAS06Hl+ssDQuyHLux5Y5ZfuOcgY64vtAiSyhaGMNbgNtcWJ8aBBPZsueM19OL
gOdNqGnw4RmH5liw4SL4na6T+qGpblEW/4G1eQXXJvfIBhlYJupaSvhuTf3msFw4
z9GY8V29deGPx5/6FRVTPTqnLoxUlfloOCYCeDJrXa9+YGECQQD24cdN9MT3HqfP
3S+UEDHO3XaDq38V3sCnKQ5mSYtnst/NV/g4bqYUOYElQW27p0YgwhHLlxWPke8a
4Jz/r4lnAkEAw6TfA36kUZfnFIXNM/0250jyZDE/yEKBXhThO8DAXAyAaEHjxA7K
+eprXP7ayFIfy+nrz/W5Iy81ibP5G/4tuQJBALaDn9ZP+DVBIoqXWI87kbb/Hpik
9mTysrZhsdWI1Viqcq3aNRVzJ7CX+pPSVQ9/0GZzUriST0w+dOgH2clkuk0CQDXX
hdh8XdRmrZ2kRRjtstJr7OlN9HO0ec3eiS3cmhO7DQukNn6aY5nrvahWKve+Qino
MpGE2nKoZ1+CPChMB2ECQG8utIhzAGH0lKbv/3+SzDERStrFYn/WqpWG3qSXAMye
s24khuRPtMYPzIxI/wZYPazbKgxuERAhiRtpz0e9jvI=
-----END RSA PRIVATE KEY-----
这里面的内容是标准的ASCII字符,中间的一大串字符就是私钥数据了。
生成RSA公钥:
rsa -in rsa_private_key.pem -out rsa_public_key.pem -pubout
打开文件看下里面的内容:
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8rPqGGsar+BWI7vAtaaDOqphy
41j5186hCU9DcchV4HWiv0HvQ3KXAEqHfZiAHZSyMSRMmDZVnqJwCVWFvKUPqU1R
sCPZ9Imk+9ZXVkM3DDdw74v/s6YMNx8cTuxybRCJUfOKbyC79cnHgmQqqkODv+En
prBtNKE4k8g90jNmbwIDAQAB
-----END PUBLIC KEY-----
这样密钥就基本生成了,不过这样密钥对的私钥是无法在代码中直接使用的,要想使用它需要借助RSAPrivateKeyStructure这个类,Java是不自带的。所以为了方便使用,我们需要对私钥进行PKCS#8编码,命令如下:
pkcs8 -topk8 -in rsa_private_key.pem -out pkcs8_rsa_private_key.pem -nocrypt
这条命令的结果依然是在bin文件夹生成了pkcs8_rsa_private_key.pem文件,打开内容如下:
-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALys+oYaxqv4FYju
8C1poM6qmHLjWPnXzqEJT0NxyFXgdaK/Qe9DcpcASod9mIAdlLIxJEyYNlWeonAJ
VYW8pQ+pTVGwI9n0iaT71ldWQzcMN3Dvi/+zpgw3HxxO7HJtEIlR84pvILv1yceC
ZCqqQ4O/4SemsG00oTiTyD3SM2ZvAgMBAAECgYBLToeX6ywNC7Icu7Hljll+45yB
jri+0CJLKFoYw1uA21xYnxoEE9my54zX04uA502oafDhGYfmWLDhIvidrpP6oalu
URb/gbV5Bdcm98gGGVgm6lpK+G5N/eawXDjP0ZjxXb114Y/Hn/oVFVM9OqcujFSV
+Wg4JgJ4Mmtdr35gYQJBAPbhx030xPcep8/dL5QQMc7ddoOrfxXewKcpDmZJi2ey
381X+DhuphQ5gSVBbbunRiDCEcuXFY+R7xrgnP+viWcCQQDDpN8DfqRRl+cUhc0z
/TbnSPJkMT/IQoFeFOE7wMBcDIBoQePEDsr56mtc/trIUh/L6evP9bkjLzWJs/kb
/i25AkEAtoOf1k/4NUEiipdYjzuRtv8emKT2ZPKytmGx1YjVWKpyrdo1FXMnsJf6
k9JVD3/QZnNSuJJPTD506AfZyWS6TQJANdeF2Hxd1GatnaRFGO2y0mvs6U30c7R5
zd6JLdyaE7sNC6Q2fppjmeu9qFYq975CKegykYTacqhnX4I8KEwHYQJAby60iHMA
YfSUpu//f5LMMRFK2sVif9aqlYbepJcAzJ6zbiSG5E+0xg/MjEj/Blg9rNsqDG4R
ECGJG2nPR72O8g==
-----END PRIVATE KEY-----
下载支付宝提供的密钥对生成工具.
http://download.csdn.net/detail/fengltxx/9674172
解压,阅读文档操作:
密钥对已经生成了.我们怎么使用呢?
a.首先要有两对密钥:
b.开始交换
c.数据传输过程加密,解密
注意: 加密,解密时.需要将 字符串形式的密钥 转换成 Key对象的密钥
package com.example.rsa;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
public final class RSAUtils
{
private static String RSA = "RSA";
/**
* 随机生成RSA密钥对(默认密钥长度为1024)
*
* @return
*/
public static KeyPair generateRSAKeyPair()
{
return generateRSAKeyPair(1024);
}
/**
* 随机生成RSA密钥对
*
* @param keyLength
* 密钥长度,范围:512~2048<br>
* 一般1024
* @return
*/
public static KeyPair generateRSAKeyPair(int keyLength)
{
try
{
KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
kpg.initialize(keyLength);
return kpg.genKeyPair();
} catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
return null;
}
}
/**
* 用公钥加密 <br>
* 每次加密的字节数,不能超过密钥的长度值减去11
*
* @param data
* 需加密数据的byte数据
* @param pubKey
* 公钥
* @return 加密后的byte型数据
*/
public static byte[] encryptData(byte[] data, PublicKey publicKey)
{
try
{
Cipher cipher = Cipher.getInstance(RSA);
// 编码前设定编码方式及密钥
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
// 传入编码数据并返回编码结果
return cipher.doFinal(data);
} catch (Exception e)
{
e.printStackTrace();
return null;
}
}
/**
* 用私钥解密
*
* @param encryptedData
* 经过encryptedData()加密返回的byte数据
* @param privateKey
* 私钥
* @return
*/
public static byte[] decryptData(byte[] encryptedData, PrivateKey privateKey)
{
try
{
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(encryptedData);
} catch (Exception e)
{
return null;
}
}
/**
* 通过公钥byte[](publicKey.getEncoded())将公钥还原,适用于RSA算法
*
* @param keyBytes
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PublicKey getPublicKey(byte[] keyBytes) throws NoSuchAlgorithmException,
InvalidKeySpecException
{
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
}
/**
* 通过私钥byte[]将公钥还原,适用于RSA算法
*
* @param keyBytes
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PrivateKey getPrivateKey(byte[] keyBytes) throws NoSuchAlgorithmException,
InvalidKeySpecException
{
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
}
/**
* 使用N、e值还原公钥
*
* @param modulus
* @param publicExponent
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PublicKey getPublicKey(String modulus, String publicExponent)
throws NoSuchAlgorithmException, InvalidKeySpecException
{
BigInteger bigIntModulus = new BigInteger(modulus);
BigInteger bigIntPrivateExponent = new BigInteger(publicExponent);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
}
/**
* 使用N、d值还原私钥
*
* @param modulus
* @param privateExponent
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PrivateKey getPrivateKey(String modulus, String privateExponent)
throws NoSuchAlgorithmException, InvalidKeySpecException
{
BigInteger bigIntModulus = new BigInteger(modulus);
BigInteger bigIntPrivateExponent = new BigInteger(privateExponent);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
}
/**
* 从字符串中加载公钥
*
* @param publicKeyStr
* 公钥数据字符串
* @throws Exception
* 加载公钥时产生的异常
*/
public static PublicKey loadPublicKey(String publicKeyStr) throws Exception
{
try
{
byte[] buffer = Base64Utils.decode(publicKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e)
{
throw new Exception("无此算法");
} catch (InvalidKeySpecException e)
{
throw new Exception("公钥非法");
} catch (NullPointerException e)
{
throw new Exception("公钥数据为空");
}
}
/**
* 从字符串中加载私钥<br>
* 加载时使用的是PKCS8EncodedKeySpec(PKCS#8编码的Key指令)。
*
* @param privateKeyStr
* @return
* @throws Exception
*/
public static PrivateKey loadPrivateKey(String privateKeyStr) throws Exception
{
try
{
byte[] buffer = Base64Utils.decode(privateKeyStr);
// X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException e)
{
throw new Exception("无此算法");
} catch (InvalidKeySpecException e)
{
throw new Exception("私钥非法");
} catch (NullPointerException e)
{
throw new Exception("私钥数据为空");
}
}
/**
* 从文件中输入流中加载公钥
*
* @param in
* 公钥输入流
* @throws Exception
* 加载公钥时产生的异常
*/
public static PublicKey loadPublicKey(InputStream in) throws Exception
{
try
{
return loadPublicKey(readKey(in));
} catch (IOException e)
{
throw new Exception("公钥数据流读取错误");
} catch (NullPointerException e)
{
throw new Exception("公钥输入流为空");
}
}
/**
* 从文件中加载私钥
*
* @param keyFileName
* 私钥文件名
* @return 是否成功
* @throws Exception
*/
public static PrivateKey loadPrivateKey(InputStream in) throws Exception
{
try
{
return loadPrivateKey(readKey(in));
} catch (IOException e)
{
throw new Exception("私钥数据读取错误");
} catch (NullPointerException e)
{
throw new Exception("私钥输入流为空");
}
}
/**
* 读取密钥信息
*
* @param in
* @return
* @throws IOException
*/
private static String readKey(InputStream in) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String readLine = null;
StringBuilder sb = new StringBuilder();
while ((readLine = br.readLine()) != null)
{
if (readLine.charAt(0) == ‘-‘)
{
continue;
} else
{
sb.append(readLine);
sb.append(‘\r‘);
}
}
return sb.toString();
}
/**
* 打印公钥信息
*
* @param publicKey
*/
public static void printPublicKeyInfo(PublicKey publicKey)
{
RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
System.out.println("----------RSAPublicKey----------");
System.out.println("Modulus.length=" + rsaPublicKey.getModulus().bitLength());
System.out.println("Modulus=" + rsaPublicKey.getModulus().toString());
System.out.println("PublicExponent.length=" + rsaPublicKey.getPublicExponent().bitLength());
System.out.println("PublicExponent=" + rsaPublicKey.getPublicExponent().toString());
}
public static void printPrivateKeyInfo(PrivateKey privateKey)
{
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
System.out.println("----------RSAPrivateKey ----------");
System.out.println("Modulus.length=" + rsaPrivateKey.getModulus().bitLength());
System.out.println("Modulus=" + rsaPrivateKey.getModulus().toString());
System.out.println("PrivateExponent.length=" + rsaPrivateKey.getPrivateExponent().bitLength());
System.out.println("PrivatecExponent=" + rsaPrivateKey.getPrivateExponent().toString());
}
}
上面需要注意的就是加密是有长度限制的,过长的话会抛异常!!!
代码中有些需要使用Base64再转换的,而java中不自带,Android中自带,所以自己写出一个来,方便Java后台使用.
package com.example.rsa;
import java.io.UnsupportedEncodingException;
public class Base64Utils
{
private static char[] base64EncodeChars = new char[]
{ ‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘, ‘G‘, ‘H‘, ‘I‘, ‘J‘, ‘K‘, ‘L‘, ‘M‘, ‘N‘, ‘O‘, ‘P‘, ‘Q‘, ‘R‘, ‘S‘, ‘T‘,
‘U‘, ‘V‘, ‘W‘, ‘X‘, ‘Y‘, ‘Z‘, ‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘g‘, ‘h‘, ‘i‘, ‘j‘, ‘k‘, ‘l‘, ‘m‘,
‘n‘, ‘o‘, ‘p‘, ‘q‘, ‘r‘, ‘s‘, ‘t‘, ‘u‘, ‘v‘, ‘w‘, ‘x‘, ‘y‘, ‘z‘, ‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘,
‘6‘, ‘7‘, ‘8‘, ‘9‘, ‘+‘, ‘/‘ };
private static byte[] base64DecodeChars = new byte[]
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53,
54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1,
-1, -1, -1 };
/**
* 加密
*
* @param data
* @return
*/
public static String encode(byte[] data)
{
StringBuffer sb = new StringBuffer();
int len = data.length;
int i = 0;
int b1, b2, b3;
while (i < len)
{
b1 = data[i++] & 0xff;
if (i == len)
{
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
sb.append("==");
break;
}
b2 = data[i++] & 0xff;
if (i == len)
{
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
sb.append("=");
break;
}
b3 = data[i++] & 0xff;
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);
sb.append(base64EncodeChars[b3 & 0x3f]);
}
return sb.toString();
}
/**
* 解密
*
* @param str
* @return
*/
public static byte[] decode(String str)
{
try
{
return decodePrivate(str);
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
return new byte[]
{};
}
private static byte[] decodePrivate(String str) throws UnsupportedEncodingException
{
StringBuffer sb = new StringBuffer();
byte[] data = null;
data = str.getBytes("US-ASCII");
int len = data.length;
int i = 0;
int b1, b2, b3, b4;
while (i < len)
{
do
{
b1 = base64DecodeChars[data[i++]];
} while (i < len && b1 == -1);
if (b1 == -1)
break;
do
{
b2 = base64DecodeChars[data[i++]];
} while (i < len && b2 == -1);
if (b2 == -1)
break;
sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4)));
do
{
b3 = data[i++];
if (b3 == 61)
return sb.toString().getBytes("iso8859-1");
b3 = base64DecodeChars[b3];
} while (i < len && b3 == -1);
if (b3 == -1)
break;
sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));
do
{
b4 = data[i++];
if (b4 == 61)
return sb.toString().getBytes("iso8859-1");
b4 = base64DecodeChars[b4];
} while (i < len && b4 == -1);
if (b4 == -1)
break;
sb.append((char) (((b3 & 0x03) << 6) | b4));
}
return sb.toString().getBytes("iso8859-1");
}
}
package com.example.rsa;
import java.io.InputStream;
import java.security.PrivateKey;
import java.security.PublicKey;
import android.app.Activity;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener
{
private Button btn1, btn2;// 加密,解密
private EditText et1, et2, et3;// 需加密的内容,加密后的内容,解密后的内容
// 注意copy密钥字符串时,不要有空格. 这对密钥必须是一对
private static String PUCLIC_KEY = "公钥";
private static String PRIVATE_KEY = "私钥";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView()
{
btn1 = (Button) findViewById(R.id.btn1);
btn2 = (Button) findViewById(R.id.btn2);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
et1 = (EditText) findViewById(R.id.et1);
et2 = (EditText) findViewById(R.id.et2);
et3 = (EditText) findViewById(R.id.et3);
}
@Override
public void onClick(View v)
{
switch (v.getId())
{
--------------- 此处模拟android端数据使用<服务器端公钥>加密后传到服务器--------------
// 加密
case R.id.btn1:
String source = et1.getText().toString().trim();
try
{
// 从字符串中得到公钥
// PublicKey publicKey = RSAUtils.loadPublicKey(PUCLIC_KEY);
// 从文件中得到公钥
InputStream inPublic = getResources().getAssets().open("rsa_public_key_me.pem");
PublicKey publicKey = RSAUtils.loadPublicKey(inPublic);
// 加密
byte[] encryptByte = RSAUtils.encryptData(source.getBytes(), publicKey);
// 为了方便观察吧加密后的数据用base64加密转一下,要不然看起来是乱码,所以解密是也是要用Base64先转换
String afterencrypt = Base64Utils.encode(encryptByte);
et2.setText(afterencrypt);
} catch (Exception e)
{
e.printStackTrace();
}
break;
-----------------这里模拟服务器端人员拿到加密后的数据用<服务器私钥>解密-----------
// 解密
case R.id.btn2:
String encryptContent = et2.getText().toString().trim();
try
{
// 从字符串中得到私钥
// PrivateKey privateKey = RSAUtils.loadPrivateKey(PRIVATE_KEY);
// 从文件中得到私钥
InputStream inPrivate = getResources().getAssets().open("rsa_private_key_pkcs8_me.pem");
PrivateKey privateKey = RSAUtils.loadPrivateKey(inPrivate);
// 因为RSA加密后的内容经Base64再加密转换了一下,所以先Base64解密回来再给RSA解密
byte[] decryptByte = RSAUtils.decryptData(Base64Utils.decode(encryptContent), privateKey);
String decryptStr = new String(decryptByte);
et3.setText(decryptStr);
} catch (Exception e)
{
e.printStackTrace();
}
break;
default:
break;
}
}
}
密钥放到assest资源文件夹里了,也可以直接使用字符串得到,上面注释掉了。
ok! 这下终于搞定了!
标签:数字转换 .exe ide content dll auto cto 命令行 mba
原文地址:http://blog.csdn.net/fengltxx/article/details/53049466