I have some some time now reshearchd how to encode a password to SHA1 with a salt.
The is the code i used on my web application part, but it will not work on a phone environment.
public class Password
{
private string _password;
private int _salt;
public Password(string strPassword, int nSalt)
{
_password = strPassword;
_salt = nSalt;
}
public string ComputeSaltedHash()
{
// Create Byte array of password string
ASCIIEncoding encoder = new ASCIIEncoding();
Byte[] _secretBytes = encoder.GetBytes(_password);
// Create a new salt
Byte[] _saltBytes = new Byte[4];
_saltBytes[0] = (byte)(_salt >> 24);
_saltBytes[1] = (byte)(_salt >> 16);
_saltBytes[2] = (byte)(_salt >> 8);
_saltBytes[3] = (byte)(_salt);
// append the two arrays
Byte[] toHash = new Byte[_secretBytes.Length + _saltBytes.Length];
Array.Copy(_secretBytes, 0, toHash, 0, _secretBytes.Length);
Array.Copy(_saltBytes, 0, toHash, _secretBytes.Length, _saltBytes.Length);
SHA1 sha1 = SHA1.Create();
Byte[] computedHash = sha1.ComputeHash(toHash);
return encoder.GetString(computedHash);
}
public static int CreateRandomSalt()
{
Byte[] _saltBytes = new Byte[4];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(_saltBytes);
return ((((int)_saltBytes[0]) << 24) + (((int)_saltBytes[1]) << 16) +
(((int)_saltBytes[2]) << 8) + ((int)_saltBytes[3]));
}
public static string CreateRandomPassword(int PasswordLength)
{
String _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ23456789!\"#¤%&/()=?$+-_.,;'*";
Byte[] randomBytes = new Byte[PasswordLength];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomBytes);
char[] chars = new char[PasswordLength];
int allowedCharCount = _allowedChars.Length;
for (int i = 0; i < PasswordLength; i++)
{
chars[i] = _allowedChars[(int)randomBytes[i] % allowedCharCount];
}
return new string(chars);
}
}
Silverlight and Windows Phone 7 do not have an ASCIIEncoding. I suggest you use the UTF8Encoding instead. If you are certain that your passwords are always within the ASCII range then this encoding will work the same as the ASCIIEncoding would of had it been present.
If on the other hand you cannot guarantee that passwords are always within the ASCII range then you would need to make sure both ends hash using the UTF8Encoding to ensure generated hashs are the same.
Related
I have an encryption task that receives an input file and an output file along with the key to perform encryption against. The strange thing is that when I try in extract a method that performs a line encryption and receives it as an argument, I get the next error: Could not find method encryptLine() for arguments [PK] on task ':presentation:encryptScenarios' of type EncryptionTask..
When I inline this method - it works ok.
Here is a code of the inlined variant:
#TaskAction
void encryptFile() {
assertThatEncryptionKeyIsPresent()
createNewOutputFileIfNotExists()
final FileOutputStream outputStream = new FileOutputStream(outputFile)
inputFile.eachLine { String line ->
final byte[] inputBytes = line.getBytes()
final byte[] secretBytes = key.getBytes()
final byte[] outputBytes = new byte[inputBytes.length]
int spos = 0
for (int pos = 0; pos < inputBytes.length; ++pos) {
outputBytes[pos] = (byte) (inputBytes[pos] ^ secretBytes[spos])
spos += 1
if (spos >= secretBytes.length) {
spos = 0
}
}
outputStream.write(Base64.encodeBase64String(outputBytes).getBytes())
}
}
And here is the code of the extracted method variant:
#TaskAction
void encryptFile() {
assertThatEncryptionKeyIsPresent()
createNewOutputFileIfNotExists()
final FileOutputStream outputStream = new FileOutputStream(outputFile)
inputFile.eachLine { String line ->
byte[] outputBytes = encryptLine(line)
outputStream.write(Base64.encodeBase64String(outputBytes).getBytes())
}
}
private byte[] encryptLine(String line) {
final byte[] inputBytes = line.getBytes()
final byte[] secretBytes = key.getBytes()
final byte[] outputBytes = new byte[inputBytes.length]
int spos = 0
for (int pos = 0; pos < inputBytes.length; ++pos) {
outputBytes[pos] = (byte) (inputBytes[pos] ^ secretBytes[spos])
spos += 1
if (spos >= secretBytes.length) {
spos = 0
}
}
outputBytes
}
How to resolve this issue using this private method that encrypts a line?
This error seems to be connected to a Groovy issue referenced here : https://issues.apache.org/jira/browse/GROOVY-7797
You are trying to call a private method from a closure within the same class and it looks like this is not supported.
Please try to remove the private modifier from encryptLine method definition, and you should get rid of this error.
I'm trying to create my first app that will connect to a woocommerce api.
Has anyone any experience in this or can point me in the direction as to how to create a connection to pull in the product list?
Thanks
Since WooCommerce has a REST API, it should be fairly simple to connect using a plain HTTP request, or a library like RestSharp.
There is also a C# client for WooCommerce - I don't know if it plays well with Xamarin, you might need to modify it a bit to get it to build.
var api = new WoocommerceApiClient(StoreUrl, ConsumerKey, ConsumerSecret);
var result = await api.Products.Get();
It's an old post but I had faced a similar issue. I had tries WoocommerceSharp with Xamarin Studio 6.1.1 (mac version); I opened the .sln file, added the missing reference to system.net.http and it worked perfectly.
If you want make it work in PCL you have to use PCLCrypto in WoocommerceApiUrlGenerator.cs , here the updated version:
namespace SharpCommerce.Web
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using PCLCrypto;
internal class WoocommerceApiUrlGenerator
{
private const string SignatureMethod = "HMAC-SHA1";
private const string ApiV3RootEndpoint = "wc-api/v3/";
private readonly string baseURI;
private readonly string consumerKey;
private readonly string consumerSecret;
internal WoocommerceApiUrlGenerator(string storeUrl, string consumerKey, string consumerSecret)
{
if (
string.IsNullOrEmpty(consumerKey) ||
string.IsNullOrEmpty(consumerSecret) ||
string.IsNullOrEmpty(storeUrl))
{
throw new ArgumentException("ConsumerKey, consumerSecret and storeUrl are required");
}
this.consumerKey = consumerKey;
this.consumerSecret = consumerSecret;
// Need 'http://www.example.com' to be 'http://www.example.com/wc-api/v3/'
this.baseURI = String.Format("{0}/{1}", storeUrl.TrimEnd('/'), ApiV3RootEndpoint);
}
internal string GenerateRequestUrl(HttpMethod httpMethod, string apiEndpoint, Dictionary<string, string> parameters = null)
{
parameters = parameters ?? new Dictionary<string, string>();
parameters["oauth_consumer_key"] = this.consumerKey;
// oauth_timestamp = number of seconds since 1/1/1970 00:00:00 GMT
// must be a positive integer
// must be greater than timestamp of previous requests
parameters["oauth_timestamp"] =
Math.Round(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds).ToString(CultureInfo.InvariantCulture);
// oauth_nonce = a unique random string for the timestamp.
// defends against replay attacks
// service provide will know that this request has never been made before.
// Just going to hash the time stamp.
//parameters["oauth_nonce"] = GenerateNonce(parameters["oauth_timestamp"]);
// Create random 32 char alphnumeric to avoid reused nonces
parameters["oauth_nonce"] = GenerateNonce();
// Declare the hashing method your using
parameters["oauth_signature_method"] = SignatureMethod;
//parameters["oauth_version"] = "1.0";
parameters["oauth_signature"] = UpperCaseUrlEncode(this.GenerateSignature(httpMethod, apiEndpoint, parameters));
var sb = new StringBuilder();
foreach (var pair in parameters)
{
sb.AppendFormat("&{0}={1}", SafeUpperCaseUrlEncode(pair.Key), SafeUpperCaseUrlEncode(pair.Value));
}
// Substring removes first '&'
var queryString = sb.ToString().Substring(1);
var url = this.baseURI + apiEndpoint + "?" + queryString;
return url;
}
private string GenerateSignature(HttpMethod httpMethod, string apiEndpoint, Dictionary<string, string> parameters)
{
// 1) Set the HTTP method for the request.
// set through 'method'
//2) Set your base request URI – this is the full request URI without query string parameters – and URL encode according to RFC 3986:
// need 'http://www.example.com/wc-api/v3/orders'
// to become: 'http%3A%2F%2Fwww.example.com%2Fwc-api%2Fv1%2Forders'
var encodedBaseRequestURI = SafeUpperCaseUrlEncode(this.baseURI + apiEndpoint);
// 3) Collect and normalize your query string parameters
// percent(%) characters should be double-encoded (e.g. % becomes %25.
var normalizedParameters = NormalizeParameters(parameters);
// 4) Sort the parameters in byte-order
var orderedNormalizedParameters = normalizedParameters.OrderBy(x => x.Key).ToList();
// 5) Join each parameter with an encoded equals sign (%3D):
//var joinedOrderedNormalizedParameters = orderedNormalizedParameters.ConvertAll(x => x.Key + "%3D" + x.Value);
var joinedOrderedNormalizedParameters = new List<string>();
foreach (var x in orderedNormalizedParameters)
{
joinedOrderedNormalizedParameters.Add(x.Key + "%3D" + x.Value);
}
// 6) Join each parameter key/value pair with an encoded ampersand (%26):
var joinedParameterPairs = String.Join("%26", joinedOrderedNormalizedParameters);
// 7) Form the string to sign by joining the HTTP method, encoded base request URI, and encoded parameter string with an unencoded ampersand symbol (&):
var stringToSign = string.Format("{0}&{1}&{2}", httpMethod.ToString().ToUpper(), encodedBaseRequestURI, joinedParameterPairs);
// 8) Generate the signature using the string to key and your consumer secret key
var preparedStringToSign = Encoding.UTF8.GetBytes(stringToSign);
var secret = this.consumerSecret + "&";
var preparedConsumerKey = Encoding.UTF8.GetBytes(secret);
var signatureHash = Sha1(preparedConsumerKey, preparedStringToSign);
var signatureString = Convert.ToBase64String(signatureHash);
return signatureString;
}
private static byte[] Sha1(byte[] key, byte[] message)
{
var mac = WinRTCrypto.MacAlgorithmProvider.OpenAlgorithm(MacAlgorithm.HmacSha1);
//var keyMaterial = WinRTCrypto.CryptographicBuffer.ConvertStringToBinary(key, Encoding.UTF8);
var cryptoKey = mac.CreateKey(key);
var hash = WinRTCrypto.CryptographicEngine.Sign(cryptoKey, message);
return hash;
//return WinRTCrypto.CryptographicBuffer.CreateFromByteArraymessage);
}
private static Dictionary<string, string> NormalizeParameters(Dictionary<string, string> parameters)
{
var result = new Dictionary<string, string>();
foreach (var pair in parameters)
{
var upperCaseUrlEncodedKey = SafeUpperCaseUrlEncode(pair.Key);
var normalizedKey = upperCaseUrlEncodedKey.Replace("%", "%25");
var upperCaseUrlEncodedValue = SafeUpperCaseUrlEncode(pair.Value);
var normalizedValue = upperCaseUrlEncodedValue.Replace("%", "%25");
result.Add(normalizedKey, normalizedValue);
}
return result;
}
private static string SafeUpperCaseUrlEncode(string stringToEncode)
{
return UpperCaseUrlEncode(System.Net.WebUtility.UrlDecode(stringToEncode));
}
private static string UpperCaseUrlEncode(string stringToEncode)
{
var basicUrlEncodedString = System.Net.WebUtility.UrlEncode(stringToEncode);
if (String.IsNullOrEmpty(basicUrlEncodedString)) return String.Empty;
var upperCaseUrlEncodedString = Regex.Replace(
basicUrlEncodedString,
"(%[0-9a-f][0-9a-f])",
c => c.Value.ToUpper());
return upperCaseUrlEncodedString;
}
private static string GenerateNonce()
{
const string ValidChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var random = new Random();
var nonceString = new StringBuilder();
for (var i = 0; i < 32; i++)
{
nonceString.Append(ValidChars[random.Next(0, ValidChars.Length - 1)]);
}
return nonceString.ToString();
}
}
}
and in WoocommerceApiDriver.cs you will have to replace
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return await client.GetStringAsync(url);
}
by
using (var client = new HttpClient()) // must use to avoid Android freezes after repeated calls
{
Task<HttpResponseMessage> r = client.GetAsync(url);
HttpResponseMessage m = r.Result;
return await m.Content.ReadAsStringAsync();
}
Et voila ! ca marche ;)
I have a class that takes a String parameter and performs a google search, then it gets the ten images and puts them in an array, that is then handled by another method in the same class. Using Javafx.scene.image would probably allow me to implement the buffering progress easily, but there is a bug with JavaFX Image, that misinterprets the color encoding of normal Images, and saves a weird looking image to the hard drive, so I just decided to use awt.Image.
This is the image search class:
public class GoogleCustomSearch {
static String key = //custom google id;
static String cx = // also a custom google id;
static String searchType = "image";
static java.awt.Image[] publicImageArray;
public static java.awt.Image[] Search(String searchParameter,int start) throws IOException, URISyntaxException{
String formatedText = URLEncoder.encode(searchParameter,"UTF-8");
URL url = new URL("https://www.googleapis.com/customsearch/v1?" + "key=" +key + "&cx=" +cx + "&q=" +formatedText + "&searchType=" +searchType +"&imgSize=medium" + "&start=" + start + "&num=10");
System.out.println(url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader( ( conn.getInputStream() ) ) );
GResults results = new Gson().fromJson(br, GResults.class);
java.awt.Image [] imageArray = new java.awt.Image[10];
//JProgressBar prb = new JProgressBar();
//MediaTracker loadTracker = new MediaTracker(prb);
for(int i = 0; i<10; i++){
try {
imageArray[i] = ImageIO.read(new URL(results.getLink(i)));
}catch (java.io.IOException e){
imageArray[i] = ImageIO.read(new File("C:\\Users\\FILIP.D\\IdeaProjects\\Manual_Artwork\\src\\MAT - NoImage.jpg"));
}
}
conn.disconnect();
return imageArray;
}
public static BufferedImage getImage(String searchPar, int index, boolean newSearch) throws IOException, URISyntaxException {
int adaptedIndex;
int start;
BufferedImage bimage;
if(index<10){
adaptedIndex = index;
start = 1;
}else if (index<20){
start = 11;
adaptedIndex = index % 10;
if(index == 10){
publicImageArray = new java.awt.Image[10];
publicImageArray = Search(searchPar,start);
}
}else if(index < 30){
start = 21;
adaptedIndex = index % 10;
if (index == 20) {
publicImageArray = new java.awt.Image[10];
publicImageArray = Search(searchPar,start);
}
}else{
adaptedIndex = index % 10;
start = 21; //ovo ce posle 30 da ga vrti u loop prvih 10
}
if(newSearch){
publicImageArray = new java.awt.Image[10];
publicImageArray = Search(searchPar,start);
return bimage = (BufferedImage) publicImageArray[adaptedIndex];
}else{
return bimage = (BufferedImage) publicImageArray[adaptedIndex];
}
}
public static RenderedImage getLiveImage (int index){
return (RenderedImage) publicImageArray[index % 10];
}
}
And this is the snippet of the main GUI class that just handles opening the new image in the array
private void nextImageResult() throws IOException, URISyntaxException {
if(imgNr == -1){
imgNr++;
changeImage(SwingFXUtils.toFXImage(GoogleCustomSearch.getImage(oppenedTrack.getArtistName() + "+" + oppenedTrack.getTrackName(),imgNr,true),null));
}else{
imgNr++;
changeImage(SwingFXUtils.toFXImage(GoogleCustomSearch.getImage(oppenedTrack.getArtistName() + "+" + oppenedTrack.getTrackName(),imgNr,false),null));
}
}
To summarise, I need a proper way to show a progress bar in the place of the image before it loads, and it needs not to hang the UI, for which I can use Task. I can optimise the loading of the array with MediaTracker, so it can prioritize loading the first few images first.
I'v received on some DES encrypted stuff from a 3rd part company. I can't decrypt it in ruby. But it works in my java code.
Here is java code:
public class Main {
public static void main(String[] args) {
try {
System.out.println(encrypt("12345678", "abc", "12345678"));
//System.out.println(encrypt("12345678", "ABC", "12345678"));
System.out.println(decrypt("12345678", "9YR6ZPdZufM=", "12345678"));
//System.out.println(decrypt("12345678", "6rtTnrF34mPkJ5SO3RiaaQ==", "12345678"));
} catch (Exception e) {
e.printStackTrace();
}
}
public static String encrypt(String key, String str, String ivString) throws Exception {
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
Key secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(ivString.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
byte[] bytes = cipher.doFinal(str.getBytes());
dumpHex(bytes);
return Base64.encode(bytes);
}
public static void dumpHex(byte[] bytes) {
for (byte b : bytes) {
System.out.println(String.format("%02x",b&0xff));
}
System.out.println(bytesToHex(bytes));
}
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
public static String decrypt(String key, String str, String ivString) throws Exception {
byte[] data = Base64.decode(str);
dumpHex(data);
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
Key secretKey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(ivString.getBytes());
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
byte[] decryptedBytes = cipher.doFinal(data);
return new String(decryptedBytes, "gb2312");
}
}
I couldn't found the same DES mode ('DES/CBC/PKCS5Padding') in ruby. I got the different result when I try to encrypt the same string.
Here is my ruby source code:
class Des
require 'openssl'
require 'base64'
ALG = 'DES-EDE3-CBC'
KEY = "12345678"
DES_KEY = "12345678"
def encode(str)
des = OpenSSL::Cipher::Cipher.new(ALG)
des.pkcs5_keyivgen(KEY, DES_KEY)
des.encrypt
cipher = des.update(str) + des.final
pp cipher.length
pp cipher.unpack('H*')[0]
return Base64.encode64(cipher)
end
def decode(str)
str = Base64.decode64(str)
pp str.unpack('H*')[0]
des = OpenSSL::Cipher::Cipher.new(ALG)
des.pkcs5_keyivgen(KEY, DES_KEY)
des.decrypt
des.update(str) + des.final
end
def KEY()
pp KEY.length
KEY
end
def DES_KEY()
pp DES_KEY.length
DES_KEY
end
end
I encrypt 'abc' with java, get "9YR6ZPdZufM=". But get "5SHCjTOrygg=" in ruby version.It confused me a lot.
I change some config in ruby code, and it works. But I didn't know why...
def DES
ALG = 'DES-EDE-CBC'
KEY = "1234567812345678"
DES_KEY = "12345678"
I was wondering what signature algorithm (digestOID) BouncyCastle uses by default if you do not specify it explicitly like like in the code below:
List certList = new ArrayList();
CMSTypedData msg = new CMSProcessableByteArray("Hello world!".getBytes());
certList.add(signCert);
Store certs = new JcaCertStore(certList);
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(signKP.getPrivate());
gen.addSignerInfoGenerator(
new JcaSignerInfoGeneratorBuilder(
new JcaDigestCalculatorProviderBuilder().setProvider("BC").build())
.build(sha1Signer, signCert));
gen.addCertificates(certs);
CMSSignedData sigData = gen.generate(msg, false);
Below is the code example for which I am wondering as you see there is no digestOID(SHA1withRSA) so what type of signature does it use:
import java.io.*;
import java.util.*;
import java.security.*;
import java.security.Security;
import java.security.cert.*;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.cms.*;
/* Create CMS/pkcs #7 signature using BC provider
M. Gallant 07/02/2003 */
class BCSignFile {
static final boolean DEBUG = false;
public static void main(String args[]) {
System.out.println("");
if (args.length < 4)
usage();
Security.addProvider(new BouncyCastleProvider());
String INFILE = args[0]; // Input file to be signed
String KEYSTORE = args[1]; // Java 2 keystore file
String ALIAS = args[2]; // Java 2 key entry alias
String PSWD = args[3]; // keystore password
// ---- in real implementation, provide some SECURE way to get keystore
// ---- password from user! -------
KeyStore keystore = null;
PublicKey pub = null;
PrivateKey priv = null;
java.security.cert.Certificate storecert = null;
java.security.cert.Certificate[] certChain = null;
ArrayList certList = new ArrayList();
CertStore certs =null;
try{
keystore = KeyStore.getInstance("JKS");
keystore.load(new FileInputStream(KEYSTORE), PSWD.toCharArray());
certChain = keystore.getCertificateChain(ALIAS);
for ( int i = 0; i < certChain.length;i++)
certList.add(certChain[i]);
certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC");
priv = (PrivateKey)(keystore.getKey(ALIAS, PSWD.toCharArray()));
storecert = keystore.getCertificate(ALIAS);
pub = keystore.getCertificate(ALIAS).getPublicKey();
}
catch(Exception exc){
System.out.println("Problem with keystore access: " + exc.toString()) ;
return;
}
if(DEBUG){
System.out.println("Public Key Format: " + pub.getFormat()) ;
System.out.println("Certificate " + storecert.toString()) ;
}
FileInputStream freader = null;
File f = null;
//------ Get the content data from file -------------
f = new File(INFILE) ;
int sizecontent = ((int) f.length());
byte[] contentbytes = new byte[sizecontent];
try {
freader = new FileInputStream(f);
System.out.println("\nContent Bytes: " + freader.read(contentbytes, 0, sizecontent));
freader.close();
}
catch(IOException ioe) {
System.out.println(ioe.toString());
return;
}
// --- Use Bouncy Castle provider to create CSM/PKCS#7 signed message ---
try{
CMSSignedDataGenerator signGen = new CMSSignedDataGenerator();
signGen.addSigner(priv, (X509Certificate)storecert, CMSSignedDataGenerator.DIGEST_SHA1);
signGen.addCertificatesAndCRLs(certs);
CMSProcessable content = new CMSProcessableByteArray(contentbytes);
CMSSignedData signedData = signGen.generate(content,"BC");
byte[] signeddata = signedData.getEncoded();
System.out.println("Created signed message: " + signeddata.length + " bytes") ;
FileOutputStream envfos = new FileOutputStream("BCsigned.p7s");
envfos.write(signeddata);
envfos.close();
}
catch(Exception ex){
System.out.println("Couldn't generate CMS signed message\n" + ex.toString()) ;
}
}
private static void usage() {
System.out.println("Usage:\n java BCSignFile <contentfile> <keystore> <alias> <keypasswd>") ;
System.exit(1);
}
}
The relevant line is this:
signGen.addSigner(priv, (X509Certificate)storecert, CMSSignedDataGenerator.DIGEST_SHA1);
This line specifies that the digest-algorithm will be SHA-1 and that the signing-algorithm will be decided based on the type of the private key in priv.
If priv contains an RSA key, it will sign using PKCS#1 v.1.5 with SHA-1 ("SHA1withRSA"). You can look in the source of CMSSignedGenerator.getEncOID() to see what happens with other types of private key.