I need to call authentication uses the hmac-sha512 algorithm. Message to be encrypted using the key (for example: vU372pd8pS4AN2XEzt2aQn6CRq6dT5) is:  "entityReference=3000001222&amp;caseReference=SilviaTemplate1&amp;type=16&amp;name=example_WS2.jpg&amp;content=[binary]".  My code:  public string ChecksumCalc(string entityReference, string caseReference, string type,string name, byte[] content, string key)     {         string message = "entityReference=" + entityReference + "&amp;caseReference=" + caseReference + "&amp;type=" + type + "&amp;name=" + name + "&amp;content=" + BitConverter.ToString(content).Replace("-",string.Empty).ToLower();          string checksum = "";         try         {             var encoding = new System.Text.ASCIIEncoding();             byte[] keyByte = encoding.GetBytes(key);             byte[] messageBytes = encoding.GetBytes(message);              using (var hmacsha512 = new HMACSHA512(keyByte))             {                 byte[] hashmessage = hmacsha512.ComputeHash(messageBytes);                 //First method                 checksum = BitConverter.ToString(hashmessage).Replace("+", "").Replace("/", "").Replace("=", "").Replace("-", "").ToLower();                  //Second method                 StringBuilder hex = new StringBuilder(hashmessage.Length * 2);                 foreach (byte b in hashmessage)                     hex.AppendFormat("{0:x2}", b);                 checksum = hex.ToString();                  //Same result             }              Console.WriteLine(checksum);         }         catch (Exception ex)         {             log.Error("Error on checksumCalc. Exception: " + ex.Message);             throw ex;         }          return checksum;     }   I commented my other attempts solve my issue, but it doesn't works.
2031
How can you convert a byte array to a hexadecimal string, and vice versa?
108285
Background info: I am planning on making a filehost with which one can encrypt and upload files. To protect the data against any form of hacking, I'd like not to know the encryption key ($K$) used for a file, so the user will have to asymmetrically encrypt $K$ and send it as well. The reason for this double encryption is that you can still share (individual!) files with other accounts by encrypting $K$ with the public keys of those users, too.  My problem is: How can a user can get a public and private key without the server saving/knowing the private key and without the user having to remember a passphrase of 250 hex characters?  Question: Is there a way to derive a key pair from a password, like PBKDF-2 does for symmetric encryption? Suggestions on rearranging the cryptographic steps in an easier way are welcome, too.  Alternatively: It is also possible to encrypt the private key with a PBKDF-applied password and store it on the server, but I'd like to keep things 'simple'. ;)  Note: At this point I don't care if it requires RSA, ECC or an obscure cryptography scheme.
63877
I can't seem to find a nice clean example of using AES 128 bit encryption.  Does anyone have some sample code?
80839
Let's say we want to sign message $M$ with RSA using a safe hash function. However, instead of signing $\operatorname{hash}(M)$, We split the message into 64-bit blocks (|| is concatenation):  $$M = {m_0}||{m_1}||{m_2}||{m_3}\,...$$  For each block we calculate:  $${h_i} = \operatorname{hash}({m_i}||i)$$  and then we calculate the total hash:  $$h = {h_1} \oplus {h_2} \oplus {h_3}\,...$$  and sign $h$ with RSA instead of $\operatorname{hash}(M)$.  Why is it weaker than signing $\operatorname{hash}(M)$?  I know that the order of the blocks cannot be modified because of the concatenation of $i$, and that I cannot add the same block twice because of that too.  I think the answer involves collision, birthday or brute-force attack which may be faster than performing those attacks against $\operatorname{hash}(M)$ but couldn't show that. Any ideas?  P.S: Homework question - hint is enough :)
25659
RSA is not designed to be used on long blocks of plaintext like a block cipher, but I need to use it to send a large (encrypted) message.  How can I do this?
40547
I'm developing a messenger application with encrypted chats.   In the first version of the app I've used PBKDF2 (10000 iterations, SHA1, random salt) to extend a short user password and generate keys to encrypt (AES256) and sign message (HMAC).  In the current version of the app I generate a random 130-bit key and use it instead of a user password. I think that using PBKDF2 with such a key has some overhead.   I see 2 possible ways to improve the current approach:   Keep using PBKDF2 and decrease iterations to 1 or 10. Don't use PBKDF2 and use HKDF instead.   What are the advantages and disadvantages of each approach? Are there any other options?
74026
How do I calculate the CRC32 (Cyclic Redundancy Checksum) of a string in .NET?
7126
I have a need to encrypt credentials for a third-party app used by a secured internal app. Over on ITSec.SE, I was helpfully shown a scheme to encrypt the third-party credentials based on a hash of the credentials for the internal app.   I picked AES as the encryption algorithm, but the problem is that the password-based scheme doesn't produce a "secret" IV. So, the IV must at least be known to an attacker (stored alongside the encrypted data). A hash value used for password verification could work, or I could just generate a pseudorandom byte array and drop it in the DB as a new column. I was further considering, for simplicity, to use a constant IV.   What adverse effect will either of these choices have on the security of the encryption? Does AES depend, as many block ciphers do, on an unpredictable IV? Does it matter if the IV is stored as unencrypted plaintext?
94927
I tried to execute some code in a sandbox and I got an odd error message:     System.UnexpectedException: Invalid parameter value '****' for   parameter "Decryption Exception".    Looks like it happened immediately following a callout attempt...
105086
The private key is any random 256 bit (but smaller than prime p) number or must be prime or other condition? For selected $x$ can be found $y$ - decompressing key: #! /usr/bin/env python3 import binascii import math p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F def decompress_pubkey(pk):     x = int.from_bytes(pk[1:33], byteorder='big')     y_sq = (pow(x, 3, p) + 7) % p     y = pow(y_sq, (p + 1) // 4, p)     if y % 2 != pk[0] % 2:         y = p - y     y = y.to_bytes(32, byteorder='big')     return b'\x04' + pk[1:33] + y  print(binascii.hexlify(decompress_pubkey(binascii.unhexlify('0229b3e0919adc41a316aad4f41444d9bf3a9b639550f2aa735676ffff25ba3898'))).decode()) print(binascii.hexlify(decompress_pubkey(binascii.unhexlify('02f15446771c5c585dd25d8d62df5195b77799aa8eac2f2196c54b73ca05f72f27'))).decode()) print(binascii.hexlify(decompress_pubkey(binascii.unhexlify('0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'))).decode())  Only last x,y pair fulfill (x3+7-y2) % p is zero. Two previous pairs are wrong?
8839
Given a message and DES encrypted form of said message, is it possible to efficiently compute the key used to encrypt the data?
92138
The previous SF questions I've seen have lead to answers that produce MD5 hashed password.  Does anyone have a suggestion on to produce an SHA-512 hashed password? I'd prefer a one liner instead of a script but, if a script is the only solution, that's fine as well.  Update  Replacing previous py2 versions with this one:  python3 -c "import crypt;print(crypt.crypt(input('clear-text pw: '), crypt.mksalt(crypt.METHOD_SHA512)))"
65747
I'm running a REST API which is returning the below:  "id" : "fdgsdgsdsdgsdg",    "pageevents" : [ {        "name" : "test",        "number" : "0123442",        "homepage" : "www.test.com"     } ],     "goals" : [ {        "name" : "test",        "number" : "0123442",        "homepage" : "www.test.com"     } ] } ]   Im using the below code to de-serialize it, so i can display it as a pageblocktable on a visualforce page however im getting the error :      System.JSONException: Illegal value for primitive   public List&lt;maMoments&gt; getMomentsActivity() {     Id contactId;     if (contactId == null) {         contactId = '0030O00001sqXJr';     }      String contactIdString = String.valueOf(contactId);     String jsonResponse = this.AutomationDetailsMoments(contactIdString);     system.debug(jsonResponse);     List&lt;maMoments&gt; mAutomation = (List&lt;maMoments&gt;) JSON.deserialize(jsonResponse, List&lt;maMoments&gt;.class);     system.debug(mAutomation);     for(maMoments emailStructure : mAutomation){      }      return mAutomation; }  public string AutomationDetailsMoments(String contactId) {     contactId = '0030O00001sqXJr';     Http h = new Http();     HttpRequest req = new HttpRequest();     req.setEndpoint('https://virtserver.swaggerhub.com/mickjdavies/Example/1.0.0/interestingmoments');     req.setMethod('POST');     req.setBody(contactId);      // Send the request, and return a response     HttpResponse res = h.send(req);     system.debug(res.getBody());     return res.getBody(); }  private class maMoments {     public String contactId;     public String id;     public List&lt;String&gt; goals;     public String name;     public String homepage;     public String phone; }
83553
If I understand correctly SHA-3 (Keccak) is resistant against more attacks than SHA-2. This would make it possible - again if I understand correctly - to use SHA-3 with a simpler scheme than HMAC.  Would there still be a reason to use the HMAC construction with SHA-3? Would it be a better idea to simply use $H(C(k, M))$ where $H$ is simply SHA-3 and $C$ is a function to create a canonical representation (encoding) of the key $k$ and the message $M$ to set them apart?  Of course I imagine that HMAC-SHA3 will be used in the majority of protocols anyway as SHA-3 was created as a drop in replacement of SHA-2. But is there any security related reason to use HMAC-SHA3 over an (even) simpler scheme?
18034
when i try to save the following code, i got the error below. Following same instructions given in this link, but still errors. Am i doing anything wrong here? please suggest.    @isTest private class WebSvcCalloutTest {     @isTest static void testEchoString() {         Account a = new Account(name='Tester',SAP_KUNNR__c='1172');         insert a;                       // This causes a fake response to be generated         Test.setMock(WebServiceMock.class, new WebServiceMockImpl());      } }   Error:  Save error: Method does not exist or incorrect signature: Test.setMock(Type, WebServiceMockImpl)    WebSvcCalloutTest.cls         @isTest global class WebServiceMockImpl implements WebServiceMock {    global void doInvoke(            Object stub,            Object request,            Map&lt;String, Object&gt; response,            String endpoint,            String soapAction,            String requestName,            String responseNS,            String responseName,            String responseType) {          sapComDocumentSapSoapFunctionsMcS.Z_GSSMWFM_HNDL_EVNTRQST00 sap1 = new sapComDocumentSapSoapFunctionsMcS.Z_GSSMWFM_HNDL_EVNTRQST00();                Map&lt;String,String&gt; mapSAP = new Map&lt;String,String&gt; {};         sapComDocumentSapSoapFunctionsMcS.ZgssmbstDatarcrd01 req = new sapComDocumentSapSoapFunctionsMcS.ZgssmbstDatarcrd01();               sapComDocumentSapSoapFunctionsMcS.ZGssmwfmHndlEvntrqst00Response_element ret =  sap1.ZGssmwfmHndlEvntrqst00('',req);         response.put('response_x', ret);     } }
109761
I have getting the below JSON on using JSON.serialize  [ {   "lname" : "Singh",   "hcpZipCode" : null,   "hcpState" : null,   "hcpEmail" : "test@test.com",   "hcpCity" : null,   "hcpAddLine1" : null,   "fname" : "Abhey",   "countryCode" : "AUS" } ]   I don't know why this '[' is coming at the begining.I don't need this '[' at the begining due to which I am getting System.JSONException: Malformed JSON: Expected '{' at the beginning of object  code     public PageReference step2() {         string JSONstr='';        List&lt;HCPRequest&gt; conWrapList = new List&lt;HCPRequest&gt;();        HCPRequest tempcontactWrapper = new HCPRequest();        tempcontactWrapper.fname='Abhey';        tempcontactWrapper.lname='Singh';        tempcontactWrapper.countryCode='AUS';        tempcontactWrapper.hcpEmail=contact.Email;         conWrapList.add(tempcontactWrapper);          JSONstr = JSON.serializePretty(conWrapList);         System.debug('\n******'+JSONstr +'\n******');          String clientId = 'xy';         String clientSecret = 'x';          //We can also store our username password in custom setting.         String username='x';//salesforce username          String password='x';//password+securitytoken         // Generating the Access Token         HttpRequest req = new HttpRequest();         req.setMethod('POST');         req.setEndpoint('https://test.salesforce.com/services/oauth2/token');// this is the OAuth endpoint where this request will be hit         req.setBody('grant_type=password&amp;client_id='+clientId+'&amp;client_secret='+clientSecret+'&amp;username='+username+'&amp;password='+password);          Http http = new Http();         HTTPResponse res = http.send(req);         String str = res.getBody();         wrapObj = (Wrapper)Json.deserialize(str,Wrapper.class);         accessToken = wrapObj.access_token;         instanceUrl = wrapObj.instance_url;          HttpRequest req1 = new HttpRequest();         string response='';         req1.setMethod('POST');         //req.setEndpoint(wrapObj.instance_url+'/services/apexrest/Account/getAccountById?name=champaKAli');         string EndPt = 'y';         string email='test@test.com';         req1.setEndpoint(EndPt);         req1.setHeader('Authorization', 'OAuth '+wrapObj.access_token);          req1.setHeader('Content-Type', 'application/json');          //req1.setBody('{"request":{"lname" : "Singh","hcpZipCode" : null,"hcpState" : null,"hcpEmail" : "test@test.com","hcpCity" : null,"hcpAddLine1" : null,"fname" : "Abhey","countryCode" : "AUS"}}');          req1.setBody('{"request":'+JSON.Serialize(conWrapList)+'}');          //req.setBody('{"request": {"countryCode": "AUS","hcpEmail" : ""+email}}');          //req.setTimeout(60000);             //req.setHeader('Content-Length', '0');         Http http1 = new Http();         HTTPResponse res1 = http1.send(req1);          System.debug('***Response***** ' + res1.getBody());         if(res1.getBody()!=null)         {             response=res1.getBody();             HCPResponse saj=(HCPResponse)JSON.deserialize(response,HCPResponse.class);           System.debug('***Response came full***** ' + saj);            System.debug('***Response came***** ' + saj.accList);             for(HCPResponseDetail s :saj.accList)            {            System.debug('***Response email***** ' + s.hcpEmail);            System.debug('***Response add2***** ' + s.hcpAddrLine2);            contact.Address1_Line2__c=s.hcpAddrLine2;            }           //return response;         //string methodcall=methodGet(JSONstr);               return Page.opptyStep2CustomReg;         }
47155
The AEAD construction for chacha20-poly1305 described in the  encodes message lengths into the text that is to be hashed. The  goes further and pads associated data and plaintext to multiples of 16 bytes.  Can anyone explain what the purpose of that is? The chacha20-poly1305 implementation found in OpenSSH doesn't do anything like that, and as far as I can see, neither does NaCl. Those are still considered secure so I wonder what's going on.