java rsa 文件加密解密_RSA 加密、解密(自己生成加密解密文件)

本文详细介绍了如何使用Java实现RSA加密解密,包括生成公钥私钥文件的步骤,涉及OpenSSL命令行工具,以及iOS端的证书导入和使用。通过创建工具类RSAEncryptor,实现了字符串和数据的RSA加密解密操作。
摘要由CSDN通过智能技术生成

本文是自己阅读了网上的高人们的文章之后,实现功能后总结出来的,方便自己方便他人,不喜勿喷

加密解密需要生成公钥、私钥文件步骤

1.打开终端 输入

openssl

c246f7e6fd92

5F88AA4A-3913-4CBC-9307-00ED47557FCD.png

2.生成私钥文件

输入:

genrsa -out private_key.pem 1024

genrsa:指定了生成了算法使用RSA

-out:后面的参数表示生成的key的输入文件

1024:表示的是生成key的长度,单位字节(bits)

c246f7e6fd92

EC31F55E-1142-49CD-A3B9-BBF435950F27.png

c246f7e6fd92

D9AD9E8E-43EE-4352-A2CC-A3787076AC51.png

若找不到该文件可全局搜索该名字

3.创建证书请求

输入:

req -new -key private_key.pem -out rsaCertReq.csr

会让输入一些信息,可填可不填

c246f7e6fd92

4405C579-7C91-4F72-A8C8-B23727AC9F4F.png

4.生成证书并签名,有效期10年

输入:

x509 -req -days 3650 -in rsaCertReq.csr -signkey private_key.pem -out rsaCert.crt

c246f7e6fd92

41C14307-493D-417B-967E-8CA6196A1344.png

5.转换格式 将 PEM 格式文件 转换成 DER 格式 ,此为公钥文件,项目中用得到

输入:

x509 -outform der -in rsaCert.crt -out public_key.der

c246f7e6fd92

0DBCD317-806A-4779-BA19-8E2C060CEEA0.png

c246f7e6fd92

9E1FB8E4-DBAA-425F-8879-3A839A09234A.png

6.导出 P12 文件,此为私钥文件。项目中用得到

输入:

pkcs12 -export -out private_key.p12 -inkey private_key.pem -in rsaCert.crt

会让输入密码,记住该密码,程序中会用得到

c246f7e6fd92

64F45FBA-74A6-4BF5-A4E1-88D324057E0B.png

7.给Java创建 rsa_public_key.pem

输入:

rsa -in private_key.pem -out rsa_public_key.pem -pubout

8.给Java创建 pkcs8_private_key.pem

输入:

pkcs8 -topk8 -in private_key.pem -out pkcs8_private_key.pem -nocrypt

c246f7e6fd92

CC811457-3CDB-43C7-ACA1-3150602A845F.png

证书已经创建完毕

c246f7e6fd92

DBB2A1A7-E042-4860-BF39-FFC524D08F8F.png

iOS使用证书

先请你把 public_key.der 和 private_key.p12 拖进你的Xcode项目里去

同时引入 Security.framework 以及 NSData+Base64.h/m (github可下载)到项目里。

为了使用方便,可引入工具类,代码如下:

@interface RSAEncryptor : NSObject

-(void) loadPublicKeyFromFile: (NSString*) derFilePath;

-(void) loadPublicKeyFromData: (NSData*) derData;

-(void) loadPrivateKeyFromFile: (NSString*) p12FilePath password:(NSString*)p12Password;

-(void) loadPrivateKeyFromData: (NSData*) p12Data password:(NSString*)p12Password;

-(NSString*) rsaEncryptString:(NSString*)string;

-(NSData*) rsaEncryptData:(NSData*)data ;

-(NSString*) rsaDecryptString:(NSString*)string;

-(NSData*) rsaDecryptData:(NSData*)data;

+(void) setSharedInstance: (RSAEncryptor*)instance;

+(RSAEncryptor*) sharedInstance;

@end

#import "RSAEncryptor.h"

#import "Base64.h"

#import

@implementation RSAEncryptor

{

SecKeyRef publicKey;

SecKeyRef privateKey;

}

-(void)dealloc

{

CFRelease(publicKey);

CFRelease(privateKey);

}

-(SecKeyRef) getPublicKey {

return publicKey;

}

-(SecKeyRef) getPrivateKey {

return privateKey;

}

-(void) loadPublicKeyFromFile: (NSString*) derFilePath

{

NSData *derData = [[NSData alloc] initWithContentsOfFile:derFilePath];

[self loadPublicKeyFromData: derData];

}

-(void) loadPublicKeyFromData: (NSData*) derData

{

publicKey = [self getPublicKeyRefrenceFromeData: derData];

}

-(void) loadPrivateKeyFromFile: (NSString*) p12FilePath password:(NSString*)p12Password

{

NSData *p12Data = [NSData dataWithContentsOfFile:p12FilePath];

[self loadPrivateKeyFromData: p12Data password:p12Password];

}

-(void) loadPrivateKeyFromData: (NSData*) p12Data password:(NSString*)p12Password

{

privateKey = [self getPrivateKeyRefrenceFromData: p12Data password: p12Password];

}

#pragma mark - Private Methods

-(SecKeyRef) getPublicKeyRefrenceFromeData: (NSData*)derData

{

SecCertificateRef myCertificate = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)derData);

SecPolicyRef myPolicy = SecPolicyCreateBasicX509();

SecTrustRef myTrust;

OSStatus status = SecTrustCreateWithCertificates(myCertificate,myPolicy,&myTrust);

SecTrustResultType trustResult;

if (status == noErr) {

status = SecTrustEvaluate(myTrust, &trustResult);

}

SecKeyRef securityKey = SecTrustCopyPublicKey(myTrust);

CFRelease(myCertificate);

CFRelease(myPolicy);

CFRelease(myTrust);

return securityKey;

}

-(SecKeyRef) getPrivateKeyRefrenceFromData: (NSData*)p12Data password:(NSString*)password

{

SecKeyRef privateKeyRef = NULL;

NSMutableDictionary * options = [[NSMutableDictionary alloc] init];

[options setObject: password forKey:(__bridge id)kSecImportExportPassphrase];

CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);

OSStatus securityError = SecPKCS12Import((__bridge CFDataRef) p12Data, (__bridge CFDictionaryRef)options, &items);

if (securityError == noErr && CFArrayGetCount(items) > 0) {

CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);

SecIdentityRef identityApp = (SecIdentityRef)CFDictionaryGetValue(identityDict, kSecImportItemIdentity);

securityError = SecIdentityCopyPrivateKey(identityApp, &privateKeyRef);

if (securityError != noErr) {

privateKeyRef = NULL;

}

}

CFRelease(items);

return privateKeyRef;

}

#pragma mark - Encrypt

-(NSString*) rsaEncryptString:(NSString*)string {

NSData* data = [string dataUsingEncoding:NSUTF8StringEncoding];

NSData* encryptedData = [self rsaEncryptData: data];

NSString* base64EncryptedString = [encryptedData base64EncodedString];

return base64EncryptedString;

}

// 加密的大小受限于SecKeyEncrypt函数,SecKeyEncrypt要求明文和密钥的长度一致,如果要加密更长的内容,需要把内容按密钥长度分成多份,然后多次调用SecKeyEncrypt来实现

-(NSData*) rsaEncryptData:(NSData*)data {

SecKeyRef key = [self getPublicKey];

size_t cipherBufferSize = SecKeyGetBlockSize(key);

uint8_t *cipherBuffer = malloc(cipherBufferSize * sizeof(uint8_t));

size_t blockSize = cipherBufferSize - 11; // 分段加密

size_t blockCount = (size_t)ceil([data length] / (double)blockSize);

NSMutableData *encryptedData = [[NSMutableData alloc] init] ;

for (int i=0; i

int bufferSize = MIN(blockSize,[data length] - i * blockSize);

NSData *buffer = [data subdataWithRange:NSMakeRange(i * blockSize, bufferSize)];

OSStatus status = SecKeyEncrypt(key, kSecPaddingPKCS1, (const uint8_t *)[buffer bytes], [buffer length], cipherBuffer, &cipherBufferSize);

if (status == noErr){

NSData *encryptedBytes = [[NSData alloc] initWithBytes:(const void *)cipherBuffer length:cipherBufferSize];

[encryptedData appendData:encryptedBytes];

}else{

if (cipherBuffer) {

free(cipherBuffer);

}

return nil;

}

}

if (cipherBuffer){

free(cipherBuffer);

}

return encryptedData;

}

#pragma mark - Decrypt

-(NSString*) rsaDecryptString:(NSString*)string {

NSData *data = [NSData dataWithBase64EncodedString:string];

// NSData* data = [NSData dataFromBase64String: string];

NSData* decryptData = [self rsaDecryptData: data];

NSString* result = [[NSString alloc] initWithData: decryptData encoding:NSUTF8StringEncoding];

return result;

}

-(NSData*) rsaDecryptData:(NSData*)data {

SecKeyRef key = [self getPrivateKey];

size_t cipherLen = [data length];

void *cipher = malloc(cipherLen);

[data getBytes:cipher length:cipherLen];

size_t plainLen = SecKeyGetBlockSize(key) - 12;

void *plain = malloc(plainLen);

OSStatus status = SecKeyDecrypt(key, kSecPaddingPKCS1, cipher, cipherLen, plain, &plainLen);

if (status != noErr) {

return nil;

}

NSData *decryptedData = [[NSData alloc] initWithBytes:(const void *)plain length:plainLen];

return decryptedData;

}

#pragma mark - Class Methods

static RSAEncryptor* sharedInstance = nil;

+(void) setSharedInstance: (RSAEncryptor*)instance

{

sharedInstance = instance;

}

+(RSAEncryptor*) sharedInstance

{

return sharedInstance;

}

@end

即可使用RSA加密解密

//配置秘钥

RSAEncryptor* rsaEncryptor = [[RSAEncryptor alloc] init];

NSString* publicKeyPath = [[NSBundle mainBundle] pathForResource:@"public_key" ofType:@"der"];

NSString* privateKeyPath = [[NSBundle mainBundle] pathForResource:@"private_key" ofType:@"p12"];

[rsaEncryptor loadPublicKeyFromFile: publicKeyPath];

[rsaEncryptor loadPrivateKeyFromFile: privateKeyPath password:@"生成p12时的密码"]; // 换成你生成p12时的密码

//字符串RSA加密

NSString *string = @"RSA加密字符串";

NSString* restrinBASE64STRING = [rsaEncryptor rsaEncryptString:string];

NSLog(@"加密后:==== %@", restrinBASE64STRING);

//字符串RSA解密

NSString* decryptString = [rsaEncryptor rsaDecryptString: restrinBASE64STRING];

NSLog(@"解密后:==== %@", decryptString);

运行结果

c246f7e6fd92

6307CA8C-8B57-46FA-AC35-29F66C24CC77.png

参考:

http://www.cnblogs.com/yangxiaolong/p/5526765.html

http://blog.csdn.net/yi_zz32/article/details/50097325

如果没有解决问题,推荐看下一篇文章

RSA 加密、解密(服务器给公钥,剩下的自己搞)

http://www.jianshu.com/p/f4497d19f336

RSA是一种非对称加密算法,它可以用于对文件进行加密解密。在Java中,可以使用Java加密库来实现RSA加密解密。下面是一个简单的示例代码: ```java import java.io.*; import java.security.*; import javax.crypto.*; public class RSAEncryption { private static final String PUBLIC_KEY_FILE = "public.key"; private static final String PRIVATE_KEY_FILE = "private.key"; public static void main(String[] args) throws Exception { // 生成密钥对 KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); SecureRandom random = new SecureRandom(); keyGen.initialize(1024, random); KeyPair keyPair = keyGen.generateKeyPair(); // 保存公钥和私钥到文件 saveKeyToFile(keyPair.getPublic(), PUBLIC_KEY_FILE); saveKeyToFile(keyPair.getPrivate(), PRIVATE_KEY_FILE); // 加密文件 encryptFile("plaintext.txt", "ciphertext.txt", keyPair.getPublic()); // 解密文件 decryptFile("ciphertext.txt", "decrypted.txt", keyPair.getPrivate()); } private static void saveKeyToFile(Key key, String fileName) throws IOException { byte[] keyBytes = key.getEncoded(); FileOutputStream fos = new FileOutputStream(fileName); fos.write(keyBytes); fos.close(); } private static void encryptFile(String inputFile, String outputFile, PublicKey publicKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); FileInputStream fis = new FileInputStream(inputFile); FileOutputStream fos = new FileOutputStream(outputFile); byte[] buffer = new byte[100]; int bytesRead; while ((bytesRead = fis.read(buffer)) != -1) { byte[] output = cipher.update(buffer, 0, bytesRead); if (output != null) { fos.write(output); } } byte[] output = cipher.doFinal(); if (output != null) { fos.write(output); } fis.close(); fos.flush(); fos.close(); } private static void decryptFile(String inputFile, String outputFile, PrivateKey privateKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); FileInputStream fis = new FileInputStream(inputFile); FileOutputStream fos = new FileOutputStream(outputFile); byte[] buffer = new byte[128]; int bytesRead; while ((bytesRead = fis.read(buffer)) != -1) { byte[] output = cipher.update(buffer, 0, bytesRead); if (output != null) { fos.write(output); } } byte[] output = cipher.doFinal(); if (output != null) { fos.write(output); } fis.close(); fos.flush(); fos.close(); } } ``` 上面的代码中,首先生成密钥对,然后保存公钥和私钥到文件中。接着,使用公钥对明文文件进行加密,将密文保存到文件中。最后,使用私钥对密文文件进行解密,将明文保存到文件中。 需要注意的是,RSA算法只能加密比密钥长度小的数据,因此在加密文件时,需要将文件分块加密,并将每个加密块保存到文件中。在解密时,将每个加密块读取出来,进行解密,然后将解密结果拼接起来即可。 另外,由于RSA算法的加密解密速度比较慢,因此在加密文件时,可能需要使用其他加密算法,如AES算法,来加密文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值