云API示例
sample_config_file_cont = {
    "private_key": """
    >>>> your private key here <<<<
""",
 
    "public_key":"""-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDyZneSY2eGnhKrArxaT6zswVH9
/EKz+CLD+38kJigWj5UaRB6dDUK9BR6YIv0M9vVQZED2650tVhS3BeX04vEFhThn
NrJguVPidufFpEh3AgdYDzOQxi06AN+CGzOXPaigTurBxZDIbdU+zmtr6a8bIBBj
WQ4v2JR/BA6gVHV5TwIDAQAB
-----END PUBLIC KEY-----
""",
    "porn": {
        "secretId": '>>>> your secretId here <<<<',
        "url": 'http://api.open.tuputech.com/v3/recognition/'
    }
}
 
images = ["/path/to/your/image/1.jpg", "/path/to/your/image/2.jpg"]
 
def APITest():
    import hashlib
    import datetime
    from Crypto.Random import random
    from Crypto.PublicKey import RSA
    from Crypto.Hash.SHA256 import SHA256Hash
    from Crypto.Hash import SHA256
    from Crypto.Signature import PKCS1_v1_5
    import base64
    timestamp_str = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    nonce_str = str(random.randint(1 << 4, 1 << 32))
 
    task_name = "porn"
    task_conf = sample_config_file_cont[task_name]
 
    params = [task_conf['secretId'], timestamp_str, nonce_str]
    params_str = ''.join(["%s," % item for item in params])
    sign_params_str = params_str[:-1] #get rid of the last ','
 
    private_key_str = sample_config_file_cont["private_key"]
    rsa_private_key = RSA.importKey(private_key_str)
    hashed_params = SHA256Hash(sign_params_str)
    signer = PKCS1_v1_5.new(rsa_private_key)
    bin_sign = signer.sign(hashed_params)
    signature_base64 = base64.b64encode(bin_sign)
 
    for addr in images:
        print "addr:",addr
    # it is not needed when you post URL instead of file path.
    files = [('image', (addr[-6:], open(addr, 'rb'), 'image/png')) for addr in images]
    req_body = {
        #'image': urls, ** this field is required if you post as URLs **
        'timestamp': timestamp_str,
        'nonce': nonce_str,
        'signature': signature_base64
    }
    import grequests as requests
    request = requests.post(task_conf['url'] + task_conf['secretId'], data=req_body, files=files) #files is not required if you post as URLs
    response = request.send().response
    print("\n>>>>>>this is raw response content\n")
    print(response.content) # this is raw response content, before its been verified, it can not be trusted.
    print("\nraw content end ======\n")

    import json
    content = json.loads(response.content)['json']
    result = json.loads(content)
    task = result['54bcfc6c329af61034f7c2fc']

    code = result['code']
    fileList = task['fileList']


    # verify
    
    content = json.loads(response.content)
    recvSignature = content['signature']
 
    json_str = content['json']
    rsakey = RSA.importKey(sample_config_file_cont['public_key'])
    verifier = PKCS1_v1_5.new(rsakey)
    digest = SHA256.new(json_str)
 
    if verifier.verify(digest, base64.b64decode(recvSignature)):
        print "verified!"
    else:
        print "fail"
 
 
if __name__ == "__main__":
    APITest()

static void Main(string[] args)
{
	Random r = new Random();
	string secretId = "your_secret_id";//你的secretid
    string timestamp = DateTime.Now.GetHashCode().ToString;//当前时间
    string nonce = r.Rdm.Next(100,999999);//随机数
    string img_url = "";//图片链接
    string sign_string = secretId + "," + timestamp + "," + nonce;
	string taskUrl = "http://api.open.tuputech.com/v3/recognition/" + secretId;//任务链接

    //读取你的PKCS8格式的私钥
    string privateKey_pkcs8 = @"MIICdDSXsdd...";
	//读取图普公钥
    string publicKey_tupu = @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDyZneSY2eGnhKrArxaT6zswVH9
/EKz+CLD+38kJigWj5UaRB6dDUK9BR6YIv0M9vVQZED2650tVhS3BeX04vEFhThn
NrJguVPidufFpEh3AgdYDzOQxi06AN+CGzOXPaigTurBxZDIbdU+zmtr6a8bIBBj
WQ4v2JR/BA6gVHV5TwIDAQAB";

	//得到签名
    string signature = RSAFromPkcs8.sign(sign_string, privateKey_pkcs8);

	try
	{
		//设置上传参数
    string param = "&image=" + HttpUtility.UrlEncode(img_url)
						+ "&timestamp=" + timestamp
						+ "&nonce=" + nonce
						+ "&signature=" + HttpUtility.UrlEncode(signature);
		byte[] bates = Encoding.UTF8.GetBytes(param);

		HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(taskUrl);
		request.Method = "POST";
		request.ContentType = "application/x-www-form-urlencoded";
		request.ContentLength = bytes.Length;
		using(Stream stream = request.GetRequestStream())
		{
			stream.Write(bytes, 0, bytes.Length);
		}

		using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
		{
			StreamReader streamReader = new StreamReader(response.GetResponseStream(),Encoding.UTF8);
			string responseStr = streamReader.readToEnd();

			if(responseStr != null)
			{
				object obj = JavaScriptConvert.DeserializeObject(data);
				JavaScriptObject js = obj as JavaScriptObject;
				string json = js["json"].ToString();
				string signature = js["signature"].ToString();
				if(RSAFromPkcs8.verify(json, signature, publicKey_tupu)){
					Console.WriteLine("验证成功"+json);
				}else{
					Console.WriteLine("验证失败");
				}
			}
		}

	}catch (Exception)
	{

	}

}
签名和验证的工具类 RSAFromPkcs8
public sealed class RSAFromPkcs8
{
    /// 
                    /// 签名
                    ///
                
    /// 需要签名的内容
    /// 私钥
    /// 
    public static string sign(string content, string privateKey)
    {
        byte[] Data = Encoding.UTF8.GetBytes(content);
        RSACryptoServiceProvider rsa = DecodePemPrivateKey(privateKey);
        SHA256 sh = new SHA256CryptoServiceProvider();
  		byte[] signData = rsa.SignData(Data, sh);
        return Convert.ToBase64String(signData);
    }

    /// 
                    /// 验证签名
                    ///
                
    /// 需要验证的内容
    /// 签名结果
    /// 公钥
    /// 
    public static bool verify(string content, string signedString, string publicKey)
    {
        bool result = false;

        byte[] Data = Encoding.UTF8.GetBytes(content);
        byte[] data = Convert.FromBase64String(signedString);
        RSAParameters paraPub = ConvertFromPublicKey(publicKey);
        RSACryptoServiceProvider rsaPub = new RSACryptoServiceProvider();
        rsaPub.ImportParameters(paraPub);

        SHA256 sh = new SHA256CryptoServiceProvider();
        result = rsaPub.VerifyData(Data, sh, data);
        return result;
    }

    /// 
                    /// 解析pem文件--私钥
                    ///
                
    /// 
    /// 
    private static RSACryptoServiceProvider DecodePemPrivateKey(String pemstr)
    {
        byte[] pkcs8privatekey;
        pkcs8privatekey = Convert.FromBase64String(pemstr);
        if (pkcs8privatekey != null)
        {
			RSACryptoServiceProvider rsa = DecodePrivateKeyInfo(pkcs8privatekey);
            return rsa;
        }else
            return null;
    }

    private static RSACryptoServiceProvider DecodePrivateKeyInfo(byte[] pkcs8)
    {
    	byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
        byte[] seq = new byte[15];

        MemoryStream mem = new MemoryStream(pkcs8);
        int lenstream = (int)mem.Length;
        BinaryReader binr = new BinaryReader(mem);    //wrap Memory Stream with BinaryReader for easy reading
            byte bt = 0;
            ushort twobytes = 0;

            try
            {

            twobytes = binr.ReadUInt16();
            if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                binr.ReadByte();    //advance 1 byte
            else if (twobytes == 0x8230)
                binr.ReadInt16();   //advance 2 bytes
            else
                return null;

			bt = binr.ReadByte();
            if (bt != 0x02)
                return null;

            twobytes = binr.ReadUInt16();

            if (twobytes != 0x0001)
                return null;

            seq = binr.ReadBytes(15);       //read the Sequence OID
            if (!CompareBytearrays(seq, SeqOID))    //make sure Sequence for OID is correct
                return null;

            bt = binr.ReadByte();
            if (bt != 0x04) //expect an Octet string
                return null;

            bt = binr.ReadByte();       //read next byte, or next 2 bytes is  0x81 or 0x82; otherwise bt is the byte count
            if (bt == 0x81)
                binr.ReadByte();
            else if (bt == 0x82)
                binr.ReadUInt16();
            //------ at this stage, the remaining sequence should be the RSA private key

            byte[] rsaprivkey = binr.ReadBytes((int)(lenstream - mem.Position));
            RSACryptoServiceProvider rsacsp = DecodeRSAPrivateKey(rsaprivkey);
            return rsacsp;
        }catch (Exception)
        {
            return null;
        }finally {
        	binr.Close();
        }
    }

	private static bool CompareBytearrays(byte[] a, byte[] b)
    {
        if (a.Length != b.Length)
            return false;
        int i = 0;
        foreach (byte c in a)
        {
            if (c != b[i])
                return false;
            i++;
        }
        return true;
    }

    private static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
    {
        byte[] MODULUS, E, D, P, Q, DP, DQ, IQ;

        // ---------  Set up stream to decode the asn.1 encoded RSA private key  ------
        MemoryStream mem = new MemoryStream(privkey);
        BinaryReader binr = new BinaryReader(mem);    //wrap Memory Stream with BinaryReader for easy reading
        byte bt = 0;
        ushort twobytes = 0;
        int elems = 0;
        try
        {
            twobytes = binr.ReadUInt16();
            if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                binr.ReadByte();    //advance 1 byte
            else if (twobytes == 0x8230)
                binr.ReadInt16();   //advance 2 bytes
            else
                return null;

            twobytes = binr.ReadUInt16();
            if (twobytes != 0x0102) //version number
                return null;
            bt = binr.ReadByte();
            if (bt != 0x00)
                return null;

			//------  all private key components are Integer sequences ----
            elems = GetIntegerSize(binr);
            MODULUS = binr.ReadBytes(elems);

            elems = GetIntegerSize(binr);
            E = binr.ReadBytes(elems);

            elems = GetIntegerSize(binr);
            D = binr.ReadBytes(elems);

            elems = GetIntegerSize(binr);
            P = binr.ReadBytes(elems);

            elems = GetIntegerSize(binr);
            Q = binr.ReadBytes(elems);

            elems = GetIntegerSize(binr);
            DP = binr.ReadBytes(elems);

            elems = GetIntegerSize(binr);
            DQ = binr.ReadBytes(elems);

            elems = GetIntegerSize(binr);
            IQ = binr.ReadBytes(elems);

            // ------- create RSACryptoServiceProvider instance and initialize with public key -----
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            RSAParameters RSAparams = new RSAParameters();
            RSAparams.Modulus = MODULUS;
            RSAparams.Exponent = E;
            RSAparams.D = D;
            RSAparams.P = P;
            RSAparams.Q = Q;
            RSAparams.DP = DP;
            RSAparams.DQ = DQ;
            RSAparams.InverseQ = IQ;
            RSA.ImportParameters(RSAparams);
            return RSA;
        }catch (Exception)
        {
            return null;
        }finally {
        	binr.Close();
        }
    }

    private static int GetIntegerSize(BinaryReader binr)
    {
        byte bt = 0;
        byte lowbyte = 0x00;
        byte highbyte = 0x00;
        int count = 0;
        bt = binr.ReadByte();
        if (bt != 0x02)     //expect integer
                return 0;
        bt = binr.ReadByte();

        if (bt == 0x81)
            count = binr.ReadByte();    // data size in next byte
        else if (bt == 0x82)
        {
            highbyte = binr.ReadByte(); // data size in next 2 bytes
            lowbyte = binr.ReadByte();
            byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
            count = BitConverter.ToInt32(modint, 0);
        }else
        {
            count = bt;     // we already have the data size
        }

		while (binr.ReadByte() == 0x00)
        {   //remove high order zeros in data
            count -= 1;
        }
        binr.BaseStream.Seek(-1, SeekOrigin.Current);       //last ReadByte wasn't a removed zero, so back up a byte
        return count;
    }

    #region 解析Pem文件--公钥
    private static RSAParameters ConvertFromPublicKey(string pemFileConent)
    {
    	byte[] keyData = Convert.FromBase64String(pemFileConent);
        if (keyData.Length < 162)
        {
            throw new ArgumentException("pem file content is incorrect.");
        }
        byte[] pemModulus = new byte[128];
        byte[] pemPublicExponent = new byte[3];
        Array.Copy(keyData, 29, pemModulus, 0, 128);
        Array.Copy(keyData, 159, pemPublicExponent, 0, 3);
        RSAParameters para = new RSAParameters();
        para.Modulus = pemModulus;
        para.Exponent = pemPublicExponent;
        return para;
    }

    private static RSAParameters ConvertFromPrivateKey(string pemFileConent)
    {
        byte[] keyData = Convert.FromBase64String(pemFileConent);
        if (keyData.Length < 609)
        {
            throw new ArgumentException("pem file content is incorrect.");
        }

        int index = 11;
        byte[] pemModulus = new byte[128];
        Array.Copy(keyData, index, pemModulus, 0, 128);

        index += 128;
        index += 2;//141
        byte[] pemPublicExponent = new byte[3];
        Array.Copy(keyData, index, pemPublicExponent, 0, 3);

        index += 3;
        index += 4;//148
        byte[] pemPrivateExponent = new byte[128];
        Array.Copy(keyData, index, pemPrivateExponent, 0, 128);

        index += 128;
        index += ((int)keyData[index + 1] == 64 ? 2 : 3);//279
        byte[] pemPrime1 = new byte[64];
        Array.Copy(keyData, index, pemPrime1, 0, 64);

        index += 64;
        index += ((int)keyData[index + 1] == 64 ? 2 : 3);//346
        byte[] pemPrime2 = new byte[64];
        Array.Copy(keyData, index, pemPrime2, 0, 64);

        index += 64;
        index += ((int)keyData[index + 1] == 64 ? 2 : 3);//412/413
        byte[] pemExponent1 = new byte[64];
        Array.Copy(keyData, index, pemExponent1, 0, 64);

        index += 64;
        index += ((int)keyData[index + 1] == 64 ? 2 : 3);//479/480
        byte[] pemExponent2 = new byte[64];
        Array.Copy(keyData, index, pemExponent2, 0, 64);

        index += 64;
        index += ((int)keyData[index + 1] == 64 ? 2 : 3);//545/546
        byte[] pemCoefficient = new byte[64];
        Array.Copy(keyData, index, pemCoefficient, 0, 64);

        RSAParameters para = new RSAParameters();
        para.Modulus = pemModulus;
        para.Exponent = pemPublicExponent;
        para.D = pemPrivateExponent;
        para.P = pemPrime1;
        para.Q = pemPrime2;
        para.DP = pemExponent1;
        para.DQ = pemExponent2;
        para.InverseQ = pemCoefficient;
        return para;
    }
    #endregion
}