java實現RSA加密與SHA簽名的例子

來源:互聯網
上載者:User

看到這篇文章的同學可幸福了,當時在做RSA加密與簽名的時候網上的資料簡直不要太老,做完後實在是忍受不下去了,這篇文章我會詳細講解iOS如何?RSA加密與簽名,並且與Java完全同步,這是我的第二篇部落格,若有什麼不足之處還請大家指教。

什麼是RSA?

答:RSA是一種非對稱式加密演算法,常用來對傳輸資料進行加密,配合上數字摘要演算法,也可以進行文字簽名。

RSA加密中padding?

答:padding即填充方式,由於RSA密碼編譯演算法中要加密的明文是要比模數小的,padding就是通過一些填充方式來限制明文的長度。後面會詳細介紹padding的幾種模式以及分段加密。

加密和加簽有什麼區別?

答:加密:公開金鑰放在用戶端,並使用公開金鑰對資料進行加密,服務端拿到資料後用私密金鑰進行解密;

加簽:私密金鑰放在用戶端,並使用私密金鑰對資料進行加簽,服務端拿到資料後用公開金鑰進行驗簽。

前者完全為了加密;後者主要是為了防惡意攻擊,防止別人類比我們的用戶端對我們的伺服器進行攻擊,導致伺服器癱瘓。

基本原理

RSA使用“金鑰組”對資料進行加密解密,在加密解密前需要先生存公開金鑰(Public Key)和私密金鑰(Private Key)。

公開金鑰(Public key): 用於加密資料. 用於公開, 一般存放在資料提供方, 例如iOS用戶端。

私密金鑰(Private key): 用於解密資料. 必須保密, 私密金鑰泄露會造成安全問題。

iOS中的Security.framework提供了對RSA演算法的支援,這種方式需要對密匙對進行處理, 根據public key產生認證, 通過private key產生p12格式的密匙。想想jave直接用字串進行加密解密簡單多了。(⊙o⊙)…

 

實戰

認證產生

RSA加密這塊公開金鑰、私密金鑰必不可少的。Apple是不支援直接使用字串進行加密解密的,推薦使用p12檔案。這邊教大家去產生在加密中使用到的所有檔案,並提供給Java使用,想當年這個公開金鑰私密金鑰搞了半天了。 %>_<%

 

產生模長為1024bit的私密金鑰

openssl genrsa -out private_key.pem 1024

產生certification require file

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

產生certification 並指定到期時間

openssl x509 -req -days3650-in rsaCertReq.csr -signkey private_key.pem -out rsaCert.crt

產生公開金鑰供iOS使用

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

產生私密金鑰供iOS使用 這邊會讓你輸入密碼,後期用到在產生secKeyRef的時候會用到這個密碼

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

產生pem結尾的公開金鑰供Java使用

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

產生pem結尾的私密金鑰供Java使用openssl pkcs8 -topk8 -in private_key.pem -out pkcs8_private_key.pem -nocrypt

以上所有的步驟都是在終端下完成的哦 (^__^)

產生公開金鑰和私密金鑰的secKeyRef


//根據你的p12檔案產生私密金鑰對應的SecKeyRef 這邊返回若是nil 請檢查你p12檔案的產生步驟
- (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;
}
-
 //根據你的der檔案公開金鑰對應的SecKeyRef
 - (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;
}
加密與解密
- (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<blockCount; i++) {
    unsigned long 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) {
        return nil;
    }
    NSData *encryptedBytes = [[NSData alloc] initWithBytes:(const void *)cipherBuffer length:cipherBufferSize];
    [encryptedData appendData:encryptedBytes];
    }
  if (cipherBuffer){
    free(cipherBuffer);
  }
  return encryptedData;
  }
-
- (NSData*)rsaDecryptData:(NSData*)data {
SecKeyRef key = [self getPrivatKey];
size_t cipherBufferSize = SecKeyGetBlockSize(key);
size_t blockSize = cipherBufferSize;
size_t blockCount = (size_t)ceil([data length] / (double)blockSize);
NSMutableData *decryptedData = [[NSMutableData alloc] init];
for (int i = 0; i < blockCount; i++) {
    unsigned long bufferSize = MIN(blockSize , [data length] - i * blockSize);
    NSData *buffer = [data subdataWithRange:NSMakeRange(i * blockSize, bufferSize)];
    size_t cipherLen = [buffer length];
    void *cipher = malloc(cipherLen);
    [buffer getBytes:cipher length:cipherLen];
    size_t plainLen = SecKeyGetBlockSize(key);
    void *plain = malloc(plainLen);
    OSStatus status = SecKeyDecrypt(key, kSecPaddingPKCS1, cipher, cipherLen, plain, &plainLen);
    if (status != noErr) {
        return nil;
    }
    NSData *decryptedBytes = [[NSData alloc] initWithBytes:(const void *)plain length:plainLen];
    [decryptedData appendData:decryptedBytes];
}
return decryptedData;
}
RSA加密中的Padding

RSA_PKCS1_PADDING 填充模式,最常用的模式

要求: 輸入:必須 比 RSA 鑰模長(modulus) 短至少11個位元組, 也就是 RSA_size(rsa) – 11 如果輸入的明文過長,必須切割,然後填充。

輸出:和modulus一樣長

根據這個要求,對於1024bit的密鑰,block length = 1024/8 – 11 = 117 位元組

 

RSA_PKCS1_OAEP_PADDING

輸入:RSA_size(rsa) – 41

輸出:和modulus一樣長

 

RSA_NO_PADDING  不填充

輸入:可以和RSA鑰模長一樣長,如果輸入的明文過長,必須切割, 然後填充

輸出:和modulus一樣長

 

簽名與驗證

//對資料進行sha256簽名

  - (NSData *)rsaSHA256SignData:(NSData *)plainData {

  SecKeyRef key = [self getPrivatKey];

 

  size_t signedHashBytesSize = SecKeyGetBlockSize(key);

  uint8_t* signedHashBytes = malloc(signedHashBytesSize);

  memset(signedHashBytes, 0x0, signedHashBytesSize);

 

  size_t hashBytesSize = CC_SHA256_DIGEST_LENGTH;

  uint8_t* hashBytes = malloc(hashBytesSize);

  if (!CC_SHA256([plainData bytes], (CC_LONG)[plainData length], hashBytes)) {

    return nil;

}

 

       SecKeyRawSign(key,

              kSecPaddingPKCS1SHA256,

              hashBytes,

              hashBytesSize,

              signedHashBytes,

              &signedHashBytesSize);

 

    NSData* signedHash = [NSData dataWithBytes:signedHashBytes

                                    length:(NSUInteger)signedHashBytesSize];

 

    if (hashBytes)

    free(hashBytes);

    if (signedHashBytes)

    free(signedHashBytes);

 

    return signedHash;

    }

-

 

      //這邊對簽名的資料進行驗證 驗簽成功,則返回YES

    - (BOOL)rsaSHA256VerifyData:(NSData *)plainData     withSignature:(NSData *)signature {

    SecKeyRef key = [self getPublicKey];

 

    size_t signedHashBytesSize = SecKeyGetBlockSize(key);

    const void* signedHashBytes = [signature bytes];

 

    size_t hashBytesSize = CC_SHA256_DIGEST_LENGTH;

    uint8_t* hashBytes = malloc(hashBytesSize);

    if (!CC_SHA256([plainData bytes], (CC_LONG)[plainData length], hashBytes)) {

       return NO;

    }

 

      OSStatus status = SecKeyRawVerify(key,

                                  kSecPaddingPKCS1SHA256,

                                  hashBytes,

                                  hashBytesSize,

                                  signedHashBytes,

                                  signedHashBytesSize);

 

    return status == errSecSuccess;

    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.