I want to perform SHA256 hashing in a Blackberry application. Searching, I found the Bouncy Castle project has a crypto library for this, but I can't find any samples to show how to use SHA256 hashing.
Just reposting user598312's answer as a response instead of a comment, so people know the solution.
private static byte[] getSHA512(String key) {
SHA512Digest digester = new SHA512Digest();
byte[] retValue = new byte[digester.getDigestSize()];
digester.update(key.getBytes(), 0, key.length());
digester.doFinal(retValue, 0);
return retValue;
}
BlackBerry has built-in implementations of nearly everything in the BouncyCastle API. For SHA256, there is SHA256Digest.
Related
I am new to KMM, but trying to port a standard android app written in Java to KMM.
So, I have the following method:
private static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA");
keyPairGen.initialize(2048);
KeyPair pair = keyPairGen.generateKeyPair();
return pair;
}
With the keypair, I am going to sign a byte array and send the signature together with the public key to a java server, think of it as a variant of FIDO2.
Converting to Kotlin was not the problem, but then the java.security.* classes are used, which seems wrong when having in mind that there should also be an iOS variant. So my idea was to have in commonMain a function which would receive the byte array to be signed and returns an object containing the signature and the publickey for verification, in androidMain then the actual implementation for doing this with the code above - but how to do this for iosMain ? I can't figure out how to generate a keypair for signing using pure Kotlin for ios...
I am trying to access google and Twitter API for one of my Project. Both of these can give access to there API only using OAuth2.
Which is best OAuth client library available for the same?
Both API use OAuth 2 only and google deprecated the OAuth 1 support. It's always good to use latest version as it's more secure.
Update:
OAuth 2 has less round trips so it fast and quick.
You can use spring-security-oauth2. It is quite easy to implement all OAuth2RestOperations.
Create a OAuth2RestOperations bean which works almost same as RestTemplate(except for OAuth2 token handling part).
For example, if you are creating an rest call with Password credential authentication,
#Bean
public OAuth2RestOperations sampleROPCRestTemplate() {
return new OAuth2RestTemplate(sampleforcePasswordResourceDetails(), new DefaultOAuth2ClientContext(new DefaultAccessTokenRequest()));
}
#Bean
protected OAuth2ProtectedResourceDetails sampleforcePasswordResourceDetails() {
ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
resource.setAccessTokenUri(tokenUrl);
resource.setClientId(clientId);
resource.setClientSecret(clientSecret);
resource.setUsername(username);
resource.setPassword(password);
resource.setClientAuthenticationScheme(AuthenticationScheme.form);
resource.setGrantType("password");
return resource;
}
I have data that I only want to make available in three different HTTP POSTs (think of a workflow) and I don't want to use a QueryString, or a Cookie for this information. For this reason, I think the concept of _viewstate applies here.
So, how should I emulate ViewState in ASP.NET MVC as a encrypted hidden field that includes confidentiality and authentication?
Does the ASP.NET 4 or newer framework include this?
More Information
ASP.NET used an encrypted Viewstate as a hidden field in a form. One of the benefits of this is that the cryptography was "authenticated", meaning that any tampering would be detected in addition to the privacy features available in an encrypted payload.
There are many many questions on this site that discuss how to retrofit Viewstate into ASP.NET MVC, but no answers I've seen address the encryption of the data that includes these features to the serialized data:
Confidentiality (privacy)
Authentication (no modifications)
It wasn't "Classic ASP" (which is the COM-heavy, VBScript-friendly platform that was popular from 1997 to 2003) but ASP.NET WebForms which used ViewState. ViewState itself was a Base64-encoded (not encrypted) representation of the page's controls' properties. This was done because HTML Forms don't transmit additional properties back to the server, only <input>s' value="" attributes, so the ViewState included things like a control's background color property (if it was set).
In WebForms, developers could use ViewState validation MAC to ensure their viewstate data wasn't altered, but in practice it frequently broke down. If you search for "Validation of viewstate MAC failed" then you'll find countless discussions on how to workaround the issue. However that is an irrelevant point in my post.
If you want to use a client form field as a roundtrip data vector, then that's perfectly fine, just do something like the code below.
class PageViewModel {
public String SecretData;
}
public ActionResult Foo() {
Byte[] someSecretData = GetIcbmLaunchCodes();
someSecretData = ArbitraryEncryptionAlgorithm( someSecretData ); // you can encrypt the data any way you want. I personally recommend a symmetric algorithm like AES or TripleDES.
HashAlgorithm hashAlgo = new HMACSHA1();
hashAlgo.Key = /* Your private key for HMAC */
Byte[] hmac = hashAlgo.ComputeHash( someSecretData );
// when using SHA1, hmac will be 160 bits long, or 20 bytes.
PageViewModel model = new PageViewModel();
model.SecretData = Convert.ToBase64String( hmac + someSecretData ); // array concatenation is an exercise for the reader
return View( model );
}
[HttpPost]
public ActionResult Foo(PageViewModel model) {
Byte[] postedData = Convert.FromBase64String( model.SecretData );
Byte[] hmac = postedData[0...20]; // array substring is an exercise for the reader
Byte[] secretData = postedData[20...n];
// Now verify the secret data
HashAlgorithm hashAlgo = new HMACSHA1();
hashAlgo.Key = /* Your private key for HMAC */
Byte[] hmac2 = hashAlgo.ComputeHash( secretData );
if( hmac2 != hmac ) {
/* the data has been tampered with. */
} else {
/* the data is unadulterated */
Byte[] originalSecretData = ArbitaryDecryptionAlgorithm( secretData );
}
}
My main purpose is to give every machine using the website a unique id, one way would be to find the mac address of the client, but not using activex, and also cant assign ID using cookie because cookies can be deleted and not also using last modified date method, so any ideas on how I could assign a unique ID, thanks
You might be able to do this using a java applet, but HTML and web browser policies are very carefully designed to prevent you from doing something like this, as it would be considered a major security risk. A Mac address is certainly not possible to grab without either an activex control (which if discovered would probably get banned for providing such personal information to javascript, unless you had really carefully planned security) or at the very least a java applet that would require the user to grant it elevated privileges.
Most companies just assign a unique id and store it in a cookie in the browser. There are technologies such as FireBreath that make it easy to create browser plugins (activex control and npapi plugin), but again -- what you're talking about has the potential to be a very, very bad idea, so tread with care.
I know its too late to reply for this post..but to share my experience i am posting my answer.(I too faced the same problem)
I used the applet and deployed it on client's machine.
import java.applet.Applet;
import java.applet.Applet;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
public class app extends Applet{
public String macAddr="";
public void init()
{
try
{
System.out.println("Start");
InetAddress ip = InetAddress.getLocalHost();
System.out.println((new StringBuilder("Current IP address:"+ip.toString())));
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
byte mac[] = network.getHardwareAddress();
System.out.println("mac : "+mac.toString());
System.out.print("Current MAC address : ");
StringBuilder sb = new StringBuilder();
for(int i = 0; i < mac.length; i++)
sb.append(String.format("%02X%s", new Object[] {
Byte.valueOf(mac[i]), i >= mac.length - 1 ? "" : "-"
}));
System.out.println(sb.toString());
macAddr=String.valueOf(sb);
System.out.println("okay good");
}
catch(SocketException e)
{
macAddr=e.toString();
e.printStackTrace();
System.out.println("not good");
}
catch (Exception e) {
macAddr=e.toString();
e.printStackTrace();
System.out.println("bad good");
}
}
}
The problem i faced after making this applet is[That it worked fine when i run it on Machine locally (RUN AS APPLET)], buT IT DOESNT WORK ON SERVER``
for that you have to sign your jar
Keytool -genkey -alias signFiles -keystore compstore -keypass KEYPASS -dname "cn=XYZ" -storepass KEY -validity 125000
jarsigner -keystore compstore -storepass PASS -keypass KEYPASS appletname.jar signFiles
After that it worked but not smoothly..as everytime i run it.Browser asks for permission.
which is not good.
I hope my experience helps
I am looking into creating a custom members login system (for learning) and I haven't been able to figure out the C# command to generate an encrypted hash.
Is there a certain namespace I need to import or anything like that?
Using the namespace System.Security.Cryptography:
MD5 md5 = new MD5CryptoServiceProvider();
Byte[] originalBytes = ASCIIEncoding.Default.GetBytes(originalPassword);
Byte[] encodedBytes = md5.ComputeHash(originalBytes);
return BitConverter.ToString(encodedBytes);
or FormsAuthentication.HashPasswordForStoringInConfigFile method
For my part, I purpose this function i use to get the gravatar picture profil:
you can use it like you want
public string getGravatarPicture()
{
MD5 md5 = new MD5CryptoServiceProvider();
Byte[] originalBytes = ASCIIEncoding.Default.GetBytes(email.ToLower());
Byte[] encodedBytes = md5.ComputeHash(originalBytes);
string hash = BitConverter.ToString(encodedBytes).Replace("-", "").ToLower();
return "http://www.gravatar.com/avatar/"+hash+"?d=mm";
}
Well, first of all an encryption hash is a contradiction. Like a vegetarian steak. You can use encryption, or you can hash them (and you should hash them), but hashing is not encryption.
Look up a class starting with Md5 ;) Or Sha1 - those are hash algoryithms. It is all there in .NET (System.Security.Cryptography namespace).
I prefer having my hash all in one concatenated string. I borrowed this to build my hash:
public static string MD5Hash(string itemToHash)
{
return string.Join("", MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(itemToHash)).Select(s => s.ToString("x2")));
}