文末有源码下载地址
问题1: RSA 不能对Excel
问题2: 在做跨平台加解密时, 关于"padding" 的类型改了好几次
问题3: 公钥加密每次加密的结果时不一样的, 用私钥加密结果是相同的
问题4: 虽然公钥加密结果不同,但私钥能正确解码
问题5: C语言设置: RSA_PKCS1_PADDING 和Java语言设置: “RSA/NONE/PKCS1Padding”
问题6: java里密钥是不带头尾格式 和换行格式, 但是C语言使用的密钥是要有头尾和换行格式的
C代码
#include "dialog.h"
#include "ui_dialog.h"
#include "qscrollbar.h"
#include "qfiledialog.h"
#include "qdebug.h"
#include "qcheckbox.h"
#include "qdesktopservices.h"
#include "openssl/rsa.h"
#include <openssl/pem.h>
#include <openssl/bn.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/bn.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include "openssl/ssl.h"
#include "openssl/err.h"
uchar g_public_key[] = "-----BEGIN PUBLIC KEY-----\n" \
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC32V2IAfotG8bZhPF8/Bx8y65g\n"\
"EDycAMyTWmvpPCfagEKORO/WvdkTYim7yhG/+pMs58wu86edP3LOK73VVlG1eeOg\n"\
"shGVLsKRMYkFRFJ2a81VL2eOaZ8EyZazJ9bkGbNz+JRecx4LkPHdEZTRiSr7zQxN\n"\
"f0UWR9Dxna1T7/C3twIDAQAB\n"\
"-----END PUBLIC KEY-----";
uchar g_private_key[] = "-----BEGIN RSA PRIVATE KEY-----\n"
"MIICXQIBAAKBgQC32V2IAfotG8bZhPF8/Bx8y65gEDycAMyTWmvpPCfagEKORO/W\n"\
"vdkTYim7yhG/+pMs58wu86edP3LOK73VVlG1eeOgshGVLsKRMYkFRFJ2a81VL2eO\n"\
"aZ8EyZazJ9bkGbNz+JRecx4LkPHdEZTRiSr7zQxNf0UWR9Dxna1T7/C3twIDAQAB\n"\
"AoGBAIS0EDAhBTzUJOdTb6AAtmtZ9eb/MVCFvyTJisTSmA2+sMvSdLAzXuH/5BHZ\n"\
"nJBPRTaPpjFpzF3Ts4GfzymTYev762lDaVNTId/md6mOcDHdkrBMpjLQcdJa8kv4\n"\
"2gdxb9+1N+6X4wRh7DyIsow2gCKwrWE1rpf3M7xnqIBI3qSpAkEA3VzD/PAU9aDn\n"\
"i3VJwEsML2eTJ52FdVAUtlvfaSnbUIgnTHNldCjVQUyT99bLs5FsRILnxM1+iFmH\n"\
"dVUvZgGN6wJBANSd6NdtTcijOqy9wb/cqTaInCLNObGmLOHSrJcngpWOXtrrk5ZV\n"\
"9JpKiNFycvM0j6+WS0aVERWjb3xo9msarmUCQAk1IJnWyqhk5vywBj9PX9Rg9IgD\n"\
"T1fP2uyy6ZoQOaUh5LCTZDbus+AhdU4ryxFPDTfUUhuniInXX4EL6ArQKb0CQCY9\n"\
"XGJag1Hhoazt2An02u429bYAqS69T3cyF957ua3CVGcVVY8FWJ/jZeYdqnT5cBpJ\n"\
"crJ4HwGASo3apu8udk0CQQCzJ28e0WVCIwxgYK81FZgTxusaSjtkv4Dbz0BXvZLH\n"\
"NX6zYO1fqM1Cm/FMqGtPvI8/O3AVJrcNeo4lgKvyDQVv\n"\
"-----END RSA PRIVATE KEY-----";
#define RSA_LENGTH 1024
// define rsa public key
#define BEGIN_RSA_PUBLIC_KEY "BEGIN RSA PUBLIC KEY"
#define BEGIN_PUBLIC_KEY "BEGIN PUBLIC KEY"
/**
* @brief Dialog::createRSA 载入密钥
* @param key 密钥
* @param publi 公钥1 私钥0
* @return
*/
RSA * Dialog::createRSA(unsigned char * key,int publi)
{
BIO *keybio ;
keybio = BIO_new_mem_buf(key, strlen((char*)key));
if (keybio==NULL)
{
qDebug()<< "Failed to create key BIO";
return 0;
}
RSA* pRsa = RSA_new();
if(publi)
{
pRsa = PEM_read_bio_RSA_PUBKEY(keybio, &pRsa,NULL, NULL);
}
else
{
pRsa = PEM_read_bio_RSAPrivateKey(keybio, &pRsa,NULL, NULL);
}
if(pRsa == NULL)
{
qDebug()<< "Failed to create RSA";
BIO_free_all(keybio);
}
return pRsa;
}
/**
* @brief Dialog::public_encrypt 公钥加密
* @param data 待加密数据
* @param data_len 待加密的数据长度
* @param key 公钥
* @param encrypted 加密后的数据
* @return 加密长度
*/
int Dialog::public_encrypt(unsigned char * data,int data_len,unsigned char * key, unsigned char *encrypted)
{
RSA * rsa = createRSA(key,1);
if(rsa==NULL)
return 0;
rsaResult = RSA_public_encrypt(data_len,data,encrypted,rsa,RSA_PKCS1_PADDING);
return rsaResult;
}
/**
* @brief Dialog::private_decrypt 私钥解密
* @param enc_data 待解密数据
* @param data_len 待解密数据长度
* @param key 私钥
* @param decrypted 解密后的数据
* @return
*/
int Dialog::private_decrypt(unsigned char * enc_data,int data_len,unsigned char * key, unsigned char *decrypted)
{
RSA * rsa = createRSA(key,0);
if(rsa==NULL)
return 0;
int rsaResult = RSA_private_decrypt(data_len,enc_data,decrypted,rsa,RSA_PKCS1_PADDING);
return rsaResult;
}
/**
* @brief Dialog::private_encrypt 私钥加密
* @param data 待加密数据
* @param data_len 待加密数据长度
* @param key 私钥
* @param encrypted 加密后数据
* @return
*/
int Dialog::private_encrypt(unsigned char * data,int data_len,unsigned char * key, unsigned char *encrypted)
{
RSA * rsa = createRSA(key,0);
if(rsa==NULL)
return 0;
qDebug()<<RSA_size(rsa);
int rsaResult = RSA_private_encrypt(data_len,data,encrypted,rsa,RSA_PKCS1_PADDING );
return rsaResult;
}
/**
* @brief Dialog::public_decrypt 公钥解密
* @param enc_data 待解密数据
* @param data_len 待解密数据长度
* @param key 公钥
* @param decrypted 解密后的数据
* @return
*/
int Dialog::public_decrypt(unsigned char * enc_data,int data_len,unsigned char * key, unsigned char *decrypted)
{
RSA * rsa = createRSA(key,1);
if(rsa==NULL)
return 0;
qDebug()<<RSA_size(rsa);
int rsaResult = RSA_public_decrypt(data_len,enc_data,decrypted,rsa,RSA_PKCS1_PADDING );
return rsaResult;
}
/**
* @brief Dialog::public_encrypt 公钥加密
* @param data 待加密数据
* @param keystr 公钥
* @param encrypted 加密后数据
* @return
*/
int Dialog::public_encrypt(QString &data,QString &keystr,QString &encrypted)
{
QByteArray keydata=keystr.toLocal8Bit();
unsigned char *key= (unsigned char*)strdup(keydata.constData());//密钥
RSA * rsa = createRSA(key,1);
if(rsa==NULL)
return 0;
free(key);
int rsasize=RSA_size(rsa);
int exppadding=rsasize;
int rsaResult=-1;
// QByteArray decdata=QByteArray::fromStdString(data.toStdString()).toBase64(QByteArray::Base64Encoding);
QByteArray decdata=data.toUtf8();
QByteArray signByteArray;
int data_len=decdata.length();
if(data_len>exppadding-11)
exppadding=exppadding-11;
int b=0;
int s=data_len/(exppadding);//片数
if(data_len%(exppadding))
s++;
for(int i=0;i<s;i++)
{
QByteArray subdata;
subdata.clear();
for(int j=0;j<exppadding;j++)
{
if(i*exppadding+j>data_len)
break;
subdata[j]=decdata[j+i*exppadding];
}
unsigned char *smldata=(unsigned char*)strdup(subdata.constData());//数据分片
unsigned char smlencrypted[1024]={0};//片段加密数据
b +=RSA_public_encrypt(exppadding,smldata,smlencrypted,rsa,RSA_PKCS1_PADDING);
if(b>0)
{
QByteArray subarray=QByteArray::fromRawData((const char *)smlencrypted,rsasize);
signByteArray.append(subarray);
}
free(smldata);
}
QString str(signByteArray.toHex());
qDebug()<<str;
encrypted.append(str);
rsaResult=b;
return rsaResult;
}
/**
* @brief Dialog::private_decrypt 私钥解密
* @param data 待解密数据
* @param keystr 私钥
* @param decrypted 解密后的数据
* @return
*/
int Dialog::private_decrypt(QString &data,QString &keystr,QString &decrypted)
{
QByteArray keydata=keystr.toLocal8Bit();
unsigned char *key= (unsigned char*)strdup(keydata.constData());//密钥
RSA * rsa = createRSA(key,0);
if(rsa==NULL)
return 0;
free(key);
int rsasize=RSA_size(rsa);
int rsaResult=-1;
QByteArray encdata=QByteArray::fromHex(QByteArray::fromStdString( data.toStdString()));
QByteArray signByteArray;
int data_len=encdata.length();
int b=0;
int s=data_len/(rsasize);//片数
if(data_len%(rsasize))
s++;
for(int i=0;i<s;i++)
{
QByteArray subdata;
subdata.clear();
for(int j=0;j<rsasize;j++)
{
if(i*rsasize+j>data_len)
break;
subdata[j]=encdata[j+i*rsasize];
}
unsigned char *smldata=(unsigned char*)subdata.data();//(unsigned char*)strdup(subdata.constData());//数据分片
unsigned char smlencrypted[1024]={0};//片段加密数据
b +=RSA_private_decrypt(rsasize,smldata,smlencrypted,rsa,RSA_PKCS1_PADDING);
if(b>0)
{
QByteArray decdata((char*)smlencrypted);
signByteArray.append(decdata);
}
}
// QByteArray b1= QByteArray::fromBase64(signByteArray,QByteArray::Base64Encoding);
QByteArray b1= signByteArray;
std::string str=b1.toStdString();
decrypted.append(QString::fromStdString( str));
rsaResult=b;
return rsaResult;
}
/**
* @brief Dialog::private_encrypt 私钥加密
* @param data 待加密数据
* @param keystr 私钥
* @param encrypted 解密后的数据
* @return
*/
int Dialog::private_encrypt(QString &data,QString &keystr,QString &encrypted)
{
QByteArray keydata=keystr.toLocal8Bit();
unsigned char *key= (unsigned char*)strdup(keydata.constData());//密钥
RSA * rsa = createRSA(key,0);
if(rsa==NULL)
return 0;
free(key);
int rsasize=RSA_size(rsa);
int exppadding=rsasize;
int rsaResult=-1;
// QByteArray decdata=QByteArray::fromStdString(data.toStdString()).toBase64(QByteArray::Base64Encoding);
QByteArray decdata=QByteArray::fromStdString(data.toStdString());
QByteArray signByteArray;
int data_len=decdata.length();
if(data_len>exppadding-11)//padding占11位
exppadding=exppadding-11;
int b=0;
int s=data_len/(exppadding);//片数
if(data_len%(exppadding))
s++;
for(int i=0;i<s;i++)
{
//分片加密
QByteArray subdata;
subdata.clear();;
for(int j=0;j<exppadding;j++)
{
if(i*exppadding+j>data_len)
break;
subdata[j]=decdata[j+i*exppadding];
}
unsigned char *smldata=(unsigned char*)strdup(subdata.constData());//数据分片
unsigned char smlencrypted[1024]={0};//片段加密数据
b +=RSA_private_encrypt(exppadding,smldata,smlencrypted,rsa,RSA_PKCS1_PADDING);
if(b>0)
{
QByteArray subarray=QByteArray::fromRawData((const char *)smlencrypted,rsasize);
signByteArray.append(subarray);
}
free(smldata);
}
QString str(signByteArray.toHex());
qDebug()<<str;
encrypted.append(str);
rsaResult=b;
return rsaResult;
}
/**
* @brief Dialog::public_decrypt 公钥解密
* @param data 待解密数据
* @param keystr 公钥
* @param decrypted 解密后的数据
* @return
*/
int Dialog::public_decrypt(QString &data,QString &keystr,QString &decrypted)
{
QByteArray keydata=keystr.toLocal8Bit();
unsigned char *key= (unsigned char*)strdup(keydata.constData());//密钥
RSA * rsa = createRSA(key,1);
if(rsa==NULL)
return 0;
free(key);
int rsasize=RSA_size(rsa);
int rsaResult=-1;
QByteArray encdata=QByteArray::fromHex(QByteArray::fromStdString( data.toStdString()));
QByteArray signByteArray;
int data_len=encdata.length();
int b=0;
int s=data_len/(rsasize);//片数
if(data_len%(rsasize))
s++;
for(int i=0;i<s;i++)
{
QByteArray subdata;
subdata.clear();
for(int j=0;j<rsasize;j++)
{
if(i*rsasize+j>data_len)
break;
subdata[j]=encdata[j+i*rsasize];
}
unsigned char *smldata=(unsigned char*)subdata.data();//(unsigned char*)strdup(subdata.constData());//数据分片
unsigned char smlencrypted[1024]={0};//片段加密数据
b +=RSA_public_decrypt(rsasize,smldata,smlencrypted,rsa,RSA_PKCS1_PADDING);
if(b>0)
{
QByteArray decdata((char*)smlencrypted);
signByteArray.append(decdata);
}
}
// QByteArray b1= QByteArray::fromBase64(signByteArray,QByteArray::Base64Encoding);
QByteArray b1=signByteArray;
std::string str=b1.toStdString();
decrypted.append(QString::fromStdString( str));
rsaResult=b;
return rsaResult;
}
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
this->setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint | Qt::WindowSystemMenuHint | Qt::WindowStaysOnTopHint);
uiInit();
setStyle(this,"./image/opdetail.qss");
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::uiInit()
{
ui->lb_logo->setStyleSheet("border-image:url(./image/logo.png);");
ui->pb_min->setStyleSheet("border-image:url(./image/min.png);");
ui->pb_close->setStyleSheet("border-image:url(./image/m_close.png);");
ui->le_dir->setEnabled(false);
ui->le_dir->setText("./");
initTable();
}
/*读取样式*/
bool Dialog::setStyle(QWidget *widget, QString qssFile)
{
if(qssFile.isEmpty() || widget == NULL)
{
return false;
}
QFile qss(qssFile);
qss.open(QFile::ReadOnly);
if(qss.isOpen())
{
QString qssstr = QLatin1String(qss.readAll());
widget->setStyleSheet(qssstr);
qss.close();
return true;
}
return false;
}
int Dialog::fileDecode(QString fileName)
{
unsigned short data[1024];
unsigned short data2[1024];
char *ch, *cch;
QStringList nameList = fileName.split("/");
QByteArray ba = fileName.toUtf8();
ch=ba.data();
int readLen = 0;
int deLen = 0;
FILE *fp = fopen(ch, "rb");
QString d_fileName = "";
d_fileName = ui->le_dir->text()+"d_"+nameList.at(nameList.count()-1);
QByteArray baa = d_fileName.toUtf8();
cch=baa.data();
FILE *fp_e = fopen(cch, "wb");
if(NULL != fp && NULL != fp_e)
{
fseek (fp , 0 , SEEK_SET);
fseek (fp_e , 0 , SEEK_SET);
memset(data, 0, RSA_LENGTH);
memset(data2, 0, RSA_LENGTH);
// 加密
// while(readLen = fread(data, 1, RSA_LENGTH/8-11, fp))
// {
// deLen = public_decrypt((uchar*)data, readLen, g_public_key, (uchar*)data2 );
// 解密
while(readLen = fread(data, 1, RSA_LENGTH/8, fp))
{
deLen = private_decrypt((uchar*)data, readLen, g_private_key, (uchar*)data2 );
if(deLen < 0)
{
qDebug()<<"private_decrpt decode error";
break;
}
fwrite(data2, deLen, 1, fp_e);
memset(data, 0, RSA_LENGTH);
memset(data2, 0, RSA_LENGTH);
if(readLen < RSA_LENGTH/8)
{
break;
}
}
fclose(fp_e);
fclose(fp);
}
}
void Dialog::decodeUseIndex(int row)
{
// 开始解密
QWidget *w = ui->tableWidget->cellWidget(row, 3);
QPushButton * pb = qobject_cast<QPushButton*>(w->children().at(1));
pb->setStyleSheet("border-image:url(./image/stop_1.png);");
pb->setEnabled(false);
pb = qobject_cast<QPushButton*>(w->children().at(2));
pb->setEnabled(false);
pb = qobject_cast<QPushButton*>(w->children().at(3));
pb->setStyleSheet("border-image:url(./image/close_1.png);");
pb->setEnabled(false);
fileDecode(tr("%1").arg(ui->tableWidget->item(row,4)->text()));
// 解密完成
ui->tableWidget->item(row,2)->setText(tr("解密完成"));
w = ui->tableWidget->cellWidget(row, 3);
pb = qobject_cast<QPushButton*>(w->children().at(1));
pb->setEnabled(false);
pb = qobject_cast<QPushButton*>(w->children().at(2));
pb->setStyleSheet("border-image:url(./image/folder.png);");
pb->setEnabled(true);
pb = qobject_cast<QPushButton*>(w->children().at(3));
pb->setStyleSheet("border-image:url(./image/close.png);");
pb->setEnabled(true);
}
QString Dialog::setDir()
{
QString file_path = QFileDialog::getExistingDirectory(this, "请选择文件路径...", "./");
if(!file_path.isEmpty())
{
return file_path;
}else
{
return "./";
}
}
void Dialog::initTable()
{
QHeaderView* headerView = ui->tableWidget->verticalHeader();
headerView->setHidden(true);
ui->tableWidget->setColumnCount(5);
ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectItems);
ui->tableWidget->setHorizontalHeaderItem(0,new QTableWidgetItem(" "));
ui->tableWidget->setHorizontalHeaderItem(1,new QTableWidgetItem("文件名"));
ui->tableWidget->setHorizontalHeaderItem(2,new QTableWidgetItem("状态"));
ui->tableWidget->setHorizontalHeaderItem(3,new QTableWidgetItem("操作"));
ui->tableWidget->setHorizontalHeaderItem(4,new QTableWidgetItem("路径"));
ui->tableWidget->verticalHeader()->setVisible(false);
ui->tableWidget->horizontalHeader()->setVisible(true);
// 自由伸缩
// ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
ui->tableWidget->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
ui->tableWidget->setMouseTracking(true);
ui->tableWidget->setShowGrid(false);//隐藏网格
ui->tableWidget->horizontalHeader()->setHighlightSections(false);//表头不塌陷
ui->tableWidget->horizontalHeader()->setSectionsClickable(false);
ui->tableWidget->verticalScrollBar()->setContextMenuPolicy(Qt::NoContextMenu);
ui->tableWidget->horizontalScrollBar()->setContextMenuPolicy(Qt::NoContextMenu);
ui->tableWidget->horizontalHeader()->setMinimumHeight(30);
ui->tableWidget->hideColumn(4);
connect(this, SIGNAL(sig_fileName(QString)),this,SLOT(addFileToTable(QString)));
}
void Dialog::on_pb_min_clicked()
{
this->showMinimized();
}
void Dialog::on_pb_close_clicked()
{
this->close();
}
void Dialog::on_pb_add_clicked()
{
QString fileName = QFileDialog::getOpenFileName(NULL,tr("添加文件"), "./", "File (*.csv)");
if(""!=fileName )
{
emit sig_fileName(fileName);
}
// qDebug()<<fileName
// return fileName;
}
void Dialog::on_pb_clear_clicked()
{
for(int i = ui->tableWidget->rowCount() -1 ; i>=0;i--)
{
ui->tableWidget->removeRow(i);
}
}
void Dialog::addFileToTable(QString fileName)
{
qDebug()<<fileName;
QStringList list = fileName.split("/");
ui->tableWidget->insertRow(ui->tableWidget->rowCount());
int index = ui->tableWidget->rowCount()-1;
QCheckBox *cb = new QCheckBox("");
QWidget* pWidget = new QWidget();
QHBoxLayout* pLayout = new QHBoxLayout(pWidget);
pLayout->addWidget(cb);
pLayout->setAlignment(Qt::AlignCenter);
pLayout->setContentsMargins(0, 0, 0, 0);
pWidget->setLayout(pLayout);
ui->tableWidget->setCellWidget(index,0,pWidget);
ui->tableWidget->setItem(index, 1, new QTableWidgetItem(list.at(list.count()-1)));
ui->tableWidget->setItem(index, 2, new QTableWidgetItem("未解密"));
QPushButton *btn_restart = new QPushButton();
btn_restart->setMaximumSize(20,20);
btn_restart->setStyleSheet("border-image:url(./image/restart.png);");
QPushButton *btn_forder = new QPushButton();
btn_forder->setMaximumSize(20,20);
btn_forder->setStyleSheet("border-image:url(./image/folder_1.png);");
QPushButton *btn_close_1 = new QPushButton();
btn_close_1->setMaximumSize(20,20);
btn_close_1->setStyleSheet("border-image:url(./image/close.png);");
// QPushButton *btn_2 = new QPushButton();
// btn_2->setText(tr("修改"));
QWidget *tmp_widget = new QWidget();
QHBoxLayout *tmp_layout = new QHBoxLayout(tmp_widget);
tmp_layout->addWidget(btn_restart);
tmp_layout->addSpacing(10);
tmp_layout->addWidget(btn_forder);
tmp_layout->addSpacing(10);
tmp_layout->addWidget(btn_close_1);
tmp_layout->setAlignment(Qt::AlignCenter);
// tmp_layout->addWidget(btn_2);
tmp_layout->setContentsMargins(0, 0, 0, 0);
ui->tableWidget->setCellWidget(index,3,tmp_widget);
ui->tableWidget->setItem(index, 4, new QTableWidgetItem(fileName));
;
ui->tableWidget->item(index, 1)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
ui->tableWidget->item(index, 2)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
// ui->tableWidget->item(index, 3)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
btn_restart->setObjectName("select");
btn_restart->setProperty("index",index);
btn_forder->setObjectName("select");
btn_forder->setProperty("index",index);
btn_close_1->setObjectName("select");
btn_close_1->setProperty("index",index);
connect(btn_restart, SIGNAL(clicked()), this, SLOT(restartClicked()));
connect(btn_forder, SIGNAL(clicked()), this, SLOT(folderClicked()));
connect(btn_close_1, SIGNAL(clicked()), this, SLOT(close_1Clicked()));
}
void Dialog::restartClicked()
{
int row = 0;
QPushButton *senderObj = qobject_cast<QPushButton*>(sender());
if(senderObj == Q_NULLPTR)
{
return;
}
qDebug()<<(tr("restartClicked row [%1]").arg(senderObj->property("index").toString()));
if(!senderObj->property("index").toString().isEmpty())
{
row = senderObj->property("index").toInt();
}
decodeUseIndex(row);
}
void Dialog::folderClicked()
{
int row = 0;
QPushButton *senderObj = qobject_cast<QPushButton*>(sender());
if(senderObj == Q_NULLPTR)
{
return;
}
qDebug()<<(tr("folderClicket row [%1]").arg(senderObj->property("index").toString()));
if(!senderObj->property("index").toString().isEmpty())
{
row = senderObj->property("index").toInt();
}
QString tmpFile = ui->tableWidget->item(row,1)->text();
QString tmpFileDir = ui->tableWidget->item(row,4)->text();
int dirLen = tmpFileDir.length();
QString fileDir = tmpFileDir.left(dirLen -1 -tmpFile.length());
qDebug()<<"folderClicked"<<fileDir;
QDesktopServices::openUrl(QUrl(fileDir, QUrl::TolerantMode));
}
void Dialog::close_1Clicked()
{
int row = 0;
QPushButton *senderObj = qobject_cast<QPushButton*>(sender());
if(senderObj == Q_NULLPTR)
{
return;
}
qDebug()<<(tr("close_1Clicked row [%1]").arg(senderObj->property("index").toString()));
if(!senderObj->property("index").toString().isEmpty())
{
row = senderObj->property("index").toInt();
}
ui->tableWidget->removeRow(row);
}
void Dialog::on_pb_start_clicked()
{
for(int i = ui->tableWidget->rowCount() -1 ; i>=0;i--)
{
QWidget *w = ui->tableWidget->cellWidget(i, 0);
// qobject_cast<QComboBox*>(tb_Device->cellWidget(index, MAIN_AutoBtn))
QCheckBox * checkBox = qobject_cast<QCheckBox*>(w->children().at(1));
if(checkBox->checkState() == Qt::Checked)
{
decodeUseIndex(i);
checkBox->setChecked(Qt::Unchecked);
}
}
}
void Dialog::on_pb_dir_clicked()
{
ui->le_dir->setText(tr("%1").arg(setDir()));
}
Java
import android.content.res.AssetManager;
import android.text.TextUtils;
import com.winspread.intelligent.station.base.app.App;
import org.apache.commons.codec.binary.Base64;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.Scanner;
import javax.crypto.Cipher;
public class RSAUtils {
public static int KEY_SIZE = 1024;
public static final int PRIVATE_KEY = 1;
public static final int PUBLIC_KEY = 2;
public static final boolean pri = false;
/**
* 文件加密
*
* @param path1
* @param path2
*/
public static boolean encrypt(String path1, String path2, boolean del) {
try {
if (pri) {
AssetManager am = App.mContext.getAssets();
InputStream is = am.open("rsakey/rsaPriKey");
String privateKey = new Scanner(is).next();
encrypt(path1, path2, privateKey, PRIVATE_KEY);
} else {
AssetManager am = App.mContext.getAssets();
InputStream is = am.open("rsakey/rsaPubKey");
String privateKey = new Scanner(is).next();
encrypt(path1, path2, privateKey, PUBLIC_KEY);
}
// 删除文件
if (del)
new File(path1).delete();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 文件解密
*
* @param path1
* @param path2
*/
public static boolean decrypt(String path1, String path2) {
try {
// 读取公钥值
AssetManager am = App.mContext.getAssets();
if (pri) {
InputStream is = am.open("rsakey/rsaPubKey");
String pubKey = new Scanner(is).next();
decrypt(path1, path2, pubKey, PUBLIC_KEY);
} else {
// 解密方法 (生成解密文件)
InputStream is = am.open("rsakey/rsaPriKey");
String pubKey = new Scanner(is).next();
decrypt(path1, path2, pubKey, PRIVATE_KEY);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 生成密钥对保存到文件中
*
* @throws Exception
*/
public static void genKeyPair() throws Exception {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(KEY_SIZE, new SecureRandom());
// 生成一个密钥对,保存在keyPair中
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 得到私钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 得到公钥
// 得到公钥字符串
String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
android.util.Base64.encodeToString(publicKey.getEncoded(), android.util.Base64.NO_WRAP);
System.out.println("公钥");
System.out.println(publicKeyString);
// 得到私钥字符串
String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
android.util.Base64.encodeToString(privateKey.getEncoded(), android.util.Base64.NO_WRAP);
System.out.println("私钥");
System.out.println(privateKeyString);
}
/**
* 加密(删除原文件)
*
* @param path1 源文件目录
* @param path2 目标文件目录
* @param key 密钥
* @param keyType 密钥类型
* @throws Exception
*/
public static void encrypt(String path1, String path2, String key, int keyType) throws Exception {
// encryptTest(key, keyType);
File file1 = new File(path1);
File file2 = new File(path2);
createFile(path2);
FileInputStream ins = new FileInputStream(file1);
FileOutputStream outs = new FileOutputStream(file2);
int block_size = (KEY_SIZE / 8) - 11;
int datalen = ins.available();
for (int i = 0; i < datalen; i += block_size) {
byte[] bytes = new byte[block_size];
int len = (i + block_size) > datalen ? (int) (datalen - i) : block_size;
ins.read(bytes, 0, len);
byte[] result = encrypt(bytes, key, keyType);
outs.write(result, 0, result.length);
}
outs.flush();
// 关闭流
outs.close();
ins.close();
}
/**
* @param inputBytes
* @param key
* @return
* @throws Exception
*/
public static byte[] encrypt(byte[] inputBytes, String key, int keyType) throws Exception {
//base64编码的密钥
byte[] decoded = android.util.Base64.decode(key, android.util.Base64.DEFAULT);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
//RSA解密
Cipher cipher = Cipher.getInstance("RSA/NONE/PKCS1Padding");
switch (keyType) {
case PRIVATE_KEY:
RSAPrivateKey priKey = (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(decoded));
cipher.init(Cipher.ENCRYPT_MODE, priKey);
break;
case PUBLIC_KEY:
RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(new X509EncodedKeySpec(decoded));
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
break;
default:
throw new Exception("UnKnown Key Type");
}
return cipher.doFinal(inputBytes);
}
/**
* 解密
*
* @param path1 源文件目录
* @param path2 目标文件目录
* @param key 密钥
* @param keyType 密钥类型
* @throws Exception
*/
public static void decrypt(String path1, String path2, String key, int keyType) throws Exception {
// decryptTest(key, keyType);
File file1 = new File(path1);
File file2 = new File(path2);
FileInputStream ins = new FileInputStream(file1);
FileOutputStream outs = new FileOutputStream(file2);
int block_size = KEY_SIZE / 8;
int datalen = ins.available();
for (int i = 0; i < datalen; i += block_size) {
byte[] bytes = new byte[block_size];
int len = (i + block_size) > datalen ? (int) (datalen - i) : block_size;
ins.read(bytes, 0, len);
byte[] result = decrypt(bytes, key, keyType);
outs.write(result, 0, result.length);
}
outs.flush();
outs.close();
ins.close();
}
/**
* @param inputBytes
* @param key
* @param keyType
* @return
* @throws Exception
*/
public static byte[] decrypt(byte[] inputBytes, String key, int keyType) throws Exception {
//base64编码的密钥
byte[] decoded = android.util.Base64.decode(key, android.util.Base64.DEFAULT);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
//RSA解密
Cipher cipher = Cipher.getInstance("RSA/NONE/PKCS1Padding");
switch (keyType) {
case PRIVATE_KEY:
RSAPrivateKey priKey = (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(decoded));
cipher.init(Cipher.DECRYPT_MODE, priKey);
break;
case PUBLIC_KEY:
RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(new X509EncodedKeySpec(decoded));
cipher.init(Cipher.DECRYPT_MODE, pubKey);
break;
default:
throw new Exception("UnKnown Key Type");
}
return cipher.doFinal(inputBytes);
}
/**
* 创建多级目录文件
*
* @param path 文件路径
* @throws IOException
*/
public static void createFile(String path) throws IOException {
if (!TextUtils.isEmpty(path)) {
File file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
}
}
private static void encryptTest(String key, int keyType) throws Exception {
String s = "ceshi123";
byte[] bytes2 = s.getBytes("UTF-8");
byte[] result2 = encrypt(bytes2, key, keyType);
System.out.println(Arrays.toString(result2));
StringBuffer sb = new StringBuffer();
for (byte b : result2) {
int hi = ((b >> 4) & 0x0F);
//得到低四位
int lo = (b & 0x0F);
char[] hex = new char[2];
//如果高四位是大于9的,将其转换成字符a-z, 最后要将得到的转换成字符(char)类型,不然得到的是二进制数
hex[0] = hi > 9 ? (char) (hi - 10 + 'a') : (char) (hi + '0');
hex[1] = lo > 9 ? (char) (lo - 10 + 'a') : (char) (lo + '0');
sb.append(new String(hex));
}
System.out.println(sb.toString());
String s1 = android.util.Base64.encodeToString(result2, android.util.Base64.NO_WRAP);
System.out.println(s1);
}
private static void decryptTest(String key, int keyType) throws Exception {
String s = "";
byte[] bytes2 = s.getBytes("UTF-8");
byte[] result2 = encrypt(bytes2, key, keyType);
String s1 = android.util.Base64.encodeToString(result2, android.util.Base64.NO_WRAP);
System.out.println(s1);
}
}
源码下载:
https://download.csdn.net/download/zhf6751134/20235609 (C 源码)
https://download.csdn.net/download/zhf6751134/20235604 (java 源码)