菜鸟教程小白 发表于 2022-12-13 14:10:54

c# - AES - c# 加密和 objective-c 解密不起作用


                                            <p><p>当我在 C# 中加密并尝试在Objective C中解密它不起作用。
你能检查一下,让我知道我做错了什么。</p>

<p>C#代码</p>

<pre><code>byte[] strKey = Convert.FromBase64String(&#34;CAshKUlVCllbEwPmzS4cTg==&#34;);
byte[] strIV = Convert.FromBase64String(&#34;HDAxBBlsKyVeIuS63kdCjg==&#34;);
byte[] strOutput = EncryptStringToBytes_Aes(&#34;satishsatyam&#34;, strKey, strIV);
string strOutput1 = ByteToString(strOutput);//i6BMzAlcnz6Z5dQKWkio7A==

static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
    {
      byte[] encrypted;
      // Create an Aes object
      // with the specified key and IV.
      using (Aes aesAlg = Aes.Create())
      {
            aesAlg.Mode = CipherMode.ECB;
            aesAlg.Padding = PaddingMode.PKCS7;
            aesAlg.KeySize = 256;
            aesAlg.BlockSize = 128;

            // Create an encryptor to perform the stream transform.
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(Key, IV);

            // Create the streams used for encryption.
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                  using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                  {
                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                  }
                  encrypted = msEncrypt.ToArray();
                }
            }
      }
      return encrypted;
    }
private string ByteToString(byte[] objByte)
    {
      string strOutput = Convert.ToBase64String(objByte);

      return strOutput;
    }
</code></pre>

<p> Objective-C </p>

<pre><code>//
//CryptLib.h
//

#import &lt;CommonCrypto/CommonDigest.h&gt;
#import &lt;CommonCrypto/CommonCryptor.h&gt;
#import &lt;UIKit/UIKit.h&gt;

@interface CryptLib : NSObject

-(NSData *)encrypt:(NSData *)plainText key:(NSString *)key iv:(NSString *)iv;
-(NSData *)decrypt:(NSData *)encryptedText key:(NSString *)key iv:(NSString *)iv;
-(NSData *)generateRandomIV:(size_t)length;
-(NSString *) md5:(NSString *) input;
-(NSString*) sha256:(NSString *)key length:(NSInteger) length;

@end


#import &#34;CryptLib.h&#34;
#import &#34;NSData+Base64.h&#34;

@implementation CryptLib


-(NSData *)decrypt:(NSData *)encryptedText key:(NSString *)key iv:(NSString *)iv {
    char keyPointer,// room for terminator (unused) ref: https://devforums.apple.com/message/876053#876053
    ivPointer;
    BOOL patchNeeded;

    patchNeeded = ( &gt; kCCKeySizeAES256+1);
    if(patchNeeded)
    {
      NSLog(@&#34;Key length is longer %lu&#34;, (unsigned long)[[ md5:key] length]);
      key = ; // Ensure that the key isn&#39;t longer than what&#39;s needed (kCCKeySizeAES256)
    }

    ;
    ;

    if (patchNeeded) {
      keyPointer = &#39;\0&#39;;// Previous iOS version than iOS7 set the first char to &#39;\0&#39; if the key was longer than kCCKeySizeAES256
    }

    NSUInteger dataLength = ;

    //see https://developer.apple.com/library/ios/documentation/System/Conceptual/ManPages_iPhoneOS/man3/CCryptorCreateFromData.3cc.html
    // For block ciphers, the output size will always be less than or equal to the input size plus the size of one block.
    size_t buffSize = dataLength + kCCBlockSizeAES128;

    void *buff = malloc(buffSize);

    size_t numBytesEncrypted = 0;
    //refer to http://www.opensource.apple.com/source/CommonCrypto/CommonCrypto-36064/CommonCrypto/CommonCryptor.h
    //for details on this function
    //Stateless, one-shot encrypt or decrypt operation.
    CCCryptorStatus status = CCCrypt(kCCDecrypt,/* kCCEncrypt, etc. */
                                     kCCAlgorithmAES128, /* kCCAlgorithmAES128, etc. */
                                     kCCOptionPKCS7Padding, /* kCCOptionPKCS7Padding, etc. */
                                     keyPointer, kCCKeySizeAES256,/* key and its length */
                                     ivPointer, /* initialization vector - use same IV which was used for decryption */
                                     , , //input
                                     buff, buffSize,//output
                                     &amp;numBytesEncrypted);
    if (status == kCCSuccess) {
      return ;
    }

    free(buff);
    return nil;
}

#import &#34;ViewController.h&#34;
#import &#34;CryptLib.h&#34;


@interface ViewController ()

@end

@implementation ViewController
- (void)viewDidLoad {
    ;
    libr = [init];

   NSString *inputString = @&#34;sample testing&#34;; // this is the text that you want to encrypt.
   NSLog(@&#34;inputString : %@&#34;, inputString); //print the inputString text

   NSString * _key = @&#34;shared secret&#34;; //secret key for encryption. To make encryption stronger, we will not use this key directly. We&#39;ll first hash the key next step and then use it.

    // _key = [ sha256:_key length:32]; //this is very important, 32 bytes = 256 bit
    _key = @&#34;CAshKUlVCllbEwPmzS4cTg==&#34;;
   NSLog(@&#34;_key data:: %@&#34;, _key); //print the _key text

   // NSString * iv =[[base64EncodingWithLineLength:0] substringToIndex:16]; //Here we are generating random initialization vector (iv). Length of this vector = 16 bytes = 128 bits
    NSString * iv = @&#34;HDAxBBlsKyVeIuS63kdCjg==&#34;;
    NSLog(@&#34;iv data:: %@&#34;, iv); //print the iv text

    NSData *encryptedData = key:_key iv:iv];
    NSString * decryptedText = [ initWithData:encryptedData encoding:NSUTF8StringEncoding];
    NSLog(@&#34;decrypted data:: %@&#34;, decryptedText); //print the decrypted text

}
</code></pre>

<p>任何适用于 ios/Android,c# 的跨平台示例代码</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>第一步是以十六进制记录加密调用前后的所有输入和输出,以便验证是否相同。<br/>
还要验证所有参数是否相同且正确,这可能需要阅读文档以确定默认值。</p>

<p>实际的加密函数比较简单,只是一个函数调用,没有什么神秘的东西,只要输入正确就行了。</p>

<ol>
<li><p>您没有为 C# 和 ObjC 代码提供相同的参数。 C#为ECB模式,ObjC为CBC模式(默认)。<br/>
使用 CBC 模式。</p></li>
<li><p> keyBase64: "CAshKUlVCllbEwPmzS4cTg=="<br/>
是十六进制 080B212949550A595B1303E6CD2E1C4E<br/>
这是16个字节。<br/>
在 C# 和 ObjC 中,您将 key 大小声明为 256 位(32 字节):分别为 <code>aesAlg.KeySize = 256;</code> 和 <code>kCCKeySizeAES256</code>。<br/>
将 128 位 key 的 key 大小指定为 128 位。</p></li>
<li><p>在 ObjC 代码中,您不是对 key 和 iv 进行 Base64 解码。</p></li>
<li><p>没有理由使用第 3 方 Base64 库。</p></li>
</ol>

<p>更新了示例代码,没有错误检查:不适用于生产:</p>

<pre><code>// First convert Base64 strings to data
NSString *stringIn = @&#34;satishsatyam&#34;;
NSData *dataIn   = ;
NSData *iv         = [ initWithBase64EncodedString:@&#34;HDAxBBlsKyVeIuS63kdCjg==&#34; options:0];
NSData *key      = [ initWithBase64EncodedString:@&#34;CAshKUlVCllbEwPmzS4cTg==&#34; options:0];

// Encryption
size_t         encryptBytes = 0;
NSMutableData *encrypted= ;
CCCrypt(kCCEncrypt,
      kCCAlgorithmAES,
      kCCOptionPKCS7Padding, // CBC is the default mode
      key.bytes, kCCKeySizeAES128,
      iv.bytes,
      dataIn.bytes, dataIn.length,
      encrypted.mutableBytes, encrypted.length,
      &amp;encryptBytes);
encrypted.length = encryptBytes;
NSLog(@&#34;encrypted hex:    %@&#34;, encrypted);
NSLog(@&#34;encrypted Base64: %@&#34;, );

// Decryption
size_t         decryptBytes = 0;
NSMutableData *decrypted= ;
CCCrypt(kCCDecrypt,
      kCCAlgorithmAES,
      kCCOptionPKCS7Padding, // CBC is the default mode
      key.bytes, kCCKeySizeAES128,
      iv.bytes,
      encrypted.bytes, encrypted.length,
      decrypted.mutableBytes, decrypted.length,
      &amp;decryptBytes);
decrypted.length = decryptBytes;

NSLog(@&#34;decrypted in hex: %@&#34;, decrypted);
NSLog(@&#34;decrypted string: %@&#34;, [ initWithData:decrypted encoding: NSUTF8StringEncoding]);
</code></pre>

<p>输出:</p>

<blockquote>
<p>encrypted as hex:    cbdb58fe ad464126 ea90252b 2ff52276<br/>
encrypted Base64: y9tY/q1GQSbqkCUrL/Uidg==<br/>
decrypted as hex: 73617469 73687361 7479616d<br/>
decrypted string: satishsatyam</p>
</blockquote></p>
                                   
                                                <p style="font-size: 20px;">关于c# - AES - c# 加密和 objective-c解密不起作用,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/35297582/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/35297582/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: c# - AES - c# 加密和 objective-c 解密不起作用