ios java rsa
时间: 2023-10-03 16:07:25 浏览: 268
iOS和Java都支持RSA加密,但是具体实现可能会有所不同。下面是一个简单的示例:
在iOS中使用RSA加密:
// 加载公钥文件
NSString *publicKeyPath = [[NSBundle mainBundle] pathForResource:@"public_key" ofType:@"der"];
NSData *publicKeyData = [[NSData alloc] initWithContentsOfFile:publicKeyPath];
SecCertificateRef certificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)publicKeyData);
// 获取公钥
SecKeyRef publicKey = NULL;
SecTrustRef trust;
SecPolicyRef policy;
policy = SecPolicyCreateBasicX509();
OSStatus status = SecTrustCreateWithCertificates(certificate, policy, &trust);
if (status == errSecSuccess) {
SecTrustResultType resultType;
status = SecTrustEvaluate(trust, &resultType);
publicKey = SecTrustCopyPublicKey(trust);
}
// 使用公钥进行加密
NSString *plainText = @"Hello, world!";
NSData *plainData = [plainText dataUsingEncoding:NSUTF8StringEncoding];
size_t cipherBufferSize = SecKeyGetBlockSize(publicKey);
uint8_t *cipherBuffer = malloc(cipherBufferSize);
memset(cipherBuffer, 0, cipherBufferSize);
OSStatus status = SecKeyEncrypt(publicKey, kSecPaddingPKCS1, [plainData bytes], [plainData length], cipherBuffer, &cipherBufferSize);
NSData *cipherData = [NSData dataWithBytes:cipherBuffer length:cipherBufferSize];
NSLog(@"Cipher text: %@", [cipherData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]);
在Java中使用RSA加密:
// 加载公钥文件
String publicKeyPath = "/path/to/public_key.der";
byte[] publicKeyBytes = Files.readAllBytes(Paths.get(publicKeyPath));
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(keySpec);
// 使用公钥进行加密
String plainText = "Hello, world!";
byte[] plainBytes = plainText.getBytes(StandardCharsets.UTF_8);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherBytes = cipher.doFinal(plainBytes);
System.out.println(Base64.getEncoder().encodeToString(cipherBytes));
需要注意的是,在iOS中使用SecKeyEncrypt函数进行加密时,需要指定填充方式为kSecPaddingPKCS1;在Java中使用Cipher类进行加密时,需要指定填充方式为PKCS1Padding。
阅读全文
相关推荐


















