ios 安卓 javaweb RSA加密解密

ios版 ,公钥私钥一键加密解密

[objc]  view plain copy
  1. @interface RSA : NSObject  
  2.   
  3. // return base64 encoded string  
  4. + (NSString *)encryptString:(NSString *)str publicKey:(NSString *)pubKey;  
  5. // return raw data  
  6. + (NSData *)encryptData:(NSData *)data publicKey:(NSString *)pubKey;  
  7. // return base64 encoded string  
  8. // enc with private key NOT working YET!  
  9. //+ (NSString *)encryptString:(NSString *)str privateKey:(NSString *)privKey;  
  10. // return raw data  
  11. //+ (NSData *)encryptData:(NSData *)data privateKey:(NSString *)privKey;  
  12.   
  13. // decrypt base64 encoded string, convert result to string(not base64 encoded)  
  14. + (NSString *)decryptString:(NSString *)str publicKey:(NSString *)pubKey;  
  15. + (NSData *)decryptData:(NSData *)data publicKey:(NSString *)pubKey;  
  16. + (NSString *)decryptString:(NSString *)str privateKey:(NSString *)privKey;  
  17. + (NSData *)decryptData:(NSData *)data privateKey:(NSString *)privKey;  
  18.   
  19. @end  

[objc]  view plain copy
  1. /* 
  2.  @author: ideawu 
  3.  @link: https://github.com/ideawu/Objective-C-RSA 
  4. */  
  5.   
  6. #import "RSA.h"  
  7. #import <Security/Security.h>  
  8.   
  9. @implementation RSA  
  10.   
  11. /* 
  12. static NSString *base64_encode(NSString *str){ 
  13.     NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding]; 
  14.     if(!data){ 
  15.         return nil; 
  16.     } 
  17.     return base64_encode_data(data); 
  18. } 
  19. */  
  20.   
  21. static NSString *base64_encode_data(NSData *data){  
  22.     data = [data base64EncodedDataWithOptions:0];  
  23.     NSString *ret = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];  
  24.     return ret;  
  25. }  
  26.   
  27. static NSData *base64_decode(NSString *str){  
  28.     NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];  
  29.     return data;  
  30. }  
  31.   
  32. + (NSData *)stripPublicKeyHeader:(NSData *)d_key{  
  33.     // Skip ASN.1 public key header  
  34.     if (d_key == nilreturn(nil);  
  35.       
  36.     unsigned long len = [d_key length];  
  37.     if (!len) return(nil);  
  38.       
  39.     unsigned charchar *c_key = (unsigned charchar *)[d_key bytes];  
  40.     unsigned int  idx    = 0;  
  41.       
  42.     if (c_key[idx++] != 0x30return(nil);  
  43.       
  44.     if (c_key[idx] > 0x80) idx += c_key[idx] - 0x80 + 1;  
  45.     else idx++;  
  46.       
  47.     // PKCS #1 rsaEncryption szOID_RSA_RSA  
  48.     static unsigned char seqiod[] =  
  49.     { 0x30,   0x0d, 0x060x090x2a, 0x860x480x860xf70x0d, 0x010x01,  
  50.         0x010x050x00 };  
  51.     if (memcmp(&c_key[idx], seqiod, 15)) return(nil);  
  52.       
  53.     idx += 15;  
  54.       
  55.     if (c_key[idx++] != 0x03return(nil);  
  56.       
  57.     if (c_key[idx] > 0x80) idx += c_key[idx] - 0x80 + 1;  
  58.     else idx++;  
  59.       
  60.     if (c_key[idx++] != '\0'return(nil);  
  61.       
  62.     // Now make a new NSData from this buffer  
  63.     return([NSData dataWithBytes:&c_key[idx] length:len - idx]);  
  64. }  
  65.   
  66. //credit: http://hg.mozilla.org/services/fx-home/file/tip/Sources/NetworkAndStorage/CryptoUtils.m#l1036  
  67. + (NSData *)stripPrivateKeyHeader:(NSData *)d_key{  
  68.     // Skip ASN.1 private key header  
  69.     if (d_key == nilreturn(nil);  
  70.   
  71.     unsigned long len = [d_key length];  
  72.     if (!len) return(nil);  
  73.   
  74.     unsigned charchar *c_key = (unsigned charchar *)[d_key bytes];  
  75.     unsigned int  idx    = 22//magic byte at offset 22  
  76.   
  77.     if (0x04 != c_key[idx++]) return nil;  
  78.   
  79.     //calculate length of the key  
  80.     unsigned int c_len = c_key[idx++];  
  81.     int det = c_len & 0x80;  
  82.     if (!det) {  
  83.         c_len = c_len & 0x7f;  
  84.     } else {  
  85.         int byteCount = c_len & 0x7f;  
  86.         if (byteCount + idx > len) {  
  87.             //rsa length field longer than buffer  
  88.             return nil;  
  89.         }  
  90.         unsigned int accum = 0;  
  91.         unsigned charchar *ptr = &c_key[idx];  
  92.         idx += byteCount;  
  93.         while (byteCount) {  
  94.             accum = (accum << 8) + *ptr;  
  95.             ptr++;  
  96.             byteCount--;  
  97.         }  
  98.         c_len = accum;  
  99.     }  
  100.   
  101.     // Now make a new NSData from this buffer  
  102.     return [d_key subdataWithRange:NSMakeRange(idx, c_len)];  
  103. }  
  104.   
  105. + (SecKeyRef)addPublicKey:(NSString *)key{  
  106.     NSRange spos = [key rangeOfString:@"-----BEGIN PUBLIC KEY-----"];  
  107.     NSRange epos = [key rangeOfString:@"-----END PUBLIC KEY-----"];  
  108.     if(spos.location != NSNotFound && epos.location != NSNotFound){  
  109.         NSUInteger s = spos.location + spos.length;  
  110.         NSUInteger e = epos.location;  
  111.         NSRange range = NSMakeRange(s, e-s);  
  112.         key = [key substringWithRange:range];  
  113.     }  
  114.     key = [key stringByReplacingOccurrencesOfString:@"\r" withString:@""];  
  115.     key = [key stringByReplacingOccurrencesOfString:@"\n" withString:@""];  
  116.     key = [key stringByReplacingOccurrencesOfString:@"\t" withString:@""];  
  117.     key = [key stringByReplacingOccurrencesOfString:@" "  withString:@""];  
  118.       
  119.     // This will be base64 encoded, decode it.  
  120.     NSData *data = base64_decode(key);  
  121.     data = [RSA stripPublicKeyHeader:data];  
  122.     if(!data){  
  123.         return nil;  
  124.     }  
  125.   
  126.     //a tag to read/write keychain storage  
  127.     NSString *tag = @"RSAUtil_PubKey";  
  128.     NSData *d_tag = [NSData dataWithBytes:[tag UTF8String] length:[tag length]];  
  129.       
  130.     // Delete any old lingering key with the same tag  
  131.     NSMutableDictionary *publicKey = [[NSMutableDictionary alloc] init];  
  132.     [publicKey setObject:(__bridge id) kSecClassKey forKey:(__bridge id)kSecClass];  
  133.     [publicKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];  
  134.     [publicKey setObject:d_tag forKey:(__bridge id)kSecAttrApplicationTag];  
  135.     SecItemDelete((__bridge CFDictionaryRef)publicKey);  
  136.       
  137.     // Add persistent version of the key to system keychain  
  138.     [publicKey setObject:data forKey:(__bridge id)kSecValueData];  
  139.     [publicKey setObject:(__bridge id) kSecAttrKeyClassPublic forKey:(__bridge id)  
  140.      kSecAttrKeyClass];  
  141.     [publicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)  
  142.      kSecReturnPersistentRef];  
  143.       
  144.     CFTypeRef persistKey = nil;  
  145.     OSStatus status = SecItemAdd((__bridge CFDictionaryRef)publicKey, &persistKey);  
  146.     if (persistKey != nil){  
  147.         CFRelease(persistKey);  
  148.     }  
  149.     if ((status != noErr) && (status != errSecDuplicateItem)) {  
  150.         return nil;  
  151.     }  
  152.   
  153.     [publicKey removeObjectForKey:(__bridge id)kSecValueData];  
  154.     [publicKey removeObjectForKey:(__bridge id)kSecReturnPersistentRef];  
  155.     [publicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnRef];  
  156.     [publicKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];  
  157.       
  158.     // Now fetch the SecKeyRef version of the key  
  159.     SecKeyRef keyRef = nil;  
  160.     status = SecItemCopyMatching((__bridge CFDictionaryRef)publicKey, (CFTypeRef *)&keyRef);  
  161.     if(status != noErr){  
  162.         return nil;  
  163.     }  
  164.     return keyRef;  
  165. }  
  166.   
  167. + (SecKeyRef)addPrivateKey:(NSString *)key{  
  168.     NSRange spos = [key rangeOfString:@"-----BEGIN RSA PRIVATE KEY-----"];  
  169.     NSRange epos = [key rangeOfString:@"-----END RSA PRIVATE KEY-----"];  
  170.     if(spos.location != NSNotFound && epos.location != NSNotFound){  
  171.         NSUInteger s = spos.location + spos.length;  
  172.         NSUInteger e = epos.location;  
  173.         NSRange range = NSMakeRange(s, e-s);  
  174.         key = [key substringWithRange:range];  
  175.     }  
  176.     key = [key stringByReplacingOccurrencesOfString:@"\r" withString:@""];  
  177.     key = [key stringByReplacingOccurrencesOfString:@"\n" withString:@""];  
  178.     key = [key stringByReplacingOccurrencesOfString:@"\t" withString:@""];  
  179.     key = [key stringByReplacingOccurrencesOfString:@" "  withString:@""];  
  180.   
  181.     // This will be base64 encoded, decode it.  
  182.     NSData *data = base64_decode(key);  
  183.     data = [RSA stripPrivateKeyHeader:data];  
  184.     if(!data){  
  185.         return nil;  
  186.     }  
  187.   
  188.     //a tag to read/write keychain storage  
  189.     NSString *tag = @"RSAUtil_PrivKey";  
  190.     NSData *d_tag = [NSData dataWithBytes:[tag UTF8String] length:[tag length]];  
  191.   
  192.     // Delete any old lingering key with the same tag  
  193.     NSMutableDictionary *privateKey = [[NSMutableDictionary alloc] init];  
  194.     [privateKey setObject:(__bridge id) kSecClassKey forKey:(__bridge id)kSecClass];  
  195.     [privateKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];  
  196.     [privateKey setObject:d_tag forKey:(__bridge id)kSecAttrApplicationTag];  
  197.     SecItemDelete((__bridge CFDictionaryRef)privateKey);  
  198.   
  199.     // Add persistent version of the key to system keychain  
  200.     [privateKey setObject:data forKey:(__bridge id)kSecValueData];  
  201.     [privateKey setObject:(__bridge id) kSecAttrKeyClassPrivate forKey:(__bridge id)  
  202.      kSecAttrKeyClass];  
  203.     [privateKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)  
  204.      kSecReturnPersistentRef];  
  205.   
  206.     CFTypeRef persistKey = nil;  
  207.     OSStatus status = SecItemAdd((__bridge CFDictionaryRef)privateKey, &persistKey);  
  208.     if (persistKey != nil){  
  209.         CFRelease(persistKey);  
  210.     }  
  211.     if ((status != noErr) && (status != errSecDuplicateItem)) {  
  212.         return nil;  
  213.     }  
  214.   
  215.     [privateKey removeObjectForKey:(__bridge id)kSecValueData];  
  216.     [privateKey removeObjectForKey:(__bridge id)kSecReturnPersistentRef];  
  217.     [privateKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnRef];  
  218.     [privateKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];  
  219.   
  220.     // Now fetch the SecKeyRef version of the key  
  221.     SecKeyRef keyRef = nil;  
  222.     status = SecItemCopyMatching((__bridge CFDictionaryRef)privateKey, (CFTypeRef *)&keyRef);  
  223.     if(status != noErr){  
  224.         return nil;  
  225.     }  
  226.     return keyRef;  
  227. }  
  228.   
  229. /* START: Encryption & Decryption with RSA private key */  
  230.   
  231. + (NSString *)encryptString:(NSString *)str privateKey:(NSString *)privKey{  
  232.     NSData *data = [RSA encryptData:[str dataUsingEncoding:NSUTF8StringEncoding] privateKey:privKey];  
  233.     NSString *ret = base64_encode_data(data);  
  234.     return ret;  
  235. }  
  236.   
  237. + (NSData *)encryptData:(NSData *)data privateKey:(NSString *)privKey{  
  238.     if(!data || !privKey){  
  239.         return nil;  
  240.     }  
  241.     SecKeyRef keyRef = [RSA addPrivateKey:privKey];  
  242.     if(!keyRef){  
  243.         return nil;  
  244.     }  
  245.   
  246.     const uint8_t *srcbuf = (const uint8_t *)[data bytes];  
  247.     size_t srclen = (size_t)data.length;  
  248.   
  249.     size_t outlen = SecKeyGetBlockSize(keyRef) * sizeof(uint8_t);  
  250.     if(srclen > outlen - 11){  
  251.         CFRelease(keyRef);  
  252.         return nil;  
  253.     }  
  254.     voidvoid *outbuf = malloc(outlen);  
  255.   
  256.     OSStatus status = noErr;  
  257.     status = SecKeyEncrypt(keyRef,  
  258.                            kSecPaddingPKCS1,  
  259.                            srcbuf,  
  260.                            srclen,  
  261.                            outbuf,  
  262.                            &outlen  
  263.                            );  
  264.     NSData *ret = nil;  
  265.     if (status != 0) {  
  266.         //NSLog(@"SecKeyEncrypt fail. Error Code: %ld", status);  
  267.     }else{  
  268.         ret = [NSData dataWithBytes:outbuf length:outlen];  
  269.     }  
  270.     free(outbuf);  
  271.     CFRelease(keyRef);  
  272.     return ret;  
  273. }  
  274.   
  275. + (NSString *)decryptString:(NSString *)str privateKey:(NSString *)privKey{  
  276.     NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];  
  277.     data = [RSA decryptData:data privateKey:privKey];  
  278.     NSString *ret = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];  
  279.     return ret;  
  280. }  
  281.   
  282. + (NSData *)decryptData:(NSData *)data privateKey:(NSString *)privKey{  
  283.     if(!data || !privKey){  
  284.         return nil;  
  285.     }  
  286.     SecKeyRef keyRef = [RSA addPrivateKey:privKey];  
  287.     if(!keyRef){  
  288.         return nil;  
  289.     }  
  290.   
  291.     const uint8_t *srcbuf = (const uint8_t *)[data bytes];  
  292.     size_t srclen = (size_t)data.length;  
  293.   
  294.     size_t outlen = SecKeyGetBlockSize(keyRef) * sizeof(uint8_t);  
  295.     if(srclen != outlen){  
  296.         //TODO currently we are able to decrypt only one block!  
  297.         CFRelease(keyRef);  
  298.         return nil;  
  299.     }  
  300.     UInt8 *outbuf = malloc(outlen);  
  301.   
  302.     //use kSecPaddingNone in decryption mode  
  303.     OSStatus status = noErr;  
  304.     status = SecKeyDecrypt(keyRef,  
  305.                            kSecPaddingNone,  
  306.                            srcbuf,  
  307.                            srclen,  
  308.                            outbuf,  
  309.                            &outlen  
  310.                            );  
  311.     NSData *result = nil;  
  312.     if (status != 0) {  
  313.         //NSLog(@"SecKeyEncrypt fail. Error Code: %ld", status);  
  314.     }else{  
  315.         //the actual decrypted data is in the middle, locate it!  
  316.         int idxFirstZero = -1;  
  317.         int idxNextZero = (int)outlen;  
  318.         for ( int i = 0; i < outlen; i++ ) {  
  319.             if ( outbuf[i] == 0 ) {  
  320.                 if ( idxFirstZero < 0 ) {  
  321.                     idxFirstZero = i;  
  322.                 } else {  
  323.                     idxNextZero = i;  
  324.                     break;  
  325.                 }  
  326.             }  
  327.         }  
  328.   
  329.         result = [NSData dataWithBytes:&outbuf[idxFirstZero+1] length:idxNextZero-idxFirstZero-1];  
  330.     }  
  331.     free(outbuf);  
  332.     CFRelease(keyRef);  
  333.     return result;  
  334. }  
  335.   
  336. /* END: Encryption & Decryption with RSA private key */  
  337.   
  338. /* START: Encryption & Decryption with RSA public key */  
  339.   
  340. + (NSString *)encryptString:(NSString *)str publicKey:(NSString *)pubKey{  
  341.     NSData *data = [RSA encryptData:[str dataUsingEncoding:NSUTF8StringEncoding] publicKey:pubKey];  
  342.     NSString *ret = base64_encode_data(data);  
  343.     return ret;  
  344. }  
  345.   
  346. + (NSData *)encryptData:(NSData *)data publicKey:(NSString *)pubKey{  
  347.     if(!data || !pubKey){  
  348.         return nil;  
  349.     }  
  350.     SecKeyRef keyRef = [RSA addPublicKey:pubKey];  
  351.     if(!keyRef){  
  352.         return nil;  
  353.     }  
  354.       
  355.     const uint8_t *srcbuf = (const uint8_t *)[data bytes];  
  356.     size_t srclen = (size_t)data.length;  
  357.       
  358.     size_t outlen = SecKeyGetBlockSize(keyRef) * sizeof(uint8_t);  
  359.     if(srclen > outlen - 11){  
  360.         CFRelease(keyRef);  
  361.         return nil;  
  362.     }  
  363.     voidvoid *outbuf = malloc(outlen);  
  364.       
  365.     OSStatus status = noErr;  
  366.     status = SecKeyEncrypt(keyRef,  
  367.                            kSecPaddingPKCS1,  
  368.                            srcbuf,  
  369.                            srclen,  
  370.                            outbuf,  
  371.                            &outlen  
  372.                            );  
  373.     NSData *ret = nil;  
  374.     if (status != 0) {  
  375.         //NSLog(@"SecKeyEncrypt fail. Error Code: %ld", status);  
  376.     }else{  
  377.         ret = [NSData dataWithBytes:outbuf length:outlen];  
  378.     }  
  379.     free(outbuf);  
  380.     CFRelease(keyRef);  
  381.     return ret;  
  382. }  
  383.   
  384. + (NSString *)decryptString:(NSString *)str publicKey:(NSString *)pubKey{  
  385.     NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];  
  386.     data = [RSA decryptData:data publicKey:pubKey];  
  387.     NSString *ret = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];  
  388.     return ret;  
  389. }  
  390.   
  391. + (NSData *)decryptData:(NSData *)data publicKey:(NSString *)pubKey{  
  392.     if(!data || !pubKey){  
  393.         return nil;  
  394.     }  
  395.     SecKeyRef keyRef = [RSA addPublicKey:pubKey];  
  396.     if(!keyRef){  
  397.         return nil;  
  398.     }  
  399.       
  400.     const uint8_t *srcbuf = (const uint8_t *)[data bytes];  
  401.     size_t srclen = (size_t)data.length;  
  402.       
  403.     size_t outlen = SecKeyGetBlockSize(keyRef) * sizeof(uint8_t);  
  404.     if(srclen != outlen){  
  405.         //TODO currently we are able to decrypt only one block!  
  406.         CFRelease(keyRef);  
  407.         return nil;  
  408.     }  
  409.     UInt8 *outbuf = malloc(outlen);  
  410.       
  411.     //use kSecPaddingNone in decryption mode  
  412.     OSStatus status = noErr;  
  413.     status = SecKeyDecrypt(keyRef,  
  414.                            kSecPaddingNone,  
  415.                            srcbuf,  
  416.                            srclen,  
  417.                            outbuf,  
  418.                            &outlen  
  419.                            );  
  420.     NSData *result = nil;  
  421.     if (status != 0) {  
  422.         //NSLog(@"SecKeyEncrypt fail. Error Code: %ld", status);  
  423.     }else{  
  424.         //the actual decrypted data is in the middle, locate it!  
  425.         int idxFirstZero = -1;  
  426.         int idxNextZero = (int)outlen;  
  427.         for ( int i = 0; i < outlen; i++ ) {  
  428.             if ( outbuf[i] == 0 ) {  
  429.                 if ( idxFirstZero < 0 ) {  
  430.                     idxFirstZero = i;  
  431.                 } else {  
  432.                     idxNextZero = i;  
  433.                     break;  
  434.                 }  
  435.             }  
  436.         }  
  437.           
  438.         result = [NSData dataWithBytes:&outbuf[idxFirstZero+1] length:idxNextZero-idxFirstZero-1];  
  439.     }  
  440.     free(outbuf);  
  441.     CFRelease(keyRef);  
  442.     return result;  
  443. }  
  444.   
  445. /* END: Encryption & Decryption with RSA public key */  
  446.   
  447. @end  

例如:

[objc]  view plain copy
  1. NSString *pubkey = @"-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDEChqe80lJLTTkJD3X3Lyd7Fj+\nzuOhDZkjuLNPog3YR20e5JcrdqI9IFzNbACY/GQVhbnbvBqYgyql8DfPCGXpn0+X\nNSxELIUw9Vh32QuhGNr3/TBpechrVeVpFPLwyaYNEk1CawgHCeQqf5uaqiaoBDOT\nqeox88Lc1ld7MsfggQIDAQAB\n-----END PUBLIC KEY-----";  
  2. NSString *privkey = @"-----BEGIN RSA PRIVATE KEY-----\nMIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMQKGp7zSUktNOQk\nPdfcvJ3sWP7O46ENmSO4s0+iDdhHbR7klyt2oj0gXM1sAJj8ZBWFudu8GpiDKqXw\nN88IZemfT5c1LEQshTD1WHfZC6EY2vf9MGl5yGtV5WkU8vDJpg0STUJrCAcJ5Cp/\nm5qqJqgEM5Op6jHzwtzWV3syx+CBAgMBAAECgYEApSzqPzE3d3uqi+tpXB71oY5J\ncfB55PIjLPDrzFX7mlacP6JVKN7dVemVp9OvMTe/UE8LSXRVaFlkLsqXC07FJjhu\nwFXHPdnUf5sanLLdnzt3Mc8vMgUamGJl+er0wdzxM1kPTh0Tmq+DSlu5TlopAHd5\nIqF3DYiORIen3xIwp0ECQQDj6GFaXWzWAu5oUq6j1msTRV3mRZnx8Amxt1ssYM0+\nJLf6QYmpkGFqiQOhHkMgVUwRFqJC8A9EVR1eqabcBXbpAkEA3DQfLVr94vsIWL6+\nVrFcPJW9Xk28CNY6Xnvkin815o2Q0JUHIIIod1eVKCiYDUzZAYAsW0gefJ49sJ4Y\niRJN2QJAKuxeQX2s/NWKfz1rRNIiUnvTBoZ/SvCxcrYcxsvoe9bAi7KCMdxObJkn\nhNXFQLav39wKbV73ESCSqnx7P58L2QJABmhR2+0A5EDvvj1WpokkqPKmfv7+ELfD\nHQq33LvU4q+N3jPn8C85ZDedNHzx57kru1pyb/mKQZANNX10M1DgCQJBAMKn0lEx\nQH2GrkjeWgGVpPZkp0YC+ztNjaUMJmY5g0INUlDgqTWFNftxe8ROvt7JtUvlgtKC\nXdXQrKaEnpebeUQ=\n-----END RSA PRIVATE KEY-----";  
  3.   
  4. NSString *originString = @"hello world!";  
  5. NSString *encWithPubKey;  
  6. NSString *decWithPrivKey;  
  7. NSString *encWithPrivKey;  
  8. NSString *decWithPublicKey;  
  9.   
  10. NSLog(@"Original string: %@", originString);  
  11.   
  12. // Demo: encrypt with public key  
  13. encWithPubKey = [RSA encryptString:originString publicKey:pubkey];  
  14. NSLog(@"Enctypted with public key: %@", encWithPubKey);  
  15. // Demo: decrypt with private key  
  16. decWithPrivKey = [RSA decryptString:encWithPubKey privateKey:privkey];  
  17. NSLog(@"Decrypted with private key: %@", decWithPrivKey);  
  18.   
  19. // by PHP  
  20. encWithPubKey = @"p1i8zlbzjy9e8PI0hsmVZUNLNy0jr7KpbsDoKek1FvHpnPXkk1W+91mizj6aD+7n7UkE2G5OrrmqaQSQzMEXOv+zgyGQH0x1AlbCYg0YAFdoOiOOUuNS4Gb9ltFmjy9pGf5mqCcr33h14Ln3l5MZGylyoSmIDpooDCk2t/BJHnU=";  
  21. decWithPrivKey = [RSA decryptString:encWithPubKey privateKey:privkey];  
  22. NSLog(@"(PHP enc)Decrypted with private key: %@", decWithPrivKey);  
  23.   
  24. // Demo: encrypt with private key  
  25. // TODO: encryption with private key currently NOT WORKING YET!  
  26. //encWithPrivKey = [RSA encryptString:originString privateKey:privkey];  
  27. //NSLog(@"Enctypted with private key: %@", encWithPrivKey);  
  28.   
  29. // Demo: decrypt with public key  
  30. encWithPrivKey = @"F+feHOH6807tUV/drvepAMzKlVKRsoDFRkFNfhS9kgVoBt2E6OnUIVw12l608yQGWiqtq8rgZgMY/VCQYZB+3r2rhDlyZ2fjo00sUFOp5BkNPFTs/NpQAolD6V3ifNgDmBQP92uVbxbod1pLRwLC0wLOhr5flQXvvobeg5KrDeE=";  
  31. decWithPublicKey = [RSA decryptString:encWithPrivKey publicKey:pubkey];  
  32. NSLog(@"(PHP enc)Decrypted with public key: %@", decWithPublicKey);  



安卓版 ,公钥一键加密解密 。需要下载org.bouncycastle.jce.provider.BouncyCastleProvider.jar包用于初始化

[java]  view plain copy
  1. import java.io.BufferedReader;  
  2. import java.io.IOException;  
  3. import java.io.InputStream;  
  4. import java.io.InputStreamReader;  
  5. import java.math.BigInteger;  
  6. import java.security.Key;  
  7. import java.security.KeyFactory;  
  8. import java.security.KeyPair;  
  9. import java.security.KeyPairGenerator;  
  10. import java.security.NoSuchAlgorithmException;  
  11. import java.security.PrivateKey;  
  12. import java.security.PublicKey;  
  13. import java.security.interfaces.RSAPrivateKey;  
  14. import java.security.interfaces.RSAPublicKey;  
  15. import java.security.spec.InvalidKeySpecException;  
  16. import java.security.spec.PKCS8EncodedKeySpec;  
  17. import java.security.spec.RSAPublicKeySpec;  
  18. import java.security.spec.X509EncodedKeySpec;  
  19.   
  20. import javax.crypto.Cipher;  
  21.   
  22.   
  23.   
  24. /** 
  25.  * @author  Young    
  26.  * @date  
  27.  *  一键加密解密     安卓版    
  28.  */  
  29. public final class RSAUtils  
  30. {  
  31.     private static String RSA = "RSA";  
  32.       
  33.     private static PublicKey publicKey;  
  34.   
  35.     /** 
  36.      * 随机生成RSA密钥对(默认密钥长度为1024) 
  37.      *  
  38.      * @return 
  39.      */  
  40.     private static KeyPair generateRSAKeyPair()  
  41.     {  
  42.         return generateRSAKeyPair(1024);  
  43.     }  
  44.   
  45.     /** 
  46.      * 随机生成RSA密钥对 
  47.      *  
  48.      * @param keyLength 
  49.      *            密钥长度,范围:512~2048<br> 
  50.      *            一般1024 
  51.      * @return 
  52.      */  
  53.     private static KeyPair generateRSAKeyPair(int keyLength)  
  54.     {  
  55.         try  
  56.         {  
  57.             KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA,new org.bouncycastle.jce.provider.BouncyCastleProvider());  
  58.             kpg.initialize(keyLength);  
  59.             return kpg.genKeyPair();  
  60.         } catch (Throwable e)  
  61.         {  
  62.             e.printStackTrace();  
  63.             return null;  
  64.         }  
  65.     }  
  66.    
  67.     /** 
  68.      * 用公钥加密 <br> 
  69.      * 每次加密的字节数,不能超过密钥的长度值减去11 
  70.      *  
  71.       
  72.      * @return 加密后的 数据 
  73.      */  
  74.     public static String encryptData(String data )  
  75.     {  
  76.         try  
  77.         {  
  78.             if (publicKey==null) {  
  79.                 publicKey=loadPublicKey(Constants.getPBK());  
  80.             }  
  81. //          Cipher cipher = Cipher.getInstance(RSA);  
  82.             Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");  
  83.             // 编码前设定编码方式及密钥  
  84.             cipher.init(Cipher.ENCRYPT_MODE, publicKey);  
  85.             // 传入编码数据并返回编码结果  
  86.             return Base64Utils.encode(cipher.doFinal(data.getBytes()));  
  87.               
  88.                
  89.         } catch (Exception e)  
  90.         {  
  91.             e.printStackTrace();  
  92.             return null;  
  93.         }  
  94.     }  
  95.   
  96.     /** 
  97.      * 用公钥解密 
  98.      *  
  99.        
  100.      * @return 
  101.      */  
  102.     public static String decryptData(String data)  
  103.     {  
  104.         try  
  105.         {     
  106.             if (publicKey==null) {  
  107.                 publicKey=loadPublicKey(Constants.getPBK());  
  108.             }  
  109.             byte[] encryptedData=Base64Utils.decode(data);  
  110. //          Cipher cipher = Cipher.getInstance(RSA);  
  111.             Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");  
  112.             cipher.init(Cipher.DECRYPT_MODE, publicKey);  
  113.             return new String(cipher.doFinal(encryptedData));  
  114.         } catch (Exception e)  
  115.         {  
  116.             return null;  
  117.         }  
  118.     }  
  119.    
  120.   
  121.     /** 
  122.      * 通过公钥byte[](publicKey.getEncoded())将公钥还原,适用于RSA算法 
  123.      *  
  124.      * @param keyBytes 
  125.      * @return 
  126.      * @throws NoSuchAlgorithmException 
  127.      * @throws InvalidKeySpecException 
  128.      */  
  129.     private static PublicKey getPublicKey(byte[] keyBytes) throws NoSuchAlgorithmException,  
  130.             InvalidKeySpecException  
  131.     {  
  132.         X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);  
  133.         KeyFactory keyFactory = KeyFactory.getInstance(RSA);  
  134.         PublicKey publicKey = keyFactory.generatePublic(keySpec);  
  135.         return publicKey;  
  136.     }  
  137.   
  138.     /** 
  139.      * 通过私钥byte[]将公钥还原,适用于RSA算法 
  140.      *  
  141.      * @param keyBytes 
  142.      * @return 
  143.      * @throws NoSuchAlgorithmException 
  144.      * @throws InvalidKeySpecException 
  145.      */  
  146.     private static PrivateKey getPrivateKey(byte[] keyBytes) throws NoSuchAlgorithmException,  
  147.             InvalidKeySpecException  
  148.     {  
  149.         PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);  
  150.         KeyFactory keyFactory = KeyFactory.getInstance(RSA);  
  151.         PrivateKey privateKey = keyFactory.generatePrivate(keySpec);  
  152.         return privateKey;  
  153.     }  
  154.   
  155.     /** 
  156.      * 使用N、e值还原公钥 
  157.      *  
  158.      * @param modulus 
  159.      * @param publicExponent 
  160.      * @return 
  161.      * @throws NoSuchAlgorithmException 
  162.      * @throws InvalidKeySpecException 
  163.      */  
  164.     private static PublicKey getPublicKey(String modulus, String publicExponent)  
  165.             throws NoSuchAlgorithmException, InvalidKeySpecException  
  166.     {  
  167.         BigInteger bigIntModulus = new BigInteger(modulus);  
  168.         BigInteger bigIntPrivateExponent = new BigInteger(publicExponent);  
  169.         RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);  
  170.         KeyFactory keyFactory = KeyFactory.getInstance(RSA);  
  171.         PublicKey publicKey = keyFactory.generatePublic(keySpec);  
  172.         return publicKey;  
  173.     }  
  174.   
  175.     /** 
  176.      * 使用N、d值还原私钥 
  177.      *  
  178.      * @param modulus 
  179.      * @param privateExponent 
  180.      * @return 
  181.      * @throws NoSuchAlgorithmException 
  182.      * @throws InvalidKeySpecException 
  183.      */  
  184.     private static PrivateKey getPrivateKey(String modulus, String privateExponent)  
  185.             throws NoSuchAlgorithmException, InvalidKeySpecException  
  186.     {  
  187.         BigInteger bigIntModulus = new BigInteger(modulus);  
  188.         BigInteger bigIntPrivateExponent = new BigInteger(privateExponent);  
  189.         RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);  
  190.         KeyFactory keyFactory = KeyFactory.getInstance(RSA);  
  191.         PrivateKey privateKey = keyFactory.generatePrivate(keySpec);  
  192.         return privateKey;  
  193.     }  
  194.   
  195.     /** 
  196.      * 从字符串中加载公钥 
  197.      *  
  198.      * @param publicKeyStr 
  199.      *            公钥数据字符串 
  200.      * @throws Exception 
  201.      *             加载公钥时产生的异常 
  202.      */  
  203.     private static PublicKey loadPublicKey(String publicKeyStr) throws Exception  
  204.     {  
  205.         try  
  206.         {  
  207.             byte[] buffer = Base64Utils.decode(publicKeyStr);  
  208.             KeyFactory keyFactory = KeyFactory.getInstance(RSA);  
  209.             X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);  
  210.             return (RSAPublicKey) keyFactory.generatePublic(keySpec);  
  211.         } catch (NoSuchAlgorithmException e)  
  212.         {  
  213.             throw new Exception("无此算法");  
  214.         } catch (InvalidKeySpecException e)  
  215.         {  
  216.             throw new Exception("公钥非法");  
  217.         } catch (NullPointerException e)  
  218.         {  
  219.             throw new Exception("公钥数据为空");  
  220.         }  
  221.     }  
  222.   
  223.     /** 
  224.      * 从字符串中加载私钥<br> 
  225.      * 加载时使用的是PKCS8EncodedKeySpec(PKCS#8编码的Key指令)。 
  226.      *  
  227.      * @param privateKeyStr 
  228.      * @return 
  229.      * @throws Exception 
  230.      */  
  231.     private static PrivateKey loadPrivateKey(String privateKeyStr) throws Exception  
  232.     {  
  233.         try  
  234.         {  
  235.             byte[] buffer = Base64Utils.decode(privateKeyStr);  
  236.             // X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);  
  237.             PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);  
  238.             KeyFactory keyFactory = KeyFactory.getInstance(RSA);  
  239.             return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);  
  240.         } catch (NoSuchAlgorithmException e)  
  241.         {  
  242.             throw new Exception("无此算法");  
  243.         } catch (InvalidKeySpecException e)  
  244.         {  
  245.             throw new Exception("私钥非法");  
  246.         } catch (NullPointerException e)  
  247.         {  
  248.             throw new Exception("私钥数据为空");  
  249.         }  
  250.     }  
  251.   
  252.     /** 
  253.      * 从文件中输入流中加载公钥 
  254.      *  
  255.      * @param in 
  256.      *            公钥输入流 
  257.      * @throws Exception 
  258.      *             加载公钥时产生的异常 
  259.      */  
  260.     private static PublicKey loadPublicKey(InputStream in) throws Exception  
  261.     {  
  262.         try  
  263.         {  
  264.             return loadPublicKey(readKey(in));  
  265.         } catch (IOException e)  
  266.         {  
  267.             throw new Exception("公钥数据流读取错误");  
  268.         } catch (NullPointerException e)  
  269.         {  
  270.             throw new Exception("公钥输入流为空");  
  271.         }  
  272.     }  
  273.   
  274.     /** 
  275.      * 从文件中加载私钥 
  276.      *  
  277.      * @param keyFileName 
  278.      *            私钥文件名 
  279.      * @return 是否成功 
  280.      * @throws Exception 
  281.      */  
  282.     private static PrivateKey loadPrivateKey(InputStream in) throws Exception  
  283.     {  
  284.         try  
  285.         {  
  286.             return loadPrivateKey(readKey(in));  
  287.         } catch (IOException e)  
  288.         {  
  289.             throw new Exception("私钥数据读取错误");  
  290.         } catch (NullPointerException e)  
  291.         {  
  292.             throw new Exception("私钥输入流为空");  
  293.         }  
  294.     }  
  295.   
  296.     /** 
  297.      * 读取密钥信息 
  298.      *  
  299.      * @param in 
  300.      * @return 
  301.      * @throws IOException 
  302.      */  
  303.     private static String readKey(InputStream in) throws IOException  
  304.     {  
  305.         BufferedReader br = new BufferedReader(new InputStreamReader(in));  
  306.         String readLine = null;  
  307.         StringBuilder sb = new StringBuilder();  
  308.         while ((readLine = br.readLine()) != null)  
  309.         {  
  310.             if (readLine.charAt(0) == '-')  
  311.             {  
  312.                 continue;  
  313.             } else  
  314.             {  
  315.                 sb.append(readLine);  
  316.                 sb.append('\r');  
  317.             }  
  318.         }  
  319.   
  320.         br.close();  
  321.         return sb.toString();  
  322.     }  
  323.   
  324.     /** 
  325.      * 打印公钥信息 
  326.      *  
  327.      * @param publicKey 
  328.      */  
  329.     private static void printPublicKeyInfo(PublicKey publicKey)  
  330.     {  
  331.         RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;  
  332.         System.out.println("----------RSAPublicKey----------");  
  333.         System.out.println("Modulus.length=" + rsaPublicKey.getModulus().bitLength());  
  334.         System.out.println("Modulus=" + rsaPublicKey.getModulus().toString());  
  335.         System.out.println("PublicExponent.length=" + rsaPublicKey.getPublicExponent().bitLength());  
  336.         System.out.println("PublicExponent=" + rsaPublicKey.getPublicExponent().toString());  
  337.     }  
  338.   
  339.     private static void printPrivateKeyInfo(PrivateKey privateKey)  
  340.     {  
  341.         RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;  
  342.         System.out.println("----------RSAPrivateKey ----------");  
  343.         System.out.println("Modulus.length=" + rsaPrivateKey.getModulus().bitLength());  
  344.         System.out.println("Modulus=" + rsaPrivateKey.getModulus().toString());  
  345.         System.out.println("PrivateExponent.length=" + rsaPrivateKey.getPrivateExponent().bitLength());  
  346.         System.out.println("PrivatecExponent=" + rsaPrivateKey.getPrivateExponent().toString());  
  347.   
  348.     }  
  349.   
  350. }  

Constants.getPBK()  

[java]  view plain copy
  1. public static  String getPBK(){  
  2.       /* 注意这里 开头结尾没有-----------  , 中间也没有\n换行符 */  
  3.    
  4.      return "MIGfMA0GCSqGSIb.........省去中了间部分..........eox88Lc1ld7MsfggQIDAQAB";  
  5.   
  6. }  




java web 版  

[java]  view plain copy
  1.    
  2.   
  3. /** 
  4.  * BASE64转换工具 
  5.  *  
  6.   
  7.  */  
  8. public class Base64Util {  
  9.     private static final char intToBase64[] = {'A''B''C''D''E''F''G''H''I''J''K''L',   
  10.                 'M''N''O''P''Q''R''S''T''U''V''W''X''Y''Z''a''b''c''d',   
  11.                 'e''f''g''h''i''j''k''l''m''n''o''p''q''r''s''t''u''v',   
  12.                 'w''x''y''z''0''1''2''3''4''5''6''7''8''9''+''/'};  
  13.     private static final byte base64ToInt[] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,   
  14.                 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,   
  15.                 -1, -1, -1, -1, -1, -1, -162, -1, -1, -16352535455565758596061,   
  16.                 -1, -1, -1, -1, -1, -1, -1012345678910111213141516,   
  17.                 171819202122232425, -1, -1, -1, -1, -1, -126272829303132,   
  18.                 33343536373839404142434445464748495051 };  
  19.       
  20.     /** 
  21.      * byte数组转换成BASE64字符串 
  22.      *  
  23.      * @param data byte数组 
  24.      * @return <b>String</b> BASE64字符串<b><br/>null</b> 转换失败 
  25.      */  
  26.     public static String byteArrayToBase64(byte[] data) {  
  27.         if(data==null || data.length==0){  
  28.             return null;  
  29.         }  
  30.         int len = data.length;  
  31.         int groups = len/3;  
  32.         int nogroups = len-3*groups;  
  33.         int resultLen = (len+2)/3*4;  
  34.         StringBuffer result = new StringBuffer(resultLen);  
  35.         int cursor = 0;  
  36.         for(int i=0;i<groups;i++){  
  37.             int byte0 = data[cursor++]&0xff;  
  38.             int byte1 = data[cursor++]&0xff;  
  39.             int byte2 = data[cursor++]&0xff;  
  40.             result.append(intToBase64[byte0>>2]);  
  41.             result.append(intToBase64[(byte0<<4)&0x3f|(byte1>>4)]);  
  42.             result.append(intToBase64[(byte1<<2)&0x3f|(byte2>>6)]);  
  43.             result.append(intToBase64[byte2&0x3f]);  
  44.         }  
  45.         if(nogroups!=0){  
  46.             int byte0 = data[cursor++]&0xff;  
  47.             result.append(intToBase64[byte0>>2]);  
  48.             if(nogroups==1){  
  49.                 result.append(intToBase64[(byte0<<4)&0x3f]);  
  50.                 result.append("==");  
  51.             }else{  
  52.                 int byte1 = data[cursor++]&0xff;  
  53.                 result.append(intToBase64[(byte0<<4)&0x3f|(byte1>>4)]);  
  54.                 result.append(intToBase64[(byte1<<2)&0x3f]);  
  55.                 result.append('=');  
  56.             }  
  57.         }  
  58.         return result.toString();  
  59.     }  
  60.       
  61.     /** 
  62.      * BASE64字符串转换成byte数组 
  63.      *  
  64.      * @param data BASE64字符串 
  65.      * @return <b>String</b> byte数组<b><br/>null</b> 转换失败 
  66.      */  
  67.     public static byte[] base64ToByteArray(String data) {  
  68.         if(StringUtil.isEmpty(data)){  
  69.             return null;  
  70.         }  
  71.         int len = data.length();  
  72.         int groups = len/4;  
  73.         if(groups*4!=len){  
  74.             return null;  
  75.         }  
  76.         int nogroups = 0;  
  77.         int fullGroups = groups;  
  78.         if(len!=0){  
  79.             if(data.charAt(len-1)=='='){  
  80.                 nogroups++;  
  81.                 fullGroups--;  
  82.             }  
  83.             if(data.charAt(len-2)=='='){  
  84.                 nogroups++;  
  85.             }  
  86.         }  
  87.         byte[] result = new byte[groups*3-nogroups];  
  88.         int inCursor = 0;  
  89.         int outCursor = 0;  
  90.         try {  
  91.             for(int i=0;i<fullGroups;i++){  
  92.                 int ch0 = base64toInt(data.charAt(inCursor++));  
  93.                 int ch1 = base64toInt(data.charAt(inCursor++));  
  94.                 int ch2 = base64toInt(data.charAt(inCursor++));  
  95.                 int ch3 = base64toInt(data.charAt(inCursor++));  
  96.                 result[outCursor++] = (byte) ((ch0<<2)|(ch1>>4));  
  97.                 result[outCursor++] = (byte) ((ch1<<4)|(ch2>>2));  
  98.                 result[outCursor++] = (byte) ((ch2<<6)|ch3);  
  99.             }  
  100.             if(nogroups!=0){  
  101.                 int ch0 = base64toInt(data.charAt(inCursor++));  
  102.                 int ch1 = base64toInt(data.charAt(inCursor++));  
  103.                 result[outCursor++] = (byte) ((ch0<<2)|(ch1>>4));  
  104.                 if(nogroups==1){  
  105.                     int ch2 = base64toInt(data.charAt(inCursor++));  
  106.                     result[outCursor++] = (byte) ((ch1<<4)|(ch2>>2));  
  107.                 }  
  108.             }  
  109.         } catch (Exception e) {  
  110.             return null;  
  111.         }  
  112.         return result;  
  113.     }  
  114.       
  115.     private static int base64toInt(char c) {  
  116.         int result = base64ToInt[c];  
  117.         if(result<0){  
  118.             throw new RuntimeException();  
  119.         }  
  120.         return result;  
  121.     }  
  122.       
  123. }  


[java]  view plain copy
  1.    
  2. import java.math.BigInteger;  
  3. import java.security.KeyFactory;  
  4. import java.security.KeyPair;  
  5. import java.security.KeyPairGenerator;  
  6. import java.security.SecureRandom;  
  7. import java.security.interfaces.RSAPrivateKey;  
  8. import java.security.interfaces.RSAPublicKey;  
  9. import java.security.spec.PKCS8EncodedKeySpec;  
  10. import java.security.spec.X509EncodedKeySpec;  
  11. import java.util.HashMap;  
  12. import java.util.Map;  
  13.   
  14. import javax.crypto.Cipher;  
  15.   
  16. import com.yagou.base.entity.Charset;  
  17.   
  18. /** 
  19.  * RSA加密解密工具 
  20.  *  
  21.   
  22.  */  
  23. public class RsaUtil {  
  24.     /** 
  25.      * 私钥加密 
  26.      *  
  27.      * @param key 私钥 
  28.      * @param data 明文 
  29.      * @return <b>String</b> 密文<b><br/>null</b> 加密失败 
  30.      */  
  31.     public static String encryptByPrivateKey(String key, byte[] data) {  
  32.         try {  
  33.             RSAPrivateKey privateKey = getPrivateKey(key);  
  34.             Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");  
  35.             cipher.init(Cipher.ENCRYPT_MODE, privateKey);  
  36.             byte[] rsa = cipher.doFinal(data);  
  37.             return Base64Util.byteArrayToBase64(rsa);  
  38.         } catch (Exception e) {  
  39.         }  
  40.         return null;  
  41.     }  
  42.       
  43.     /** 
  44.      * 私钥加密 
  45.      *  
  46.      * @param key 私钥 
  47.      * @param data 明文 
  48.      * @return <b>String</b> 密文<b><br/>null</b> 加密失败 
  49.      */  
  50.     public static String encryptByPrivateKey(String key, String data) {  
  51.         try {  
  52.             byte[] bdata = StringUtil.strToByte(data);  
  53.             RSAPrivateKey privateKey = getPrivateKey(key);  
  54.             Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");  
  55.             cipher.init(Cipher.ENCRYPT_MODE, privateKey);  
  56.             byte[] rsa = cipher.doFinal(bdata);  
  57.             return Base64Util.byteArrayToBase64(rsa);  
  58.         } catch (Exception e) {  
  59.         }  
  60.         return null;  
  61.     }  
  62.       
  63.     /** 
  64.      * 公钥加密 
  65.      *  
  66.      * @param key 公钥 
  67.      * @param data 明文 
  68.      * @return <b>String</b> 密文<b><br/>null</b> 加密失败 
  69.      */  
  70.     public static String encryptByPublicKey(String key, byte[] data) {  
  71.         try {  
  72.             RSAPublicKey publicKey = getPublicKey(key);  
  73.             Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");  
  74.             cipher.init(Cipher.ENCRYPT_MODE, publicKey);  
  75.             byte[] rsa = cipher.doFinal(data);  
  76.             return Base64Util.byteArrayToBase64(rsa);  
  77.         } catch (Exception e) {  
  78.         }  
  79.         return null;  
  80.     }  
  81.       
  82.     /** 
  83.      * 公钥加密 
  84.      *  
  85.      * @param key 公钥 
  86.      * @param data 明文 
  87.      * @return <b>String</b> 密文<b><br/>null</b> 加密失败 
  88.      */  
  89.     public static String encryptByPublicKey(String key, String data) {  
  90.         try {  
  91.             byte[] bdata = StringUtil.strToByte(data);  
  92.             RSAPublicKey publicKey = getPublicKey(key);  
  93.             Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");  
  94.             cipher.init(Cipher.ENCRYPT_MODE, publicKey);  
  95.             byte[] rsa = cipher.doFinal(bdata);  
  96.             return Base64Util.byteArrayToBase64(rsa);  
  97.         } catch (Exception e) {  
  98.         }  
  99.         return null;  
  100.     }  
  101.   
  102.     /** 
  103.      * 私钥解密 
  104.      *  
  105.      * @param key 私钥 
  106.      * @param data 密文 
  107.      * @return <b>String</b> 明文<b><br/>null</b> 解密失败 
  108.      */  
  109.     public static String decryptByPrivateKey(String key, byte[] data) {  
  110.         try {  
  111.             RSAPrivateKey privateKey = getPrivateKey(key);  
  112.             Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");  
  113.             cipher.init(Cipher.DECRYPT_MODE, privateKey);  
  114.             byte[] rsa = cipher.doFinal(data);  
  115.             return new String(rsa, Charset.UTF8.getCharset());  
  116.         } catch (Exception e) {  
  117.         }  
  118.         return null;  
  119.     }  
  120.       
  121.     /** 
  122.      * 私钥解密 
  123.      *  
  124.      * @param key 私钥 
  125.      * @param data 密文 
  126.      * @return <b>String</b> 明文<b><br/>null</b> 解密失败 
  127.      */  
  128.     public static String decryptByPrivateKey(String key, String data) {  
  129.         try {  
  130.             byte[] bdata = Base64Util.base64ToByteArray(data);  
  131.             RSAPrivateKey privateKey = getPrivateKey(key);  
  132.             Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");  
  133.             cipher.init(Cipher.DECRYPT_MODE, privateKey);  
  134.             byte[] rsa = cipher.doFinal(bdata);  
  135.             return new String(rsa, Charset.UTF8.getCharset());  
  136.         } catch (Exception e) {  
  137.         }  
  138.         return null;  
  139.     }  
  140.       
  141.     /** 
  142.      * 公钥解密 
  143.      *  
  144.      * @param key 公钥 
  145.      * @param data 密文 
  146.      * @return <b>String</b> 明文<b><br/>null</b> 解密失败 
  147.      */  
  148.     public static String decryptByPublicKey(String key, byte[] data) {  
  149.         try {  
  150.             RSAPublicKey publicKey = getPublicKey(key);  
  151.             Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");  
  152.             cipher.init(Cipher.DECRYPT_MODE, publicKey);  
  153.             byte[] rsa = cipher.doFinal(data);  
  154.             return new String(rsa, Charset.UTF8.getCharset());  
  155.         } catch (Exception e) {  
  156.         }  
  157.         return null;  
  158.     }  
  159.       
  160.     /** 
  161.      * 公钥解密 
  162.      *  
  163.      * @param key 公钥 
  164.      * @param data 密文 
  165.      * @return <b>String</b> 明文<b><br/>null</b> 解密失败 
  166.      */  
  167.     public static String decryptByPublicKey(String key, String data) {  
  168.         try {  
  169.             byte[] bdata = Base64Util.base64ToByteArray(data);  
  170.             RSAPublicKey publicKey = getPublicKey(key);  
  171.             Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");  
  172.             cipher.init(Cipher.DECRYPT_MODE, publicKey);  
  173.             byte[] rsa = cipher.doFinal(bdata);  
  174.             return new String(rsa, Charset.UTF8.getCharset());  
  175.         } catch (Exception e) {  
  176.         }  
  177.         return null;  
  178.     }  
  179.   
  180.     /** 
  181.      * JS密钥对 
  182.      *  
  183.      * @param size 密钥长度 
  184.      * @return 密钥对 
  185.      */  
  186.     public static Map<String, String> genJsKey(int size) {  
  187.         Map<String, String> keyMap = new HashMap<String, String>();  
  188.         try {  
  189.             KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");  
  190.             keygen.initialize(size, new SecureRandom());  
  191.             KeyPair keyPair = keygen.generateKeyPair();  
  192.             RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();  
  193.             RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  
  194.             BigInteger n = privateKey.getModulus();  
  195.             BigInteger e = publicKey.getPublicExponent();  
  196.             BigInteger d = privateKey.getPrivateExponent();  
  197.             String p = Base64Util.byteArrayToBase64(privateKey.getEncoded());  
  198.             keyMap.put("n", n.toString(16));  
  199.             keyMap.put("e", e.toString(16));  
  200.             keyMap.put("d", d.toString(16));  
  201.             keyMap.put("p", p);  
  202.         } catch (Exception e) {  
  203.         }  
  204.         return keyMap;  
  205.     }  
  206.   
  207.     /** 
  208.      * JS密文解密 
  209.      *  
  210.      * @param key 私钥 
  211.      * @param data 密文 
  212.      * @return <b>String</b> 明文<b><br/>null</b> 解密失败 
  213.      */  
  214.     public static String decryptJsData(String key, String data) {  
  215.         try {  
  216.             byte[] bdata = hexToByte(StringUtil.strToByte(data));  
  217.             RSAPrivateKey privateKey = getPrivateKey(key);  
  218.             Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");  
  219.             cipher.init(Cipher.DECRYPT_MODE, privateKey);  
  220.             byte[] rsa = cipher.doFinal(bdata);  
  221.             return new String(rsa, Charset.UTF8.getCharset());  
  222.         } catch (Exception e) {  
  223.         }  
  224.         return null;  
  225.     }  
  226.       
  227.     private static RSAPrivateKey getPrivateKey(String key) {  
  228.         try {  
  229.             byte[] keyBytes = Base64Util.base64ToByteArray(key);  
  230.             PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);  
  231.             KeyFactory factory = KeyFactory.getInstance("RSA");  
  232.             return (RSAPrivateKey) factory.generatePrivate(spec);  
  233.         } catch (Exception e) {  
  234.         }  
  235.         return null;  
  236.     }  
  237.       
  238.     private static RSAPublicKey getPublicKey(String key) {  
  239.         try {  
  240.             byte[] keyBytes = Base64Util.base64ToByteArray(key);  
  241.             X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);  
  242.             KeyFactory factory = KeyFactory.getInstance("RSA");  
  243.             return (RSAPublicKey) factory.generatePublic(spec);  
  244.         } catch (Exception e) {  
  245.         }  
  246.         return null;  
  247.     }  
  248.       
  249.     private static byte[] hexToByte(byte[] hex){  
  250.         if(hex.length%2!=0){  
  251.             return null;  
  252.         }  
  253.         byte[] b = new byte[hex.length/2];  
  254.         for(int i=0;i<hex.length;i+=2){  
  255.             String str = new String(hex, i, 2);  
  256.             b[i/2] = (byte) Integer.parseInt(str, 16);  
  257.         }  
  258.         return b;  
  259.     }  
  260.   
  261. }  


[java]  view plain copy
  1.    
  2.   
  3. import java.net.URLEncoder;  
  4. import java.util.UUID;  
  5.   
  6. import com.yagou.base.entity.Charset;  
  7.   
  8. /** 
  9.  * 字符串工具 
  10.  *  
  11.   
  12.  */  
  13. public class StringUtil {  
  14.     /** 
  15.      * 获得32位唯一ID 
  16.      *  
  17.      * @return 
  18.      */  
  19.     public static String getUUID() {  
  20.         return UUID.randomUUID().toString().replaceAll("-""");  
  21.     }  
  22.       
  23.     /** 
  24.      * 判断字符串是否为空 
  25.      *  
  26.      * @param value 
  27.      * @return 
  28.      */  
  29.     public static boolean isEmpty(String value) {  
  30.         if(value==null || value.trim().length()==0){  
  31.             return true;  
  32.         }  
  33.         return false;  
  34.     }  
  35.       
  36.     /** 
  37.      * 获得字符串长度<br /> 
  38.      * 中文长度为3,其他长度1 
  39.      *  
  40.      * @param value 
  41.      * @return 
  42.      */  
  43.     public static int strLen(String value) {  
  44.         if(isEmpty(value)){  
  45.             return 0;  
  46.         }  
  47.         int len = 0;  
  48.         String chinese = "[\u0391-\uFFE5]";  
  49.         for(int i=0;i<value.length();i++){  
  50.             String str = value.substring(i, i+1);  
  51.             if(str.matches(chinese)){  
  52.                 len += 3;  
  53.             }else{  
  54.                 len += 1;  
  55.             }  
  56.         }  
  57.         return len;  
  58.     }  
  59.       
  60.     /** 
  61.      * 字符串转Integer 
  62.      *  
  63.      * @param value 
  64.      * @return 
  65.      */  
  66.     public static Integer strToInt(String value) {  
  67.         try {  
  68.             return Integer.parseInt(value);  
  69.         } catch (Exception e) {  
  70.         }  
  71.         return null;  
  72.     }  
  73.       
  74.     /** 
  75.      * 字符串转Long 
  76.      *  
  77.      * @param value 
  78.      * @return 
  79.      */  
  80.     public static Long strToLong(String value) {  
  81.         try {  
  82.             return Long.parseLong(value);  
  83.         } catch (Exception e) {  
  84.         }  
  85.         return null;  
  86.     }  
  87.       
  88.     /** 
  89.      * 获得字符串编码格式<br /> 
  90.      * 编码格式可为utf-8|iso-8859-1 
  91.      *  
  92.      * @param value 
  93.      * @return 
  94.      */  
  95.     public static Charset getEncode(String value) {  
  96.         if(isEmpty(value)){  
  97.             return null;  
  98.         }  
  99.         if(value.matches("^[\u0000-\u0080]+$")){  
  100.             return Charset.UTF8;  
  101.         }  
  102.         Charset encode = Charset.ISO8859;  
  103.         try {  
  104.             if(value.equals(new String(value.getBytes(encode.getCharset()), encode.getCharset()))){  
  105.                 return encode;  
  106.             }  
  107.         } catch (Exception e) {  
  108.         }  
  109.         encode = Charset.UTF8;  
  110.         try {  
  111.             if(value.equals(new String(value.getBytes(encode.getCharset()), encode.getCharset()))){  
  112.                 return encode;  
  113.             }  
  114.         } catch (Exception e) {  
  115.         }  
  116.         return null;  
  117.     }  
  118.       
  119.     /** 
  120.      * 识别字符串编码并重新编码成utf-8格式<br /> 
  121.      * 原编码格式可为utf-8|iso-8859-1 
  122.      *  
  123.      * @param value 
  124.      * @return 
  125.      */  
  126.     public static String encodeToUtf8(String value) {  
  127.         try {  
  128.             Charset encode = getEncode(value);  
  129.             if(encode!=null && !Charset.UTF8.getCharset().equals(encode.getCharset())){  
  130.                 value = new String(value.getBytes(encode.getCharset()), Charset.UTF8.getCharset());  
  131.                 return value;  
  132.             }  
  133.         } catch (Exception e) {  
  134.         }  
  135.         return value;  
  136.     }  
  137.       
  138.     /** 
  139.      * URL编码 
  140.      *  
  141.      * @param url 
  142.      * @return 
  143.      */  
  144.     public static String urlEncode(String url) {  
  145.         try {  
  146.             return URLEncoder.encode(url, Charset.UTF8.getCharset());  
  147.         } catch (Exception e) {  
  148.             return null;  
  149.         }  
  150.     }  
  151.       
  152.     /** 
  153.      * byte数组转字符串 
  154.      *  
  155.      * @param value 
  156.      * @return 
  157.      */  
  158.     public static String byteToStr(byte[] value) {  
  159.         try {  
  160.             return new String(value, Charset.UTF8.getCharset());  
  161.         } catch (Exception e) {  
  162.             return null;  
  163.         }  
  164.     }  
  165.       
  166.     /** 
  167.      * 字符串转byte数组 
  168.      *  
  169.      * @param value 
  170.      * @return 
  171.      */  
  172.     public static byte[] strToByte(String value) {  
  173.         try {  
  174.             return value.getBytes(Charset.UTF8.getCharset());  
  175.         } catch (Exception e) {  
  176.             return null;  
  177.         }  
  178.     }  
  179.       
  180. }  


[java]  view plain copy
  1. /** 
  2.   
  3.  */  
  4. public class RsaKey {  
  5.        
  6.       
  7.     /* 注意这里 开头结尾没有-----------  , 中间也没有\n换行符 */  
  8.      public static final String privateKey = "MIICdgIBADANBgkqhkiGKGsQiUpcZOn/U5。。。。。。。。ffQJAX10xxSrVsEYNZH3iDVCy3g==";  
  9.        
  10.      public static final String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA。。。。。。。。。。。mFZDj0LdC91+YMPKPnMiECf7I+FYI5rTWdlDAELPawIDAQAB";  
  11. }  

 
 

使用:

[java]  view plain copy
  1.                 //RSA加密后的字符串  
  2. String pwd="QAF3LNljSQDWYaOOsliW1u+J++Du5xyTnyuNgAl8FGAfm3mPjLEFrfA1cPsa2gwyirHzCpGTv0WnRIobXWnI3UsXwAvRBtOcWRscJjMDlF7ad5+tly0zUwPJvrvd5Vm1ViilqaOEiPHTTZqzLdZvSK/zofgr6D4jqx8+TF6GdNc=";  
  3.   
  4.   
  5. String s2=RsaUtil.decryptByPrivateKey(RsaKey.privateKey, pwd);  
  6. System.out.println(s2);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值