关键词:服务集成,系统集成,流程启动,数据交互,数据传输
O2OA允许用户自行修改源码或者增加源码来扩展系统服务,也可以包装功能更强的业务服务。本文主要介绍如何在O2OA中开发接口与外部系统进行数据交互。
外部系统调用接口发起流程
1.在服务管理创建接口
2.以发起一个收文流程为例,接口内容如下:
/*
//requestText为外系统传入的参数:title,from,to等为传入的业务数据(根据实际情况调整),contents为正文数组对象,slaves为附件数组对象,没有的可以不传。
假设requestText = {
"title" : "关于某某某的通知公告(标题,必填)",
"from" : "办公室(来文单位,必填)",
"to" : "qhsnynctrsc(OA的部门人事处ID,必填)",
"date" : "2020-05-09(收文日期,选填)",
"no" : "农123(字号,选填)",
"key" : "nmt(文件加密私钥,选填,为空则认为没加密)",
"contents" : [ {
"filepath" : "http://xxxxx.com?file=aaaa.docx",
"filename" : "aaaa.docx"
} ],
"slaves" : [ {
"filepath" : "http://xxxxx.com?file=slaves.docx",
"filename" : "slaves.docx"
} ]
}
*/
try{
var result = {
}
print( "requestText="+requestText );
var requestJson = JSON.parse(requestText);
if( typeof(requestJson) === "string" ){
requestJson = JSON.parse(requestJson);
}
if(requestJson.title === "" || requestJson.from === "" || requestJson.to === ""){//必填信息校验
result.state = "NMT0002";
result.message = "失败";
result.data = "标题或者来文单位或者OA部门ID为空";
}else{
var processId = "d75fe1d2-6823-4e33-9798-6218d82f930f"; //需要启动的流程标识
var identity = "xxxxx@474820e2-4c54-4e5c-8c82-5915d5ca6d2c@I"; //启动人员身份
//传入的参数名和表单字段名不一致,所以重新拼接,subject,input_department,receive_date,input_file_no为流程表单字段标识
var datastr = '{"subject":"'+requestJson.title+'","input_department":"'+requestJson.from+'","receive_date":"'+requestJson.date+'","input_file_no":"'+requestJson.no+'"}';
datastr = JSON.parse(datastr);
var applications = resources.getContext().applications();
var data = {
"title": requestJson.title,
"identity": identity,
"data" : datastr //表单数据
}
var resp = applications.postQuery('x_processplatform_assemble_surface', 'work/process/'+processId, JSON.stringify( data )); //调用平台启动流程接口
var result1 = JSON.parse( resp.toString() );
var workId = result1.data[0].work; //返回workid
//上传附件-----------------------------------------------------------begin
var token = getToken();
//print( "contents个数:" + requestJson.contents.length);
//print( "slaves个数:" + requestJson.slaves.length);
var contentsSite = "attachment"; //正文附件放置的附件区域
var slavesSite = "attachment_1"; //普通附件放置的附件区域
//处理contents
var conArr = requestJson.contents;
for(var i=0;i//处理slaves
var slavesArr = requestJson.slaves;
for(var j=0;j//上传附件-----------------------------------------------------------end
result.state = "NMT0001";
result.message = "成功";
result.data = workId;
}
}catch(e){
e.printStackTrace();
result.state = "NMT0002";
result.message = "失败";
result.data = e.name + ": " + e.message
}
this.response.setBody(result,"application/json");
/*
var workid = "0b3eeab0-c3af-4223-b091-60fee7b733f9"; //workid:待办id
var fileUrl = "http://127.0.0.1/x_desktop/js/base.js"; //附件下载链接
var fileName = "base.js"; //附件名称
var token = getToken();
site:附件放置区域
*/
function uploadAtt(workid,fileUrl,fileName,token,site){ //上传附件
try {
print("token=============================="+token);
//实例化java类
var HashMap = Java.type("java.util.HashMap");
var LinkedHashMap = Java.type("java.util.LinkedHashMap");
var HttpClientUtilsUpfile = Java.type("com.z.custom.HttpClientUtilsUpfile");
var headMap = new LinkedHashMap();
headMap.put("x-token", token);
headMap.put("accept", "*/*");
headMap.put("connection", "Keep-Alive");
headMap.put("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
var uploadParams = new LinkedHashMap();
uploadParams.put("fileName", fileName); //附件名称
uploadParams.put("site", site); //附件区域
uploadParams.put("extraParam","");
//密钥和向量是跟外系统做的加密参数约定
//密钥
var sessionKey = "12345678123456781234567812345678";
//向量
var iv = "1234567812345678";
//上传附件接口,传入文档的workid
var strurl = "http://localhost:20020/x_processplatform_assemble_surface/jaxrs/attachment/upload/work/" + workid;
/*
*方法功能:java模拟表单附件上传
*strurl : 上传附件接口地址
*fileUrl : 附件下载地址
*fileName :附件名称
*uploadParams : 上传附件接口参数
*headMap : 表单头参数
*/
//uploadByteFileImpl 此方法是用于双方AES加解密附件上传使用,如不需要加解密可使用:uploadUrlFileImpl方法进行附件上传
HttpClientUtilsUpfile.getInstance().uploadByteFileImpl(strurl, fileUrl,fileName,"file", uploadParams, headMap,sessionKey,iv);
} catch (e) {
e.printStackTrace();
e.printStackTrace();
result.state = "NMT0002";
result.message = "失败";
result.data = e.name + ": " + e.message
}
}
function getToken(){ //获取token
var HttpClientUtilsUpfile = Java.type("com.z.custom.HttpClientUtilsUpfile");
//使用token进行Sso登陆
var path = "http://localhost:20020/x_organization_assemble_authentication/jaxrs/sso";
var login_uid = "13379254582"; //用户简称
var client = "wwx" //SSO名称
var sso_key = "987654321"; //SSO密钥
//获取token
var token = HttpClientUtilsUpfile.getInstance().getToken(path,client,login_uid,sso_key);
return token;
}
将流程数据传回外部系统
在服务管理创建接口,接口内容如下:
/*
requestText为入参
*/
try{
var result = {
}
var pushdata = {
}
var requestJson = JSON.parse(requestText);
if( typeof(requestJson) === "string" ){
requestJson = JSON.parse(requestJson);
}
print( "workId="+requestJson.workId);
//通过workId得到所有附件列表
var applications = resources.getContext().applications();
var resp = applications.getQuery('x_processplatform_assemble_surface', 'attachment/list/work/'+requestJson.workId);
var result1 = JSON.parse( resp.toString() );
var dataArr = result1.data;
var contentArr = [];
var salvesArr = [];
for(var i=0;ivar salvesStr = '';
var filepath = '';
filepath = "http://localhost:20020/x_qhny_assemble_control/jaxrs/attachment/aes/"+ dataArr[i].id +"/stream"
salvesStr = '{"filepath":"'+filepath+'","filename":"'+dataArr[i].name+'"}';
if(dataArr[i].site === "attachment"){
salvesArr.push(salvesStr)
}else{
contentArr.push(salvesStr)
}
}
pushdata.title = requestJson.subject;//标题,必填
pushdata.from = requestJson.danwei;//来文单位,必填
pushdata.to = requestJson.to; //区划编号
pushdata.date = ""; //收文日期,选填
pushdata.no = requestJson.fone; //字号,选填
pushdata.key = ""; //文件加密私钥,选填,为空则认为没加密
pushdata.contents = JSON.parse("[" + contentArr + "]");
pushdata.slaves = JSON.parse("[" + salvesArr + "]");
var url = 'http://ip:端口/OAJoint/Document'; //外系统提供的接口
var ArrayList = Java.type('java.util.ArrayList');
var heads = new ArrayList();
var NameValuePair = Java.type('com.x.base.core.project.bean.NameValuePair');
var p1 = new NameValuePair('Content-Type', 'application/json; charset=utf-8');
var AppId = "FF82CEDA-2334-4571-B326-DB37C8B66DAC";
var Timestamp = parseInt(new Date().getTime()/1000)+"";
var p2 = new NameValuePair('AppId', AppId);
var p3 = new NameValuePair('Timestamp', Timestamp);
heads.add(p1);
heads.add(p2);
heads.add(p3);
var OASecret = "62717DB4-AD9A-4B07-BDD4-72163EEA3A02";//Md5加密的Key
var mac= AppId + OASecret + Timestamp
print( "mac = " + mac );
try{
print(">>>>>>>>>尝试对Mac进行Md5加密");
var md5Util = Java.type('com.z.custom.MD5Util');
var md5Mac = md5Util.getMD5( mac );
print( "md5Mac = " + md5Mac );
var p3 = new NameValuePair('Mac', md5Mac);
heads.add(p3)
}catch(e){
print(e);
}
print(">>>>>headers:")
var HttpConnectionClass = Java.type('com.x.base.core.project.connection.HttpConnection');
var docContent =JSON.stringify(pushdata);
print("sendContent:"+docContent);
var resp = HttpConnectionClass.postAsString(url, heads, docContent);
print("返回1:"+ resp.toString());
if(resp.toString()=='{"state":"NMT0001","message":"成功"}'){
this.response.setBody(true);
}else{
this.response.setBody(false);
}
}catch(e){
e.printStackTrace();
result.state = "NMT0002";
result.message = "失败";
result.data = e.name + ": " + e.message
this.response.setBody(false);
}
说明
SSO配置
getToken()方法里面的sso名称和sso密钥配置在“系统设置”里
HttpClientUtilsUpfile类代码
HttpClientUtilsUpfile类代码如下:
package com.z.custom;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.x.base.core.project.tools.Crypto;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import javax.crypto.CipherInputStream;
public class HttpClientUtilsUpfile{
public static final int THREAD_POOL_SIZE = 5;
public interface HttpClientDownLoadProgress{
public void onProgress(int prgetInstanceogress);
}
private static HttpClientUtilsUpfile httpClientDownload;
private ExecutorService downloadExcutorService;
private HttpClientUtilsUpfile(){
downloadExcutorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
}
public static HttpClientUtilsUpfile getInstance(){
if (httpClientDownload == null) {
httpClientDownload = new HttpClientUtilsUpfile();
}
return httpClientDownload;
}
/**
* 下载文件
*
* @param url
* @param filePath
*/
public void download(final String url, final String filePath){ downloadExcutorService.execute(new Runnable() {
public void run(){
httpDownloadFile( url, filePath, null, null);
}
});
}
/**
* 下载文件
*
* @param url
* @param filePath
* @param progress
*
*/
public void download(final String url, final String filePath, final HttpClientDownLoadProgress progress){
downloadExcutorService.execute(new Runnable() {
public void run(){
httpDownloadFile(url, filePath, progress, null);
}
});
}
/**
*下载文件
*
* @param url
* @param filePath
*/
private void httpDownloadFile(String url, String filePath,
HttpClientDownLoadProgress progress, MapheadMap){
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpGet = new HttpGet(url);
setGetHead(httpGet, headMap);
CloseableHttpResponse response1 = httpclient.execute(httpGet);
try {
HttpEntity httpEntity = response1.getEntity();
long contentLength = httpEntity.getContentLength();
InputStream is = httpEntity.getContent();
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int r = 0;
long totalRead = 0;
while ((r = is.read(buffer)) > 0) {
output.write(buffer, 0, r);
totalRead += r;
if (progress != null) {
progress.onProgress((int) (totalRead * 100 / contentLength));
}
}
FileOutputStream fos = new FileOutputStream(filePath);
output.writeTo(fos);
output.flush();
output.close();
fos.close();
EntityUtils.consume(httpEntity);
} finally {
response1.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 发送Get请求
*
* @param url
* @return
*/
public String httpGet(String url){
return httpGet(url, null);
}
/**
* 发送Get请求
*
* @param url
* @return
*/
public String httpGet(String url, MapheadMap){
String responseContent = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response1 = httpclient.execute(httpGet);
setGetHead(httpGet, headMap);
try {
System.out.println(response1.getStatusLine());
HttpEntity entity = response1.getEntity();
responseContent = getRespString(entity);
System.out.println("debug:" + responseContent);
EntityUtils.consume(entity);
} finally {
response1.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
public String httpPost(String url, MapparamsMap){
return httpPost(url, paramsMap, null);
}
/**
* 发送Post请求
*
* @param url
* @param paramsMap
* @return
*/
public String httpPost(String url, MapparamsMap, MapheadMap){
String responseContent = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost(url);
setPostHead(httpPost, headMap);
setPostParams(httpPost, paramsMap);
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
responseContent = getRespString(entity);
EntityUtils.consume(entity);
} finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("responseContent = " + responseContent);
return responseContent;
}
/**
* 设置Post请求的HttpHeader
*
* @param httpPost
* @param headMap
*/
private void setPostHead(HttpPost httpPost, MapheadMap){
if (headMap != null && headMap.size() > 0) {
SetkeySet = headMap.keySet();
for (String key : keySet) {
httpPost.addHeader(key, headMap.get(key));
}
}
}
/**
* 设置Get请求的HttpHeader
*
* @param httpGet
* @param headMap
*/
private void setGetHead(HttpGet httpGet, MapheadMap){
if (headMap != null && headMap.size() > 0) {
SetkeySet = headMap.keySet();
for (String key : keySet) {
httpGet.addHeader(key, headMap.get(key));
}
}
}
/**
* 上传文件的实现方法
*
* @param serverUrl
* @param localFilePath
* @param serverFieldName
* @param params
* @return
* @throws Exception
*/
public String uploadFileImpl(String serverUrl, String localFilePath,String serverFieldName, Mapparams, Mapparamshead)
throws Exception{
String respStr = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost(serverUrl);
setPostHead(httppost, paramshead);
FileBody binFileBody = new FileBody(new File(localFilePath));
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
// add the file params
multipartEntityBuilder.addPart(serverFieldName, binFileBody);
setUploadParams(multipartEntityBuilder, params);
HttpEntity reqEntity = multipartEntityBuilder.build();
httppost.setEntity(reqEntity);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity resEntity = response.getEntity();
respStr = getRespString(resEntity);
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
System.out.println("resp=" + respStr);
return respStr;
}
/**
* 上传文件的实现方法
*
* @param serverUrl
* @param urlFilePath
* @param urlFileName
* @param serverFieldName
* @param params
* @return
* @throws Exception
*/
public String uploadUrlFileImpl(String serverUrl, String urlFilePath,String urlFileName,String serverFieldName, Mapparams, Mapparamshead)
throws Exception{
String respStr = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost(serverUrl);
setPostHead(httppost, paramshead);
FileBody binFileBody = new FileBody(new File(urlFilePath));
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
// add the file params
BufferedInputStream in = getFileInputStream(urlFilePath);
InputStreamBody inputStreamBody = new InputStreamBody(in,urlFileName);
multipartEntityBuilder.addPart(serverFieldName, inputStreamBody);
setUploadParams(multipartEntityBuilder, params);
HttpEntity reqEntity = multipartEntityBuilder.build();
httppost.setEntity(reqEntity);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
respStr = getRespString(resEntity);
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
System.out.println("resp=" + respStr);
return respStr;
}
/**
* 上传文件的实现方法
* 上传前 需要解密
* @param serverUrl 上传附件服务
* @param urlFilePath 附件URL
* @param urlFileName 附件名称
* @param serverFieldName
* @param params 附件参数
* @param paramshead 文件头
* @param skey 密钥
* @param siv 向量
* @return
* @throws Exception
*/
public String uploadByteFileImpl(String serverUrl, String urlFilePath,String urlFileName,String serverFieldName, Mapparams, Mapparamshead,String skey,String siv)
throws Exception{
String respStr = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost(serverUrl);
setPostHead(httppost, paramshead);
//ileBody binFileBody = new FileBody(new File(urlFilePath));
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
// add the file params
BufferedInputStream fis = getFileInputStream(URLDecoder.decode(urlFilePath, "UTF-8" ));;
//解密
CipherInputStream cis = AESFile.decryptedFile(fis,skey,siv);
if(cis != null){
//InputStream inputByteFile = new ByteArrayInputStream(byteFile);
//BufferedInputStream in = new BufferedInputStream(inputByteFile);
InputStreamBody inputStreamBody = new InputStreamBody(cis,urlFileName);
multipartEntityBuilder.addPart(serverFieldName, inputStreamBody);
setUploadParams(multipartEntityBuilder, params);
HttpEntity reqEntity = multipartEntityBuilder.build();
httppost.setEntity(reqEntity);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
respStr = getRespString(resEntity);
EntityUtils.consume(resEntity);
} finally {
response.close();
}
}else{
respStr = "解密失败";
}
} finally {
httpclient.close();
}
System.out.println("resp=" + respStr);
return respStr;
}
/**
* 设置上传时的参数
*
* @param multipartEntityBuilder
* @param params
*/
private void setUploadParams(MultipartEntityBuilder multipartEntityBuilder,
Mapparams){
if (params != null && params.size() > 0) {
Setkeys = params.keySet();
for (String key : keys) {
multipartEntityBuilder.addPart(key, new StringBody(params.get(key),ContentType.APPLICATION_JSON));
}
}
}
/**
* 获取响应内容
*
* @param entity
* @return
* @throws Exception
*/
private String getRespString( HttpEntity entity ) throws Exception{
if (entity == null) {
return null;
}
InputStream is = entity.getContent();
StringBuffer strBuf = new StringBuffer();
byte[] buffer = new byte[4096];
int r = 0;
while ((r = is.read(buffer)) > 0) {
strBuf.append(new String(buffer, 0, r, "UTF-8"));
}
return strBuf.toString();
}
/**
* 设置Post请求发送的参数
*
* @param httpPost
* @param paramsMap
* @throws Exception
*/
private void setPostParams(HttpPost httpPost, MapparamsMap)
throws Exception{
if (paramsMap != null && paramsMap.size() > 0) {
Listnvps = new ArrayList();
SetkeySet = paramsMap.keySet();
for (String key : keySet) {
nvps.add(new BasicNameValuePair(key, paramsMap.get(key)));
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
}
}
/**
* 发送Post请求
* @param url
* @param param
* @return
*/
public static String sendPost(String url, String param){
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
in = new BufferedReader( new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println(" POST"+e);
e.printStackTrace();
}
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
System.out.println(result);
return result;
}
/**
* 根据ssoToken获取人员认证后的真实xtoken
* @param url
* @param client
* @param login_uid
* @param sso_key
* @return
*/
public String getToken(String url, String client, String login_uid, String sso_key ){
long time = new Date().getTime();
String xtoken = null;
try {
xtoken = Crypto.encrypt( login_uid + "#" + time, sso_key );
System.out.println(xtoken);
} catch (Exception e1) {
e1.printStackTrace();
}
String string = "{\"token\": "+xtoken+", \"client\": \""+ client +"\"}";
String str = getInstance().sendPost( url,string );
System.out.println("sso response: " + str );
try {
JsonElement jsonObj = new JsonParser().parse(str);
if( jsonObj != null && jsonObj.getAsJsonObject().get("data") != null ){
JsonObject data = jsonObj.getAsJsonObject().get("data").getAsJsonObject();
System.out.println("getToken: " + data.get("token"));
return data.get("token").getAsString();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private BufferedInputStream getFileInputStream(String urlPath){
BufferedInputStream bin=null;
URL url;
try {
url = new URL(urlPath);
URLConnection urlConnection = url.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
httpURLConnection.setConnectTimeout(1000*5);
httpURLConnection.setRequestMethod("GET");
// 设置字符编码
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.connect();
bin = new BufferedInputStream(httpURLConnection.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
return bin;
}
private InputStream getInputStream(String urlPath){
InputStream bin=null;
URL url;
try {
url = new URL(urlPath);
URLConnection urlConnection = url.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
httpURLConnection.setConnectTimeout(1000*5);
httpURLConnection.setRequestMethod("GET");
// 设置字符编码
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.connect();
bin = httpURLConnection.getInputStream();
} catch (Exception e) {
e.printStackTrace();
}
return bin;
}
public static void main(String[] args) throws IOException, Exception{
}
}
AES加解密
AESFile类代码:
package com.z.custom;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import sun.misc.BASE64Decoder;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.*;
import java.util.Random;
public class AESFile{
@SuppressWarnings("static-access")
//文件加密的实现方法
public static void encryptFile2(String fileName,String encryptedFileName,String sKey,String siv){
try {
//导入支持AES/CBC/PKCS7Padding的Provider
Security.addProvider(new BouncyCastleProvider());
FileInputStream fis = new FileInputStream(fileName);
FileOutputStream fos = new FileOutputStream(encryptedFileName);
byte[] keyValue = sKey.getBytes();
SecretKeySpec encryKey= new SecretKeySpec(keyValue,"AES");//加密秘钥
//byte[] ivValue=new byte[16];
byte[] ivValue = siv.getBytes();
Random random = new Random(System.currentTimeMillis());
random.nextBytes(ivValue);
IvParameterSpec iv = new IvParameterSpec(ivValue);//获取系统时间作为IV
fos.write(ivValue); //记录IV
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
cipher.init(Cipher.ENCRYPT_MODE, encryKey,iv);
CipherInputStream cis=new CipherInputStream(fis, cipher);
byte[] buffer=new byte[1024];
int n=0;
while((n=cis.read(buffer))!=-1){
fos.write(buffer,0,n);
}
cis.close();
fos.close();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
}
}
@SuppressWarnings("static-access")
//文件解密的实现代码 通过文件流
public static CipherInputStream decryptedFile(InputStream fis,String sKey, String siv){
try {
//导入支持AES/CBC/PKCS7Padding的Provider
Security.addProvider(new BouncyCastleProvider());
byte[] keyValue = sKey.getBytes();
SecretKeySpec key= new SecretKeySpec(keyValue,"AES");
byte[] ivValue = siv.getBytes();
//fis.read(ivValue);//获取IV值
IvParameterSpec iv= new IvParameterSpec(ivValue);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
cipher.init(Cipher.DECRYPT_MODE, key,iv);
CipherInputStream cis= new CipherInputStream(fis, cipher);
return cis;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
} catch (InvalidKeyException e) {
e.printStackTrace();
return null;
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
return null;
} catch (NoSuchPaddingException e) {
e.printStackTrace();
return null;
} catch (NoSuchProviderException e) {
e.printStackTrace();
return null;
}
}
@SuppressWarnings("static-access")
//文件解密的实现代码
public static void decryptedFile2(String encryptedFileName,String decryptedFileName, String sKey, String siv){
try {
//导入支持AES/CBC/PKCS7Padding的Provider
Security.addProvider(new BouncyCastleProvider());
FileInputStream fis = new FileInputStream(encryptedFileName);
FileOutputStream fos = new FileOutputStream(decryptedFileName);
BASE64Decoder decoder = new BASE64Decoder();
//byte[] fileIdentifier=new byte[15];
//byte[] keyValue=new byte[16];
//String sKey= "12345678123456781234567812345678";
byte[] keyValue = sKey.getBytes();
//fis.read(keyValue);//读记录的文件加密密码的消息摘要
//fis.read(fileIdentifier);
//System.out.println("file=="+new String(fileIdentifier,"UTF-8"));
//if(new String (fileIdentifier).equals("MyFileEncryptor")){
SecretKeySpec key= new SecretKeySpec(keyValue,"AES");
//byte[] ivValue= new byte[16];
//String siv = "1234567812345678";
byte[] ivValue = siv.getBytes();
//fis.read(ivValue);//获取IV值
IvParameterSpec iv= new IvParameterSpec(ivValue);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
cipher.init(Cipher.DECRYPT_MODE, key,iv);
CipherInputStream cis= new CipherInputStream(fis, cipher);
byte[] buffer=new byte[1024];
int n=0;
while((n=cis.read(buffer))!=-1){
fos.write(buffer,0,n);
}
cis.close();
fos.close();
//JOptionPane.showMessageDialog(null, "解密成功");
//}else{
//JOptionPane.showMessageDialog(null, "文件不是我加密的,爱找谁着谁去");
//}
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
}
}
}
MD5加密
package com.z.custom;
import org.apache.commons.codec.digest.DigestUtils;
import java.math.BigInteger;
import java.security.MessageDigest;
/**
* MD5通用类
*
*/
public class MD5Util{
public static String getMD5(String str){
try {
// 生成一个MD5加密计算摘要
MessageDigest md = MessageDigest.getInstance("MD5");
// 计算md5函数
md.update(str.getBytes());
// digest()最后确定返回md5 hash值,返回值为8为字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符
// BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的hash值
String md5=new BigInteger(1, md.digest()).toString(16);
//BigInteger会把0省略掉,需补全至32位
return fillMD5(md5);
} catch (Exception e) {
throw new RuntimeException("MD5加密错误:"+e.getMessage(),e);
}
}
public static String fillMD5(String md5){
return md5.length()==32?md5:fillMD5("0"+md5);
}
/**
* MD5方法
*
* @param text 明文
* @param key 密钥
* @return 密文
* @throws Exception
*/
public static String md5(String text, String key) throws Exception{
//加密后的字符串
String encodeStr=DigestUtils.md5Hex(text + key);
System.out.println("MD5加密后的字符串为:encodeStr="+encodeStr);
return encodeStr;
}
/**
* MD5验证方法
*
* @param text 明文
* @param key 密钥
* @param md5 密文
* @return true/false
* @throws Exception
*/
public static boolean verify( String text, String key, String md5) throws Exception{
//根据传入的密钥进行验证
String md5Text = md5(text, key);
if(md5Text.equalsIgnoreCase(md5))
{
System.out.println("MD5验证通过");
return true;
}
return false;
}
public static void main(String[] args) throws Exception{
String str = "lee81glee81glee81glee81glee81glee81glee81glee81glee81glee81glee81glee81glee81glee81glee81glee81glee81glee81glee81glee81glee81g";
System.out.println("md5:"+getMD5(str));
System.out.println("length:"+getMD5(str).length());
}
}
搭建自定义工程
以上所用到的java类不包含在平台源码中,需要以自定义工程的方式注入到平台中进行使用,搭建自定义工程及开发参考教程:http://www.o2oa.net//course/tuef8c