代码之家  ›  专栏  ›  技术社区  ›  LiamB

解码PEM(c#)

  •  1
  • LiamB  · 技术社区  · 14 年前

    我已经收集了一些我需要使用的旧代码,我在C中有以下函数

    int pem64_decode_bytes(const char *intext,
                           int nchars,
                           unsigned char *outbytes)
    {
      unsigned char *outbcopy = outbytes;
      while (nchars >= 4) {
        char 
          c1 = intext[0], 
          c2 = intext[1],
          c3 = intext[2],
          c4 = intext[3];
        int 
          b1 = pem64_dict_offset(c1), 
          b2 = pem64_dict_offset(c2),
          b3 = pem64_dict_offset(c3),
          b4 = pem64_dict_offset(c4);
    
        if ((b1 == -1) || (b2 == -1) || (b3 == -1) || (b4 == -1))
          return outbytes - outbcopy;
    
        *(outbytes++) = (b1 << 2) | (b2 >> 4);
    
        if (c3 != FILLERCHAR)
          *(outbytes++) = ((b2 & 0xf) << 4) | (b3 >> 2);
        if (c4 != FILLERCHAR)
          *(outbytes++) = ((b3 & 0x3) << 6) | b4;
    
        nchars -= 4;
        intext += 4;
      }
    
      return outbytes - outbcopy;
    }
    

    它应该对已编码的数据包进行解码。有人知道这是不是一个标准函数吗?我需要把它转换成C#,我不是C编码员有人知道有这样的例子吗?

    =======

    public static List<byte> pem64_decode_bytes(string InText, int NumberOfBytes)
        {
            var RetData = new List<byte>();
    
            while (NumberOfBytes >= 4)
            {
                char c1 = InText[0];
                char c2 = InText[1];
                char c3 = InText[2];
                char c4 = InText[3];
    
                int b1 = pem64_dict_offset(c1);
                int b2 = pem64_dict_offset(c2);
                int b3 = pem64_dict_offset(c3);
                int b4 = pem64_dict_offset(c4);
    
                if (b1 == -1 || b2 == -1 || b3 == -1 || b4 == -1)
                {
                    return RetData;
                }
    
                (outbytes)++.Deref = b1 << 2 | b2 >> 4;
                if (c3 != FILLERCHAR)
                {
                    (outbytes)++.Deref = (b2 & 0xf) << 4 | b3 >> 2;
                }
                if (c4 != FILLERCHAR)
                {
                    (outbytes)++.Deref = (b3 & 0x3) << 6 | b4;
                }
    
                NumberOfBytes -= 4;
            }
    
            return RetData;
        }
    
    1 回复  |  直到 14 年前
        1
  •  0
  •   Will Dean    14 年前

    你也有pem64\u dict\u offset的来源吗?我不认为这是一个标准函数,尽管它看起来很像Base64解码。

    如果是这样的话,转换成C#可能不是很难。

    List<Byte> outbytes = new List<Byte>()
    outbytes.Add(the new byte)
    

    “return outbytes outbcopy”将变为“return outbytes.Count”(尽管在C语言中更常见的做法是只返回列表,而不是要求调用者为您分配列表)。