C使用openssl RSA base64对数据进行加密解密出错 20C

对数据进行RSA base64加密的时候没有出错,但是在解码base64的时候解码出来的字符串为空。
附代码,求大佬帮忙看一下:

int base64_encode(char *in_str, int in_len, char *out_str)
{
    BIO *b64, *bio;
    BUF_MEM *bptr = NULL;
    size_t size = 0;

    if (in_str == NULL || out_str == NULL)
        return -1;

    b64 = BIO_new(BIO_f_base64());
    bio = BIO_new(BIO_s_mem());
    bio = BIO_push(b64, bio);

    BIO_write(bio, in_str, in_len);
    BIO_flush(bio);

    BIO_get_mem_ptr(bio, &bptr);
    memcpy(out_str, bptr->data, bptr->length);
    out_str[bptr->length] = '\0';
    size = bptr->length;

    BIO_free_all(bio);
    return size;
}
int base64_decode(char *in_str, int in_len, char *out_str)
    {
    BIO *b64, *bio;
    BUF_MEM *bptr = NULL;
    int counts;
    int size = 0;

    if (in_str == NULL || out_str == NULL)
        return -1;

    b64 = BIO_new(BIO_f_base64());
    BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);

    bio = BIO_new_mem_buf(in_str, in_len);
    bio = BIO_push(b64, bio);

    size = BIO_read(bio, out_str, in_len);
    out_str[size] = '\0';

    BIO_free_all(bio);
    return size;
}
unsigned char *my_encrypt(char *str,char *path_key){
    char *p_en;
    RSA *p_rsa;
    FILE *file,*p_file;
    int flen,rsa_len;
    if((file=fopen(path_key,"r"))==NULL){
        perror("open key file error");
        return NULL;
    }
    if((p_rsa=PEM_read_RSA_PUBKEY(file,NULL,NULL,NULL))==NULL){//PUBLIC KEY
    // if((p_rsa=PEM_read_RSAPublicKey(file,NULL,NULL,NULL))==NULL){//RSA PUBLIC KEY
    ERR_print_errors_fp(stdout);
        return NULL;
    }
    flen=strlen(str);
    rsa_len=RSA_size(p_rsa);
    p_en=(unsigned char *)malloc(rsa_len+1);
    memset(p_en,0,rsa_len+1);
    if(RSA_public_encrypt(rsa_len,(unsigned char *)str,(unsigned char*)p_en,p_rsa,RSA_NO_PADDING)<0){
        return NULL;
    }
    RSA_free(p_rsa);
    fclose(file);

    // p_file=fopen("./p_file.txt","w");
    // fputs(p_en, p_file);
    return p_en;
}
char *my_decrypt(unsigned char *str,char *path_key){
    char *p_de;
    RSA *p_rsa;
    FILE *file;
    int rsa_len;
    if((file=fopen(path_key,"r"))==NULL){
        perror("open key file error");
        return NULL;
    }
    if((p_rsa=PEM_read_RSAPrivateKey(file,NULL,NULL,NULL))==NULL){
        ERR_print_errors_fp(stdout);
        return NULL;
    }
    rsa_len=RSA_size(p_rsa);
    p_de=(unsigned char *)malloc(rsa_len+1);
    memset(p_de,0,rsa_len+1);
    if(RSA_private_decrypt(rsa_len,(unsigned char *)str,(unsigned char*)p_de,p_rsa,RSA_NO_PADDING)<0){
        return NULL;
    }
    RSA_free(p_rsa);
    fclose(file);
    return p_de;
}
main{
        char source[1024]="hello";
    char *ptr_en,*ptr_de, base64_en[1024] = "", base64_de[1024] = "";
    printf("source is    :%s\n",source);

    ptr_en=my_encrypt(source,PUBLICKEY);
    printf("ptr_en strlen = %d\n", strlen(ptr_en));
    printf("after encrypt:%s\n",ptr_en);

    base64_encode(ptr_en,strlen(ptr_en),base64_en);
    printf("after encode len: %d\nmsg:%s\n",strlen(base64_en), base64_en);
    base64_decode(base64_en,strlen(base64_en),base64_de);
    printf("after decode len: %d\nmsg:%s\n",strlen(base64_de), base64_de);//len输出长度为0 数据为空

    ptr_de=my_decrypt(base64_de,OPENSSLKEY);
    printf("ptr_de strlen = %d\n", strlen(ptr_de));
    printf("after decrypt:%s\n",ptr_de);
    if(ptr_en!=NULL){
    free(ptr_en);
    }
    if(ptr_de!=NULL){
    free(ptr_de);
    }
    return 0;
        }

base64_decode解码后长度为0,数据为空。当他们单独使用的加密解密的时候没问题,合起来就会出现这个情况,求大佬看一下 ,非常感谢

1个回答

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
如何实现C++版的RSA加密,在不使用Openssl的情况下

已知公钥和私钥都是字符串、不使用Openssl等库的情况下实现C++版的RSA加密

openssl php RSA密钥生成错误,无法加密

$res = openssl_pkey_new(); @openssl_pkey_export($res,$pri); @$d= openssl_pkey_get_details($res); $pub = $d['key']; var_dump($pub); //为什么会输出空? $res = openssl_pkey_get_private($pri); if (@openssl_sign('hello', $out, $res)) { echo $out."<br>".base64_encode($out); } $sig = $out; $sig = base64_decode($sig); $res = openssl_pkey_get_public($pub); if (@openssl_verify('hello', $sig, $res) === 1) { echo "ok"; }else{ echo "flase"; }

PHP RSA-公钥base64编码

<div class="post-text" itemprop="text"> <p>I am working on a web application and I need to talk to server in encrypted way using RSA public/private key. I have a public key in a text file like this:</p> <pre><code>¨Ì�sr�java.math.BigIntegerå¸ü©;˚�I�bitCountIbitLengthI�firstNonzeroByteNumI�lowestSetBitI�signum[ � magnitudet�[Bxr�java.lang.Numberܨïî‡ã��xpˇˇˇˇˇˇˇˇˇˇˇ˛ˇˇˇ˛���ur�[B¨Û¯T‡��xp���ØÕ..˛¶⁄ [í'‰∑S~ÆhU‚Ãu|ˆ*Ÿ"E˝x©àÚ†qçÎU¬òü`Oˇ?{q^⁄/O'•à%œÍ¬S� ∏íU$0≥i‹Hï™è&gt;æ∑÷é˜ FVÚµ™ŒR=*ÑπGF%À¨ËߥÀüm‡(T¨‘Pq.ã3ˇ∑Ò;ªmÔ˙ C–„¿ç5åÌŒææ°4ån”®Å–MAQ’kÜì∑ÊË°ÂÅíîc»AÈ� ∫ıƒËv:eÚDÑØKv3Áq”cO´HÁzπ…ÅÔ©ˇwlWènö◊aAß° m͇ïöH˚Æ)˛WeŸci·JbÜ q˙H£xsq�~��ˇˇˇˇˇˇˇˇˇˇˇ˛ˇˇˇ˛���uq�~����≠íi5˛¸¥Q‚í(2ûfiΩL0ΩÅ≤ò` ÷…7¯ú)K´ºÎW2j·°Ø«¨X”gºŸ«lÇ8øÃ√3RÕ·ƒŸÚ¢fl∆,flr’X∆È|˚ì[Nfl%≈Búp·≤∑◊gπrõà–À≠˛`»Á†U„«¨ë+e|üæÄ®iLˇ⁄q¨@ä;…gRî&gt;òvû+…U^ËÕdT∫|≠˙N"#zßø⁄+Å2ï¢=Nûe≠D˙§∞7X≥QPZ(Û`Ã-àÙ√ÿ÷Û˘£5[ŒÂ◊�IÄfiV bf´ÄÍÚ∫ê!*Ô´õD »E˛˙úhiô{ì“åCZWœ-åWÊ6‘t·x </code></pre> <p>When I try to base64 encode it the result is:</p> <pre><code>rO0ABXNyABRqYXZhLm1hdGguQmlnSW50ZWdlcoz8nx+pO/sdAwAGSQAIYml0Q291bnRJAAliaXRMZW5ndGhJABNmaXJzdE5vbnplcm9CeXRlTnVtSQAMbG93ZXN0U2V0Qml0SQAGc2lnbnVtWwAJbWFnbml0dWRldAACW0J4cgAQamF2YS5sYW5nLk51bWJlcoaslR0LlOCLAgAAeHD///////////////7////+AAAAAXVyAAJbQqzzF/gGCFTgAgAAeHAAAAEAr80ULi7+ptoVW5In5LdTfq5oVeLMdXwO9irZIkX9eKmI8qBxjetVwpifYE8M/z8ee3Fe2i9PJ6WIJQ/PHOrCUwAJA7iSVQEYAyQwF7Np3BRIlaqPPr631o73IEZW8rWqzlI9KoS5R0Yly6zop7TLn23gKFSs1FBxGi6LCjMe/7fxO7tt7/p/AUPQ48CNNYzGCu3Ovr6hNIxuBBzTqIHQTUFR1WuGk7fm6KHlgZIelAsWY8hB6QC6B3/1xALodjpl8kSErwRLdjPncdNjT6sZSOd6ucmBGu+p/3dsV49umtdhQacCocpt6uCVmkgM+64p/ldl2WMSaeFKYoYgcfpIo3hzcQB+AAD///////////////7////+AAAAAXVxAH4ABAAAAQCtDpJpDDX+Bfy0UeIXkigNMp7evQ5MML2Bsphg1sk3+JwpS6u86wdXMmrhoa/HrFjTZ7zZx2yCOL8WzMMzUh3NGuHE2fKi3xrGLN9y1VjGHul8+5NbTt8lxUKccOGytwbXZ7lym4jQEsut/h5gyOcRoFXjHceskStlfJ++gKhpTP/acaxAijvJZ1IRlD6Ydp4ryQNVXujNZFS6fK36TiJ/I3qnvxfaK4EylaISPU6eZa1E+qSwN1gQs1FQWigQ82DMLYj0w9jW8/mjNRpbEs7l1wBJgN5WCWJmqweA6vK6kCEq76ubRAnIRf76nGhpmXuT0oxDEVpXzy2MV+Y21HTheA== </code></pre> <p>which always gives me an invalid public key. When I try:</p> <pre><code>openssl_public_encrypt($data, $encrypted_data, base64_encode($key), OPENSSL_PKCS1_PADDING); </code></pre> <p>I know that the public key must start with:</p> <pre><code>-----BEGIN PUBLIC KEY----- </code></pre> <p>and ending with:</p> <pre><code>-----END PUBLIC KEY----- </code></pre> <p>I tried to use:</p> <pre><code>"-----BEGIN PUBLIC KEY----- " . chunk_split(base64_encode($key)) . " -----END PUBLIC KEY-----"; </code></pre> <p>but it is still not working. Can anyone offer any help?</p> </div>

C ++中的RSA解密,PHP中的加密

<div class="post-text" itemprop="text"> <p>I am working on an application which generates RSA encrypted session keys and stores them in a database. Later theses keys are transfered to a C++ application via Javascript. Therefore I want to use the OpenSSL library. I generated a 2048 bit key pair with openssl, which is used in both methods.</p> <p>My PHP functions works like this:</p> <pre><code>function encrypt_with_public_key($input, $key) { openssl_public_encrypt($input, $crypttext, $key, OPENSSL_PKCS1_OAEP_PADDING); return $crypttext; } </code></pre> <p>and</p> <pre><code>$fp = fopen("public.pem","r"); $public_pem = fread($fp,8192); fclose($fp); $public_key = openssl_get_publickey($public_pem); $sessionKey = ...; $encSessionKey = encrypt_with_public_key($sessionKey, $public_key); </code></pre> <p>I tested this part successfully. The part I have trouble with, is the C++ part. I use MS Visual Studio 2013. <strong>Edit</strong>: added hex encoding (using Crypto++)</p> <pre><code>#include &lt;openssl/pem.h&gt; #include &lt;openssl/rsa.h&gt; #include &lt;openssl/err.h&gt; #include &lt;openssl/crypto.h&gt; ... string decrypted, encoded; decrypted.clear(); char privateKey[] = "-----BEGIN RSA PRIVATE KEY----- "\ ... RSA *rsa = NULL; BIO *keybio; keybio = BIO_new_mem_buf(privateKey, strlen(privateKey)); rsa = PEM_read_bio_RSAPrivateKey(keybio, &amp;rsa, NULL, NULL); StringSource ss2(input, true, new HexEncoder( new StringSink(encoded) ) ); RSA_private_decrypt(encoded.length(), (unsigned char *)encoded.data(), (unsigned char *)decrypted.data(), rsa, RSA_PKCS1_OAEP_PADDING); FBLOG_INFO("", ERR_error_string(ERR_get_error(), NULL)); return decrypted; </code></pre> <p>Note that the private key is not read from a file.</p> <p>OpenSSL returns the following error: 0406506C: lib(4): func(101): reason(108).</p> <p>It means afaik that my input data is longer than the modulus length (please correct me if I'm wrong). Anyone who knows how to handle this? I thought such problems are solved through the padding parameters.</p> <p>The input data is the direct output of the php encrypt function (no base64 oder anything).</p> </div>

在JavaScript中加密字符串并使用RSA技术在PHP中解密

<div class="post-text" itemprop="text"> <p>I am trying to encrypt some text in JavaScript and then send it to PHP (etc: with Ajax) to decrypt it there and save it (etc: In MySQL).</p> <p>Here is my code so far:</p> <p><strong>In JavaScript:</strong></p> <p>I am using this library for the encryption: <a href="http://travistidwell.com/blog/2013/02/15/a-better-library-for-javascript-asymmetrical-rsa-encryption/" rel="nofollow">http://travistidwell.com/blog/2013/02/15/a-better-library-for-javascript-asymmetrical-rsa-encryption/</a></p> <pre><code>function ConvertToURL(data) { // Converts data to URL friendly form // etc: Replaces '+', '/', '=' with 'plus', 'slash', 'equal' }; function AjaxOrder(data) { // Sends data in PHP with Ajax } var publicKey = '-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDlOJu6TyygqxfWT7eLtGDwajtN FOb9I5XRb6khyfD1Yt3YiCgQWMNW649887VGJiGr/L5i2osbl8C9+WJTeucF+S76 xFxdU6jE0NQ+Z+zEdhUTooNRaY5nZiu5PgDB0ED/ZKBUSLKL7eibMxZtMlUDHjm4 gwQco1KRMDSmXSMkDwIDAQAB -----END PUBLIC KEY-----'; var encrypt = new JSEncrypt(); encrypt.setPublicKey(publicKey); var encrypted = encrypt.encrypt('Text to send.'); *// And now I am sending the encrypted text with some Ajax function* AjaxOrder(ConvertToURL(encrypted)); </code></pre> <p><strong>In PHP:</strong></p> <pre><code>$dataPost = $_POST('dt'); function ConvertFromURL($data) { // Converts $data to original form // etc: Replaces 'plus', 'slash', 'equal' with '+', '/', '=' } function ReturnData($data) { // Sends $data back in JavaScript as an answer to Ajax } $privateKey = '-----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDlOJu6TyygqxfWT7eLtGDwajtNFOb9I5XRb6khyfD1Yt3YiCgQ WMNW649887VGJiGr/L5i2osbl8C9+WJTeucF+S76xFxdU6jE0NQ+Z+zEdhUTooNR aY5nZiu5PgDB0ED/ZKBUSLKL7eibMxZtMlUDHjm4gwQco1KRMDSmXSMkDwIDAQAB AoGAfY9LpnuWK5Bs50UVep5c93SJdUi82u7yMx4iHFMc/Z2hfenfYEzu+57fI4fv xTQ//5DbzRR/XKb8ulNv6+CHyPF31xk7YOBfkGI8qjLoq06V+FyBfDSwL8KbLyeH m7KUZnLNQbk8yGLzB3iYKkRHlmUanQGaNMIJziWOkN+N9dECQQD0ONYRNZeuM8zd 8XJTSdcIX4a3gy3GGCJxOzv16XHxD03GW6UNLmfPwenKu+cdrQeaqEixrCejXdAF z/7+BSMpAkEA8EaSOeP5Xr3ZrbiKzi6TGMwHMvC7HdJxaBJbVRfApFrE0/mPwmP5 rN7QwjrMY+0+AbXcm8mRQyQ1+IGEembsdwJBAN6az8Rv7QnD/YBvi52POIlRSSIM V7SwWvSK4WSMnGb1ZBbhgdg57DXaspcwHsFV7hByQ5BvMtIduHcT14ECfcECQATe aTgjFnqE/lQ22Rk0eGaYO80cc643BXVGafNfd9fcvwBMnk0iGX0XRsOozVt5Azil psLBYuApa66NcVHJpCECQQDTjI2AQhFc1yRnCU/YgDnSpJVm1nASoRUnU8Jfm3Oz uku7JUXcVpt08DFSceCEX9unCuMcT72rAQlLpdZir876 -----END RSA PRIVATE KEY-----'; openssl_private_decrypt(ConvertFromURL($dataPost), $decryptedWord, $privateKey); ReturnData(base64_encode($decryptedWord)); </code></pre> <p>Now the answer from PHP is empty every time. Any ideas to make this work?</p> <p>Thank you for your time!</p> </div>

java 如何实现PEM格式的RSA加密和解密

思路是: 1、先用.NET生成XML格式的公钥和密钥 ``` /// <summary> ///在给定路径中生成XML格式的私钥和公钥。 /// </summary> public void GenerateKeys(string path) { using (var rsa = new RSACryptoServiceProvider(RsaKeySize)) { try { // 获取私钥和公钥。 var publicKey = rsa.ToXmlString(false); var privateKey = rsa.ToXmlString(true); // 保存到磁盘 File.WriteAllText(Path.Combine(path, publicKeyFileName), publicKey); File.WriteAllText(Path.Combine(path, privateKeyFileName), privateKey); MessageBox.Show(string.Format("生成的RSA密钥的路径: {0}\\ [{1}, {2}]", path, publicKeyFileName, privateKeyFileName)); } finally { rsa.PersistKeyInCsp = false; } } } ``` 2、再用BouncyCastle将XML的公钥和密钥转成PEM格式的 ``` /// <summary> /// RSA私钥格式转换,.net->java /// </summary> /// <param name="privateKey">.net生成的私钥</param> /// <returns></returns> public static string RSAPrivateKeyDotNet2Java(string privateKey) { XmlDocument doc = new XmlDocument(); doc.LoadXml(privateKey); BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText)); BigInteger exp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText)); BigInteger d = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("D")[0].InnerText)); BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("P")[0].InnerText)); BigInteger q = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Q")[0].InnerText)); BigInteger dp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DP")[0].InnerText)); BigInteger dq = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DQ")[0].InnerText)); BigInteger qinv = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("InverseQ")[0].InnerText)); RsaPrivateCrtKeyParameters privateKeyParam = new RsaPrivateCrtKeyParameters(m, exp, d, p, q, dp, dq, qinv); PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKeyParam); byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded(); return Convert.ToBase64String(serializedPrivateBytes); } /// <summary> /// RSA公钥格式转换,.net->java /// </summary> /// <param name="publicKey">.net生成的公钥</param> /// <returns></returns> public static string RSAPublicKeyDotNet2Java(string publicKey) { XmlDocument doc = new XmlDocument(); doc.LoadXml(publicKey); BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText)); BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText)); RsaKeyParameters pub = new RsaKeyParameters(false, m, p); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub); byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded(); return Convert.ToBase64String(serializedPublicBytes); } ``` 3、然后java怎么利用我转换成PEM格式的公钥密钥进行加密和解密,使得跟.NET的一样?

openssl 使用BIO进行加密的疑问

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/evp.h> #include <openssl/aes.h> #include <openssl/bio.h> int main(void) { BIO *bc = NULL, *b = NULL; char userkey[EVP_MAX_KEY_LENGTH]; char iv[EVP_MAX_IV_LENGTH]; unsigned char *date = malloc(AES_BLOCK_SIZE*3); unsigned char *encrypt = malloc(AES_BLOCK_SIZE*6); unsigned char *plain = malloc(AES_BLOCK_SIZE*6); int ret; int len = 0; memset((void*)userkey, 'k', EVP_MAX_KEY_LENGTH); memset((void*)iv, 'i', EVP_MAX_IV_LENGTH); memset((void*)date, 'p', AES_BLOCK_SIZE*3); memset((void*)encrypt, 0, AES_BLOCK_SIZE*6); memset((void*)plain, 0, AES_BLOCK_SIZE*6); bc = BIO_new(BIO_f_cipher()); BIO_set_cipher(bc,EVP_aes_256_ecb(), userkey, iv, 1); b = BIO_new(BIO_s_null()); b = BIO_push(bc,b); len = BIO_write(b, date, AES_BLOCK_SIZE*3); printf("result: %d\n",BIO_get_cipher_status(b)); BIO_flush(b); printf("write len: %d\n", len); len = BIO_read(b, encrypt, AES_BLOCK_SIZE*6); printf("result: %d\n",BIO_get_cipher_status(b)); printf("read len: %d\n", len); BIO_free(b); return 0; } 想使用BIO的方式使用EVP_aes_256_ecb()对数据进行加密,但是结果打印如下 result: 1 write len: 48 result: 1 read len: 16 在不使用padding的情况下,加密前后数据应该相等,为什么我read的结果是16,不是48呢? 对BIO使用不熟悉,是不是BIO使用的方式不对,请各位大大帮忙解决 系统是ubuntu 12.04

使用golang解密使用php openssl_encrypt加密的文件

<div class="post-text" itemprop="text"> <p>First of all. I'm on thin ice here!</p> <p>I have a encrypted file that I get from php. I'm trying to decrypt this with golang. </p> <p>The php application uses a public RSA key to encrypt the key used to encrypt with aes-256-cbc.</p> <p>I've created some proof of concept code, but I can't get it right. Even though key and iv look correct on both sides there is something that is not. The result is just garbage. I'm suspecting either some encoding mismatch (expecting base64, getting string bytes...something) or that I've misunderstood some concept.</p> <p>Encrypting:</p> <pre><code>&lt;?php $cipher = "AES-256-CBC"; $ivLength = openssl_cipher_iv_length($cipher="AES-256-CBC"); echo "iv len: " . $ivLength . " "; $iv = openssl_random_pseudo_bytes($ivLength); $key = "1234567890abcdef"; $ciphertext = openssl_encrypt("hello world", $cipher, $key, 0, $iv); $publicKey = openssl_pkey_get_public(file_get_contents("some-public-key.pub")); if (!$publicKey) { die("OpenSSL: Unable to get public key for encryption. Is the location correct? Does this key require a password?"); } $ok = openssl_public_encrypt($key, $encryptedKey, $publicKey); if (!$ok) { die("Encryption failed. Ensure you are using a PUBLIC key."); } echo "key unencrypted: " . $key . " "; echo "iv: " . base64_encode($iv) . " "; echo "ciphertext: " . $ciphertext . " "; echo "ciphertext binary: " . (base64_decode($ciphertext)) . " "; echo "combined: " . ($iv . $ciphertext) . " "; file_put_contents("key.enc", $encryptedKey); file_put_contents("content.enc", $iv . $ciphertext); file_put_contents("content.dec", openssl_decrypt($ciphertext, $cipher, $key, 0, $iv)); openssl_free_key($publicKey); ?&gt; </code></pre> <p>Decrypting:</p> <pre><code>package main import ( "crypto/aes" "crypto/cipher" "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/base64" "encoding/hex" "encoding/pem" "fmt" "io" "io/ioutil" "log" ) func main() { // Read the input file in, err := ioutil.ReadFile("key.enc") if err != nil { log.Fatalf("input file: %s", err) } // Read the private key pemData, err := ioutil.ReadFile("some-private-key") if err != nil { log.Fatalf("read key file: %s", err) } // Extract the PEM-encoded data block block, _ := pem.Decode(pemData) if block == nil { log.Fatalf("bad key data: %s", "not PEM-encoded") } if got, want := block.Type, "RSA PRIVATE KEY"; got != want { log.Fatalf("unknown key type %q, want %q", got, want) } // Decode the RSA private key priv, err := x509.ParsePKCS1PrivateKey(block.Bytes) if err != nil { log.Fatalf("bad private key: %s", err) } // Decrypt the data cipherKey, err := rsa.DecryptPKCS1v15(rand.Reader, priv, in) if err != nil { log.Fatalf("decrypt: %s", err) } fmt.Println("Key decrypted:", string(cipherKey)) // Read encrypted content file content, err := ioutil.ReadFile("content.enc") if err != nil { log.Fatalf("input file: %s", err) } fmt.Println("Cipherkey: ", string(cipherKey)) cipherText := content cipherBlock, err := aes.NewCipher(cipherKey) if err != nil { panic(err) } iv := cipherText[:aes.BlockSize] fmt.Println("iv:", base64.StdEncoding.EncodeToString(iv)) fmt.Println("ciphertext:", string(cipherText[aes.BlockSize:])) cipherText, _ = base64.StdEncoding.DecodeString(string(cipherText[aes.BlockSize:])) fmt.Println("ciphertext binary: ", string(cipherText)) // CBC mode always works in whole blocks. if len(cipherText)%aes.BlockSize != 0 { panic(fmt.Sprintf("ciphertext (len=%d) is not a multiple of the block size (%d)", len(cipherText), aes.BlockSize)) } mode := cipher.NewCBCDecrypter(cipherBlock, iv) mode.CryptBlocks(cipherText, cipherText) fmt.Printf("The result: %s ", cipherText) } </code></pre> <p>Here's some example output from executing this (first php, then go):</p> <pre><code>iv len: 16 key unencrypted: 1234567890abcdef iv: QffXbVRuwyopwwvQXQ8N6g== ciphertext: Wk8Gv1xQWikp1YryQiywgQ== ciphertext binary: ZO�\PZ))Պ�B,�� combined: A��mTn�*)� �Wk8Gv1xQWikp1YryQiywgQ== ----- Key decrypted: 1234567890abcdef Cipherkey: 1234567890abcdef iv: QffXbVRuwyopwwvQXQ8N6g== ciphertext: Wk8Gv1xQWikp1YryQiywgQ== ciphertext binary: ZO�\PZ))Պ�B,�� The result: ��2��J���~A�D </code></pre> </div>

前端jsencrypt加密,后端无法解密

## 前后端RSA加密 > 在做一个web安全登录的作业时,遇到前后端RSA加密问题。。 1. 后端 java 生成RSA密钥对,privateKey,publicKey 后端RSA是从帖子上抄的: (学习加密四spring boot 使用RSA+AES混合加密,前后端传递参数加解密)[https://blog.csdn.net/baidu_38990811/article/details/83540404] **使用PKCS8规范** ``` // 后端部分代码 RSA /** * 生成密钥对(公钥和私钥) * @return * @throws Exception */ public static Map<String, Object> genKeyPair() throws Exception { KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); keyPairGen.initialize(INITIALIZE_LENGTH); KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); Map<String, Object> keyMap = new HashMap<String, Object>(2); keyMap.put(PUBLIC_KEY, publicKey); keyMap.put(PRIVATE_KEY, privateKey); return keyMap; } /** * 私钥解密 * @param encryptedData 已加密数据 * @param privateKey 私钥(BASE64编码) * @return * @throws Exception */ public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception { byte[] keyBytes = Base64.decodeBase64(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key privateK = keyFactory.generatePrivate(pkcs8KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, privateK); int inputLen = encryptedData.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 对数据分段解密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } byte[] decryptedData = out.toByteArray(); out.close(); return decryptedData; } ``` 2. 前端:vue+webpack - 从后端获取一个公钥**publicKey** - 使用jsencrypt 和 **publicKey**加密内容,得到String encrypted 3. 后端拿到传回的encrypted, 再解密时报错 ``` javax.crypto.BadPaddingException: Decryption error at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:383) at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:294) at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:363) at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389) at javax.crypto.Cipher.doFinal(Cipher.java:2222) at com.security.loginserver.Util.RSAUtils.decryptByPrivateKey(RSAUtils.java:126) at com.security.loginserver.Util.RSAUtils.decryptDataOnJava(RSAUtils.java:285) ``` ## 测试情况 1. 后端单独测试RSA加密解密,正常 2. 前端单独测试RSA加密解密,使用后端的publicKey和privatekey正常 3. 搜到的贴子说,原因是JSEncrypt使用pkcs1规范,后端java用了**PKCS8规范**,,,然后就无从下手了 4. 求助大佬

C#实现RSA签名,签名算法采用SHA-256,JAVA部分已有,因需要转为C#代码,望大神出手相助

package test; import java.math.BigInteger; import java.security.KeyFactory; import java.security.MessageDigest; import java.security.PrivateKey; import java.security.Signature; import java.security.spec.RSAPrivateKeySpec; import java.util.Calendar; import java.util.Date; public class test { public static void main(String[] args) throws Exception { String msg = "0|20140411|1\n银联基金交易账号|用户在基金公司的账号|申请日期|银联订单号|确认日期|基金公司确认编号|返回码|失败原因\n1040000000371674|20000015|20140410|20120528990000120140410000000120|20140411|2250000000016|0000|\n"; byte[] data = msg.getBytes("UTF-8"); // 私钥 BigInteger modulus = new BigInteger("00af9133ade333df8b9aabd776334d0d8f5d96597fe2041fff716185305934cc7a386ab451f28156730ce8a76adcf9bf93ffc87fa47c0d60c4652f1700f50304997a20563cc854f1f84c921f9b1f72d0d3e989d4b22669014859135e89ced24bbac3af1d1a4a76ff5736f81fdc461d2f96cebc5f36eacae7981e7ea59443448fa1", 16); BigInteger privateExponent = new BigInteger("009c46140920e6c881bc405f7e1ff5e32f0cafcaa4912af8cc6840d4cc0f6b76e3079abb3d022dec246686249773707efd9ebcfa19102edc46948650e49232888116e4b54fe77b6eaf5061db4f50c89646241559f602d477efb0d6b755a67a40e978753f56d16142660c47bc91408cf01deaaf3f30180050e2730980e9498cdd3d", 16); RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(modulus, privateExponent); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec); //用SHA-256做摘要 MessageDigest md= MessageDigest.getInstance("SHA-256"); data=md.digest(data); // 签名 Signature instance = Signature.getInstance("SHA1withRSA"); instance.initSign(privateKey); instance.update(data); byte[] sing = instance.sign(); System.out.println(byteArr2HexString(sing)); } // 以下为调用到的公共方法 public static String byteArr2HexString(byte[] bytearr) { if (bytearr == null) { return "null"; } StringBuffer sb = new StringBuffer(); for (int k = 0; k < bytearr.length; k++) { if ((bytearr[k] & 0xFF) < 16) { sb.append("0"); } sb.append(Integer.toString(bytearr[k] & 0xFF, 16)); } return sb.toString(); } }

python 关于 OpenSSL.crypto 模块验签问题

对接一个接口,在数据发送与接收时需要rsa签名和验签。 采用 OpenSSL.crypto 模块进行签名 签名的主要部分是: ``` from OpenSSL.crypto import load_privatekey,FILETYPE_PEM,sign,verify def tosign(data,private_key): key = load_privatekey(FILETYPE_PEM, private_key) return base64.b64encode(sign(key,data,'sha1')) def verysign(data,getsign,public_key): sign = base64.b64decode(getsign) key = load_certificate(FILETYPE_PEM,public_key) ret = verify(key,sign,data,'sha1') return ret ``` 密钥是”BEGIN RSA PRIVATE KEY --- END RSA PRIVATE KEY” 公钥是 “ BEGIN PUBLIC KEY --- END PUBLIC KEY” 签名是没有问题的,但是验签会报错:[('PEM routines', 'PEM_read_bio', 'no start line')] 对一些加密解密加签的本来就不熟,在 google 后更加蒙蔽了,所以想请问各位大佬指出一下问题,给个解决方案或者一点建议

如何解密用JSEncrypt加密的PHP中的数据

<div class="post-text" itemprop="text"> <p>I'm trying to secure communication between a JS front-end and a PHP backend by using symmetric and asymmetric encryption. I'm creating a symmetric key on the client and encrypting it with the server's public key with JSEncrypt and sending it to the server for future use. However, I'm getting stuck when I get the data on the server side. openssl_open requires an envelope to decrypt the symmetric key and I'm not even positive what data is supposed to be in the envelope. I was under the impression that the envelope is the symmetric key that was encrypted with the public key, but using that has not worked. I've also tried different combinations of decoding as I've read that JSEncrypt encodes the message in base 64 and the key in hex, but those attempts are fruitless as well.</p> <p><b>JS encryption code:</b></p> <pre><code>let pub = "-----BEGIN PUBLIC KEY-----...-----END PUBLIC KEY-----"; //I have a function that just creates a random string of characters let key = generateKey(32); let aesData = CryptoJS.AES.encrypt( "test", key ); let symKey = aesData.key + ":::" + aesData.iv; let msg = aesData.toString(); let rsa = new JSEncrypt(); rsa.setPublicKey( pub ); let cryptKey = rsa.encrypt( symKey ); //I'm passing the data through a hidden form field $("#key").val(cryptKey + ":::" + msg); </code></pre> <p><b>PHP decryption code:</b></p> <pre><code>$key = openssl_get_privatekey( file_get_contents( $_SERVER["PRIV_KEY"]) ); $encryptedKey = explode( ":::", $msg )[0]; $realMsg = base64_decode(explode( ":::", $msg )[1]); openssl_open($realMsg, $decrypted, $encryptedKey, $key); return $decrypted; </code></pre> <p>The code above outputs nothing because the openssl_open call fails (returns false). When I base 64 decode the $encryptedKey variable, I get:</p> <pre><code>�vEi���pΕ��d_���@����욲JE�� </code></pre> <p>but the symmetric key changes every time, so the output changes every time as well. Like I said, I've tried different encoding combinations, but they all return similar nonsense. As the JS code shows, I've encrypted the message "test".</p> <p>I've never implemented encryption before, so I might be way off the mark here, but after staring at this code for days, any insight would be appreciated.</p> <p>Edit: I'm having problems decrypting with my private key in PHP, not with the symmetric key</p> </div>

使用c#中的公钥加密数据,并使用php中的私钥解密数据

<div class="post-text" itemprop="text"> <p>I'm trying to encrypt a JSON string in C# en decrypt it in PHP by using OpenSSL RSA.</p> <p>The following code is in C#:</p> <pre><code>public static string EncryptData(string data) { string key = @"-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC/J/txQvYBm5iOHRRRtgdXd5hq DEavxy5OExSiwjJgOgT72A9GX7+E7QYfhUZJTGtf+/J84tuJPx6/Ff1dZa1XRW84 /n5m7fw93CTVwpfRFi0Owenor44zgk6ABSfMlCzwGfdcS8AFiWCFUBpatKte6PaO /WfYK7qz/5faSp3FawIDAQAB -----END PUBLIC KEY-----"; OpenSSL.Crypto.CryptoKey pKey = OpenSSL.Crypto.CryptoKey.FromPublicKey(key, null); OpenSSL.Crypto.RSA rsa = pKey.GetRSA(); byte[] encryptedData = rsa.PublicEncrypt (Encoding.UTF8.GetBytes(data), OpenSSL.Crypto.RSA.Padding.PKCS1); rsa.Dispose(); return Convert.ToBase64String (encryptedData); } </code></pre> <p>then I send the encoded <code>encryptedData</code> to PHP and put it into the <code>PrivateKeyDecrypt</code> function.</p> <p>Code in PHP:</p> <pre><code>&lt;?php // include the lib //require_once('OpenSSL.php'); $ssl = new OpenSSL(); $ssl-&gt;loadPrivateKeyWithoutPath('-----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQC+wVuIECnd7dvt7yqoElg4DL8jSKFpUavKfviSBE2Z+5z5YWnf i4mp/r0P0jVbE+dfqReaIr4UOt//hPvwvioAJ576KPOCTYZiIGehkqafGWS+01wH nAPSj/C7Xt7F9Mh5McH4CnBR5VN93KKZtQtfNsNPPBdXwQuquONOUgUgTwIDAQAB AoGAIQkvpvLVrV/CVQS0qIL00FA00hGEEs9YJyuyNOeV4PMYjn/2bAaogs5hQ9ot 72YVDhYkxkb6EFrZ7FDFqT3l2/BpQEsJ6/GQq2gX0rYGfJ5sWrN+KIuSJr4FWSN+ LrvIEr35hKHY6mytiQg9D58b5kSjaB9ea/qhh/hJL2VfWGECQQDlBBJsccR2ZzzH QN5omwFrUuxnqraY5LyZB8xUnqo9iDULO+GTcW/5eO9TBoWuDf1Ul3Snts9Tb+uD UYL1y5onAkEA1Ts182anQHCjUtp2hooLjDcOvIK3gi5TchqHW6T4K3tNtnbfOB9P gMNgcKljjXlQXl3ornvLTYBC483MS4RpmQJAZMiS9whmBhlOpP1GI1C7oih/Auwc qVJYMRw+bqrYjnWnqkby8XkFZwsyfx4qrDtZ1eVFIB2SRczGHyc688JjFwJBAIxa lx6J2VlfSwIEbrQMNaGrs/V9jVERMTgQIjy+j+P/G54ZDMEiSvCUqew+cxryWWZk Jf6D2cQ/wsez9N9YXzECQQDMH6jS9vp7aabI2UKy5RhTqvP6kRmi28/GHb/8QrFx tldiw2THvc4+4QT9tuv5OA6xRnEO5mt5u3vFHciqeRR7 -----END RSA PRIVATE KEY-----'); public function PrivateKeyDecrypt($raw_data, $base64 = TRUE) { if ($this-&gt;privateKey == NULL) trigger_error("Private key has not been specified.", E_USER_ERROR); if (!openssl_private_decrypt(($base64) ? base64_decode($raw_data) : $raw_data, $decrypted_data, $this-&gt;privateKey, $this-&gt;padding)) trigger_error("Unable to decrypt data.", E_USER_ERROR); return $decrypted_data; } </code></pre> <p>The error I get when I call the <code>PrivateKeyDecrypt</code> function is: </p> <pre><code>FATAL ERROR: unable to decrypt data in ... </code></pre> <p>Does anyone have any idea what causes this error? </p> </div>

Apache Modulue开发中遇到的问题,关于openssl加密,总是报错,错在哪里?

char *iaisession_getobmuid(request_rec *r, const char *encid, const unsigned char *enckey, unsigned char *iv, const char *mtiid) { unsigned char *obmuid = (unsigned char *) apr_pcalloc(r->pool, LENGTH_OBMUID + 1); char *b64edobmuid; // get muid length int mtiidlen = strlen(mtiid); // encrypted obmuid length int obmuidlen = 0; // padding length int paddinglen = 0; // according to the key length, decide 128bit or 256bit AES encryption algorithm. const EVP_CIPHER *aes_cbc = NULL; int keylen = strlen((char *)enckey); if (keylen == LENGTH_KEY_16) { aes_cbc = EVP_aes_128_cbc(); } else if (keylen == LENGTH_KEY_32) { aes_cbc = EVP_aes_256_cbc(); } // cipher contex EVP_CIPHER_CTX ctx; // initializes cipher contex. EVP_CIPHER_CTX_init(&ctx); // sets up cipher context ctx for encryption with cipher type from ENGINE (default implementation). EVP_EncryptInit_ex(&ctx, aes_cbc, NULL, enckey, iv); // encrypts mtiidlen bytes from the mtiid in and writes the encrypted version to obmuid. EVP_EncryptUpdate(&ctx, obmuid, &obmuidlen, (unsigned char *)mtiid, mtiidlen); // obmuid is the encrypts. EVP_EncryptFinal_ex(&ctx, obmuid + obmuidlen, &paddinglen); // clears all information from a cipher context and free up any allocated memory associate with it. EVP_CIPHER_CTX_cleanup(&ctx); // base64 encode b64edobmuid = iaisession_encodebybase64(r->pool, obmuid); return b64edobmuid; } [Wed Jul 03 01:43:13 2013] [notice] child pid 28278 exit signal Segmentation fault (11)

在php中使用公钥加密后,如何使用私钥解密c#中的数据块?

<div class="post-text" itemprop="text"> <p>How do I decrypt the output of this code using the private key (pem format) in C# ? </p> <pre><code>$output = json_encode(array('see'=&gt;'me')); define('CIPHER_BLOCK_SIZE', 100); $encrypted = ''; $key = file_get_contents('public.txt'); $chunks = str_split($output, CIPHER_BLOCK_SIZE); foreach($chunks as $chunk) { $chunkEncrypted = ''; $valid = openssl_public_encrypt($chunk, $chunkEncrypted, $key, OPENSSL_PKCS1_PADDING); if($valid === false){ $encrypted = ''; break; //also you can return and error. If too big this will be false } else { $encrypted .= $chunkEncrypted; } } $output = base64_encode($encrypted); //encoding the whole binary String as MIME base 64 echo $output; </code></pre> <p><a href="http://pastebin.com/6Q2Zb3j6" rel="nofollow noreferrer">Click here for a large json sample ready formatted</a> to replace the following line in the above sample, to test chunking, as the <code>$output</code> json above is too small for chunking to take effect.</p> <pre><code>$output = json_encode(array('see'=&gt;'me')); </code></pre> <h2>Explanation of what the code above does</h2> <p>The above code is a modification of <a href="http://php.net/manual/en/function.openssl-private-encrypt.php#119810" rel="nofollow noreferrer">this solution</a> which breaks the data into smaller chunks (100 bytes per chunk) and encrypts them using a public key in pem format.</p> <h2>Objective</h2> <p>I am looking at encrypting larger than a few bytes for more secure transit of data, and found that encrypting/decrypting using certificates is the best route to go.</p> <p>The intent is to encrypt data in php (using the private key) which would then be received in an application written in C# and decrypted (using the public key).</p> <h2>C# - The road so far</h2> <hr> <h2>Following is my attempt at decrypting in c# :</h2> <p>Usage :</p> <pre><code>// location of private certificate string key = @"C:\path\to\private.txt"; // output from php script (encrypted) string encrypted = "Bdm4s7aw.....Pvlzg="; // decrypt and store decrypted string string decrypted = crypt.decrypt( encrypted, key ); </code></pre> <p>Class :</p> <pre><code>public static string decrypt(string encrypted, string privateKey) { try { RSACryptoServiceProvider rsa = DecodePrivateKeyInfo( DecodePkcs8PrivateKey( File.ReadAllText( privateKey ) ) ); return Encoding.UTF8.GetString( rsa.Decrypt( Convert.FromBase64String( encrypted ), false ) ); } catch (CryptographicException ce) { return ce.Message; } catch (FormatException fe) { return fe.Message; } catch (IOException ie) { return ie.Message; } catch (Exception e) { return e.Message; } } </code></pre> <h2>The other methods this depends on (harvested from <a href="http://www.jensign.com/opensslkey/opensslkey.cs" rel="nofollow noreferrer">opensslkey.cs</a> )</h2> <pre><code>//-------- Get the binary PKCS #8 PRIVATE key -------- private static byte[] DecodePkcs8PrivateKey( string instr ) { const string pemp8header = "-----BEGIN PRIVATE KEY-----"; const string pemp8footer = "-----END PRIVATE KEY-----"; string pemstr = instr.Trim(); byte[] binkey; if ( !pemstr.StartsWith( pemp8header ) || !pemstr.EndsWith( pemp8footer ) ) return null; StringBuilder sb = new StringBuilder( pemstr ); sb.Replace( pemp8header, "" ); //remove headers/footers, if present sb.Replace( pemp8footer, "" ); string pubstr = sb.ToString().Trim(); //get string after removing leading/trailing whitespace try { binkey = Convert.FromBase64String( pubstr ); } catch ( FormatException ) { //if can't b64 decode, data is not valid return null; } return binkey; } //------- Parses binary asn.1 PKCS #8 PrivateKeyInfo; returns RSACryptoServiceProvider --- private static RSACryptoServiceProvider DecodePrivateKeyInfo( byte[] pkcs8 ) { // encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1" // this byte[] includes the sequence byte and terminal encoded null byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 }; byte[] seq = new byte[15]; // --------- Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob ------ 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(); } } //------- Parses binary ans.1 RSA private key; returns RSACryptoServiceProvider --- 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; } 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; } </code></pre> <p>This is all functional now, however it still doesn't incorporate chunking in the decryption process. </p> <p><em>What must I do to read these blocks in, as larger files will definitely be larger than the original unencrypted data.</em></p> <p>My previous attempt was to try something like the following code, but this seems flawed as it is always padding 100 bytes (even when the total bytes are less), and the base64 decoding of the <code>json_encode(array('see'=&gt;'me'))</code> using my current public key for encrypting ends up being 512 bytes.</p> <pre><code> byte[] buffer = new byte[100]; // the number of bytes to decrypt at a time int bytesReadTotal = 0; int bytesRead = 0; string decrypted = ""; byte[] decryptedBytes; using ( Stream stream = new MemoryStream( data ) ) { while ( ( bytesRead = await stream.ReadAsync( buffer, bytesReadTotal, 100 ) ) &gt; 0 ) { decryptedBytes = rsa.Decrypt( buffer, false ); bytesReadTotal = bytesReadTotal + bytesRead; decrypted = decrypted + Encoding.UTF8.GetString( decryptedBytes ); } } return decrypted; </code></pre> <p>For your convenience, I put up a php script to <a href="https://www.tehplayground.com/tewUt9MmPsB7oiUZ" rel="nofollow noreferrer">generate a public and private key to test with</a> on <strong>tehplayground.com</strong>.</p> </div>

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

搜狗输入法也在挑战国人的智商!

故事总是一个接着一个到来...上周写完《鲁大师已经彻底沦为一款垃圾流氓软件!》这篇文章之后,鲁大师的市场工作人员就找到了我,希望把这篇文章删除掉。经过一番沟通我先把这篇文章从公号中删除了...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

2020阿里全球数学大赛:3万名高手、4道题、2天2夜未交卷

阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

程序员为什么千万不要瞎努力?

本文作者用对比非常鲜明的两个开发团队的故事,讲解了敏捷开发之道 —— 如果你的团队缺乏统一标准的环境,那么即使勤劳努力,不仅会极其耗时而且成果甚微,使用...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发(16k)

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

《Oracle Java SE编程自学与面试指南》最佳学习路线图2020年最新版(进大厂必备)

正确选择比瞎努力更重要!

《Oracle Java SE编程自学与面试指南》最佳学习路线图(2020最新版)

正确选择比瞎努力更重要!

都前后端分离了,咱就别做页面跳转了!统统 JSON 交互

文章目录1. 无状态登录1.1 什么是有状态1.2 什么是无状态1.3 如何实现无状态1.4 各自优缺点2. 登录交互2.1 前后端分离的数据交互2.2 登录成功2.3 登录失败3. 未认证处理方案4. 注销登录 这是本系列的第四篇,有小伙伴找不到之前文章,松哥给大家列一个索引出来: 挖一个大坑,Spring Security 开搞! 松哥手把手带你入门 Spring Security,别再问密...

字节跳动面试官竟然问了我JDBC?

轻松等回家通知

面试官:你连SSO都不懂,就别来面试了

大厂竟然要考我SSO,卧槽。

阿里面试官让我用Zk(Zookeeper)实现分布式锁

他可能没想到,我当场手写出来了

终于,月薪过5万了!

来看几个问题想不想月薪超过5万?想不想进入公司架构组?想不想成为项目组的负责人?想不想成为spring的高手,超越99%的对手?那么本文内容是你必须要掌握的。本文主要详解bean的生命...

自从喜欢上了B站这12个UP主,我越来越觉得自己是个废柴了!

不怕告诉你,我自从喜欢上了这12个UP主,哔哩哔哩成为了我手机上最耗电的软件,几乎每天都会看,可是吧,看的越多,我就越觉得自己是个废柴,唉,老天不公啊,不信你看看…… 间接性踌躇满志,持续性混吃等死,都是因为你们……但是,自己的学习力在慢慢变强,这是不容忽视的,推荐给你们! 都说B站是个宝,可是有人不会挖啊,没事,今天咱挖好的送你一箩筐,首先啊,我在B站上最喜欢看这个家伙的视频了,为啥 ,咱撇...

代码注释如此沙雕,会玩还是你们程序员!

某站后端代码被“开源”,同时刷遍全网的,还有代码里的那些神注释。 我们这才知道,原来程序员个个都是段子手;这么多年来,我们也走过了他们的无数套路… 首先,产品经理,是永远永远吐槽不完的!网友的评论也非常扎心,说看这些代码就像在阅读程序员的日记,每一页都写满了对产品经理的恨。 然后,也要发出直击灵魂的质问:你是尊贵的付费大会员吗? 这不禁让人想起之前某音乐app的穷逼Vip,果然,穷逼在哪里都是...

2020春招面试了10多家大厂,我把问烂了的数据库事务知识点总结了一下

2020年截止目前,我面试了阿里巴巴、腾讯、美团、拼多多、京东、快手等互联网大厂。我发现数据库事务在面试中出现的次数非常多。

爬虫(101)爬点重口味的

小弟最近在学校无聊的很哪,浏览网页突然看到一张图片,都快流鼻血。。。然后小弟冥思苦想,得干一点有趣的事情python 爬虫库安装https://s.taobao.com/api?_ks...

在拼多多上班,是一种什么样的体验?我心态崩了呀!

之前有很多读者咨询我:武哥,在拼多多上班是一种什么样的体验?由于一直很忙,没抽出时间来和大家分享。上周末特地花点时间来写了一篇文章,跟大家分享一下拼多多的日常。 1. 倒时差的作息 可能很多小伙伴都听说了,拼多多加班很严重。这怎么说呢?作息上确实和其他公司有点区别,大家知道 996,那么自然也就能理解拼多多的“11 11 6”了。 所以当很多小伙伴早上出门时,他们是这样的: 我们是这样的: 当...

应聘3万的职位,有必要这么刁难我么。。。沙雕。。。

又一次被面试官带到坑里面了。面试官:springmvc用过么?我:用过啊,经常用呢面试官:springmvc中为什么需要用父子容器?我:嗯。。。没听明白你说的什么。面试官:就是contr...

立即提问
相关内容推荐