Nemo

Nemo 关注TA

路漫漫其修远兮,吾将上下而求索。

Nemo

Nemo

关注TA

路漫漫其修远兮,吾将上下而求索。

  •  普罗旺斯
  • 负责帅就完事了
  • 写了1,496,113字

该文章投稿至Nemo社区   Java  板块 复制链接


安卓/JAVA服务端RSA加解密工具

发布于 2017/04/25 19:15 1,841浏览 0回复 5,597

Ubuntu下准备证书相关的文件:

    #创建私钥  
    openssl genrsa -out private_key.pem 1024  
    #创建证书请求(按照提示输入信息)  
    openssl req -new -out cert.csr -key private_key.pem  
    #自签署根证书  
    openssl x509 -req -in cert.csr -out public_key.der -outform der -signkey private_key.pem -days 3650  
    #用java代码要从这个文件中得到想要的priavtekey 可以先用命令(就被这东西卡住了)  
    openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key.pem -out private_pkcs8_der.key -nocrypt  






import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;

import javax.crypto.Cipher;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


/**
 * RSA加解密工具
* @author:Nemo 20170425
*/
public class Crypt {

static BASE64Decoder decoder = new BASE64Decoder();
static BASE64Encoder encoder = new BASE64Encoder();

private static String RSA = "RSA";

private static String encode = "UTF-8";//保持平台兼容统一使用utf-8

//私钥文件路径
private static String privateFile = "/keys/private_pkcs8_der.key";
//公钥文件路径
private static String publicFile = "/keys/public_key.der";


//pkcs8_der.key文件为私钥 只能保存在服务端
//public_key.der为公钥文件,保存在客户端
public static void main(String[] args) throws Exception {

String pwd="12345678";
//客户端加密
String password = DESAndRSAEncrypt(pwd);
System.out.println("pwd RSA加密后base64"+password);

//服务端解密
String textDecrypt = DESAndRSADecrypt(password);
System.out.println("解密后数据:"+textDecrypt);
// generateKeyPair();
}

//客户端加密
public static String DESAndRSAEncrypt(String data) throws Exception{

byte[] encryptKey = RSAEncrypt(data.getBytes(encode));
String keyBase64 = encoder.encode(encryptKey);

return keyBase64;
}

/**
* 服务端解密
* @param data
* @return
* @throws Exception
*/
public static String DESAndRSADecrypt(String data) throws Exception {
byte[] encryptedKey = decoder.decodeBuffer(data);
byte[] decryptedKey= RSADecrypt(encryptedKey);
data = new String(decryptedKey,encode);
return data;
}

/**
* 公钥加密
* @param plainText
* @return
* @throws Exception
*/
private static byte[] RSAEncrypt(byte[] plainText) throws Exception{
//读取公钥
CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509");

//获取私钥文件的路径
String path = Class.class.getClass().getResource("/").getPath();

FileInputStream bais = new FileInputStream(path + publicFile);
Certificate cert = certificatefactory.generateCertificate(bais);
bais.close();
PublicKey puk = cert.getPublicKey();
// System.out.println("公钥base64"+encoder.encode(puk.getEncoded()));
return doEncrypt(plainText, puk, RSA);
}

/**
* 私钥解密
* @param encryptData
* @return
* @throws Exception
*/
private static byte[] RSADecrypt(byte[] encryptData) throws Exception{

//获取私钥文件的路径
String path = Class.class.getClass().getResource("/").getPath();

FileInputStream in = new FileInputStream(path + privateFile);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] tmpbuf = new byte[1024];
int count = 0;
while ((count = in.read(tmpbuf)) != -1) {
bout.write(tmpbuf, 0, count);
}
in.close();
//读取私钥
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(bout.toByteArray());
PrivateKey prk = keyFactory.generatePrivate(privateKeySpec);
// System.out.println("私钥base64"+encoder.encode(prk.getPrivateExponent().toByteArray()));
return doDecrypt(encryptData, prk, RSA);
}

/**
* 执行加密操作
* @param data 待操作数据
* @param key Key
* @param type 算法 RSA or DES
* @return
* @throws Exception
*/
private static byte[] doEncrypt(byte[] data,Key key,String type) throws Exception{

//安卓和java的编码算法不太一样,安卓type需要修改为RSA/ECB/PKCS1Padding
Cipher cipher = Cipher.getInstance(type);
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(data);
}

/**
* 执行解密操作
* @param data 待操作数据
* @param key Key
* @param type 算法 RSA or DES
* @return
* @throws Exception
*/
private static byte[] doDecrypt(byte[] data,Key key,String type) throws Exception{
Cipher cipher = Cipher.getInstance(type);
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(data);
}

private static void generateKeyPair() throws Exception{
KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
kpg.initialize(1024); // 指定密钥的长度,初始化密钥对生成器
KeyPair kp = kpg.generateKeyPair(); // 生成密钥对
RSAPublicKey puk = (RSAPublicKey) kp.getPublic();
RSAPrivateKey prk = (RSAPrivateKey) kp.getPrivate();
BigInteger e = puk.getPublicExponent();
BigInteger n = puk.getModulus();
BigInteger d = prk.getPrivateExponent();

BASE64Encoder encoder = new BASE64Encoder();
System.out.println("public key:\n"+encoder.encode(n.toByteArray()));
System.out.println("private key:\n"+encoder.encode(d.toByteArray()));
}
}
本文标签
 {{tag}}
点了个评