How to implement DES encrypting with ('DES/CBC/PKCS5Padding' mode) in Ruby? - ruby

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"

Related

how to print image to thermal printer in kotlin

i already able to print text using kotlin to thermal printer, but im still dont know how to print image to thermal printer in kotlin. please give me sample printing image to thermal printer in kotlin.i already search for the topics, but it written in java, i doesnt know java very much thanks for the help
private fun p1() {
val namaToko = "Rose Medical"
val alamatToko = "Pramuka raya no.1 Jakarta Timur"
val telp = "021-85901642"
val enter = "\n"
val strip = "-"
val rp ="Rp."
val ex = " X "
val textTotal = "Total Rp:"
val ppnTv = "PPN :Rp."
val chargeTv ="Charge :Rp."
val totalTv = "Total Belanja :Rp."
val scope = CoroutineScope(Dispatchers.IO)
scope.launch {
// chunks1
try{
writeWithFormat(namaToko.toByteArray(),Formatter().get(),Formatter.centerAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(alamatToko.toByteArray(),Formatter().get(),Formatter.centerAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(telp.toByteArray(),Formatter().get(),Formatter.centerAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.rightAlign())
}catch (e: Exception) {
Log.e("PrintActivity", "Exe ", e)
}
// chunks2
for(pointer in salesBody.indices){
try {
val merk = salesBody[pointer].merk
writeWithFormat(merk!!.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(strip.toByteArray(),Formatter().get(),Formatter.leftAlign())
val barang = salesBody[pointer].namaBrg
writeWithFormat(barang!!.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.leftAlign())
val varian = salesBody[pointer].varian
writeWithFormat(varian!!.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(rp.toByteArray(),Formatter().get(),Formatter.leftAlign())
val harga = ValidNumber().deciformat(salesBody[pointer].hargaJual.toString())
writeWithFormat(harga.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(ex.toByteArray(),Formatter().get(),Formatter.leftAlign())
val jumlah = ValidNumber().deciformat(salesBody[pointer].qty.toString())
writeWithFormat(jumlah.toByteArray(),Formatter().get(),Formatter.leftAlign())
val satuan = salesBody[pointer].unit
writeWithFormat(satuan!!.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(textTotal.toByteArray(),Formatter().get(),Formatter.rightAlign())
val total = ValidNumber().deciformat(salesBody[pointer].total.toString())
writeWithFormat(total.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.leftAlign())
}catch (e: Exception) {
Log.e("PrintActivity", "Exe ", e)
}
}
// chunks3
try{
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.leftAlign())
val tanggal = salesHeader[0].tanggal
writeWithFormat(tanggal!!.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(strip.toByteArray(),Formatter().get(),Formatter.leftAlign())
val jam = salesHeader[0].jam
writeWithFormat(jam!!.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(strip.toByteArray(),Formatter().get(),Formatter.leftAlign())
val idTag= salesHeader[0].idTag
writeWithFormat(idTag!!.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.leftAlign())
val payment= salesHeader[0].payment
writeWithFormat(payment!!.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(ppnTv.toByteArray(),Formatter().get(),Formatter.rightAlign())
val ppnValue = ValidNumber().deciformat(salesHeader[0].ppn.toString())
writeWithFormat(ppnValue.toByteArray(),Formatter().get(),Formatter.rightAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.rightAlign())
writeWithFormat(chargeTv.toByteArray(),Formatter().get(),Formatter.rightAlign())
val chargeValue = ValidNumber().deciformat(salesHeader[0].charge.toString())
writeWithFormat(chargeValue.toByteArray(),Formatter().get(),Formatter.rightAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.rightAlign())
writeWithFormat(totalTv.toByteArray(),Formatter().get(),Formatter.rightAlign())
var totalValue = ValidNumber().deciformat(salesHeader[0].allTotal.toString())
writeWithFormat(totalValue.toByteArray(),Formatter().get(),Formatter.rightAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.rightAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.rightAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.rightAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.rightAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.rightAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.rightAlign())
}catch (e: Exception) {
Log.e("PrintActivity", "Exe ", e)
}
}
}
//print code
class Formatter {
/** The format that is being build on */
private val mFormat: ByteArray
init {
// Default:
mFormat = byteArrayOf(27, 33, 0)
}
/**
* Method to get the Build result
*
* #return the format
*/
fun get(): ByteArray {
return mFormat
}
fun bold(): Formatter {
// Apply bold:
mFormat[2] = (0x8 or mFormat[2].toInt()).toByte()
return this
}
fun small(): Formatter {
mFormat[2] = (0x1 or mFormat[2].toInt()).toByte()
return this
}
fun height(): Formatter {
mFormat[2] = (0x10 or mFormat[2].toInt()).toByte()
return this
}
fun width(): Formatter {
mFormat[2] = (0x20 or mFormat[2].toInt()).toByte()
return this
}
fun underlined(): Formatter {
mFormat[2] = (0x80 or mFormat[2].toInt()).toByte()
return this
}
companion object {
fun rightAlign(): ByteArray {
return byteArrayOf(0x1B, 'a'.code.toByte(), 0x02)
}
fun leftAlign(): ByteArray {
return byteArrayOf(0x1B, 'a'.code.toByte(), 0x00)
}
fun centerAlign(): ByteArray {
return byteArrayOf(0x1B, 'a'.code.toByte(), 0x01)
}
}
}//last
fun writeWithFormat(buffer: ByteArray, pFormat: ByteArray?, pAlignment: ByteArray?): Boolean {
val mmOutStream: OutputStream = mBluetoothSocket.outputStream
return try {
// Notify printer it should be printed with given alignment:
mmOutStream.write(pAlignment)
// Notify printer it should be printed in the given format:
mmOutStream.write(pFormat)
// Write the actual data:
mmOutStream.write(buffer, 0, buffer.size)
// Share the sent message back to the UI Activity
//App.getInstance().getHandler().obtainMessage(MESSAGE_WRITE, buffer.size, -1, buffer).sendToTarget()
true
} catch (e: IOException) {
Log.e(TAG, "Exception during write", e)
false
}
}
//print code close
Using Thermal Printer repo references, I managed to print image to Bluetooth thermal printer. Make sure to use a proper black and white image to print.
Here is the piece of code I used to make a java class
--BitmapHelper.java.
public class BitmapHelper {
private static String[] binaryArray = { "0000", "0001", "0010", "0011",
"0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011",
"1100", "1101", "1110", "1111" };
public static byte[] decodeBitmap(Bitmap bmp){
//Bitmap bmp = Bitmap.createScaledBitmap(bitmap, 50, 50, false);
int maxWidth = 350;
int bmpWidth = bmp.getWidth();
int bmpHeight = bmp.getHeight();
if(bmpWidth > maxWidth){
float aspectRatio = bmp.getWidth() /
(float) bmp.getHeight();
bmpWidth = maxWidth;
bmpHeight = Math.round(bmpWidth / aspectRatio);
bmp = Bitmap.createScaledBitmap(bmp, bmpWidth, bmpHeight, false);
}
List<String> list = new ArrayList<>(); //binaryString list
StringBuffer sb;
int zeroCount = bmpWidth % 8;
StringBuilder zeroStr = new StringBuilder();
if (zeroCount > 0) {
for (int i = 0; i < (8 - zeroCount); i++) {
zeroStr.append("0");
}
}
for (int i = 0; i < bmpHeight; i++) {
sb = new StringBuffer();
for (int j = 0; j < bmpWidth; j++) {
int color = bmp.getPixel(j, i);
int r = (color >> 16) & 0xff;
int g = (color >> 8) & 0xff;
int b = color & 0xff;
// if color close to white,bit='0', else bit='1'
if (r > 160 && g > 160 && b > 160)
sb.append("0");
else
sb.append("1");
}
if (zeroCount > 0) {
sb.append(zeroStr);
}
list.add(sb.toString());
}
List<String> bmpHexList = binaryListToHexStringList(list);
String commandHexString = "1D763000";
String widthHexString = Integer
.toHexString(bmpWidth % 8 == 0 ? bmpWidth / 8
: (bmpWidth / 8 + 1));
if (widthHexString.length() > 2) {
Log.e("decodeBitmap error", " width is too large");
return null;
} else if (widthHexString.length() == 1) {
widthHexString = "0" + widthHexString;
}
widthHexString = widthHexString + "00";
String heightHexString = Integer.toHexString(bmpHeight);
if (heightHexString.length() > 2) {
Log.e("decodeBitmap error", " height is too large");
return null;
} else if (heightHexString.length() == 1) {
heightHexString = "0" + heightHexString;
}
heightHexString = heightHexString + "00";
List<String> commandList = new ArrayList<>();
commandList.add(commandHexString+widthHexString+heightHexString);
commandList.addAll(bmpHexList);
return hexList2Byte(commandList);
}
private static List<String> binaryListToHexStringList(List<String> list) {
List<String> hexList = new ArrayList<String>();
for (String binaryStr : list) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < binaryStr.length(); i += 8) {
String str = binaryStr.substring(i, i + 8);
String hexString = myBinaryStrToHexString(str);
sb.append(hexString);
}
hexList.add(sb.toString());
}
return hexList;
}
private static String myBinaryStrToHexString(String binaryStr) {
StringBuilder hex = new StringBuilder();
String f4 = binaryStr.substring(0, 4);
String b4 = binaryStr.substring(4, 8);
String hexStr = "0123456789ABCDEF";
for (int i = 0; i < binaryArray.length; i++) {
if (f4.equals(binaryArray[i]))
hex.append(hexStr.substring(i, i + 1));
}
for (int i = 0; i < binaryArray.length; i++) {
if (b4.equals(binaryArray[i]))
hex.append(hexStr.substring(i, i + 1));
}
return hex.toString();
}
private static byte[] hexList2Byte(List<String> list) {
List<byte[]> commandList = new ArrayList<byte[]>();
for (String hexStr : list) {
commandList.add(hexStringToBytes(hexStr));
}
return sysCopy(commandList);
}
private static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
private static byte[] sysCopy(List<byte[]> srcArrays) {
int len = 0;
for (byte[] srcArray : srcArrays) {
len += srcArray.length;
}
byte[] destArray = new byte[len];
int destLen = 0;
for (byte[] srcArray : srcArrays) {
System.arraycopy(srcArray, 0, destArray, destLen, srcArray.length);
destLen += srcArray.length;
}
return destArray;
}
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
}
Then I use it in the print activity:
private fun p2(){
val convertBmp : Bitmap
convertBmp = BitmapFactory.decodeResource(getResources(),com.example.ronibluetooth.R.drawable.poly)
val decodeBmp = BitmapHelper.decodeBitmap(convertBmp)
val scope = CoroutineScope(Dispatchers.IO)
scope.launch {
try {
val os =mBluetoothSocket.outputStream
os.write(decodeBmp,0,decodeBmp.size)
}
catch (e: Exception) {
Log.e("PrintActivity", "Exe ", e)
}
}
}
image to print
result print

Gradle custom task implementation: could not find method for arguments

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.

DES decryption in Ruby

The following is my java code for DES decryption:
public static byte[] decrypt(final byte[] value, final String key) throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeySpecException, IllegalBlockSizeException, BadPaddingException {
final DESKeySpec objDesKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
final SecretKeyFactory objKeyFactory = SecretKeyFactory.getInstance("DES");
final SecretKey objSecretKey = objKeyFactory.generateSecret(objDesKeySpec);
final byte[] rgbIV = key.getBytes();
final IvParameterSpec iv = new IvParameterSpec(rgbIV);
final Cipher objCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
objCipher.init(2, objSecretKey, iv);
return objCipher.doFinal(value);
}
And I try to convert it to Ruby code as the following:
def decryption(key, decodeString)
ALG = 'des'
cipher = OpenSSL::Cipher::Cipher.new(ALG)
cipher.decrypt #choose descryption mode.
cipher.key = key
plain = cipher.update(decodeString )
plain << cipher.final
end
After executing the java and ruby code, I got the same size of bytes, but the contents of bytes are different. Where did I go wrong?
Thanks for your question!
To do this, use the OpenSSL::Cipher library. Here is a link with some sample code for AES: http://www.ruby-doc.org/stdlib-1.9.3/libdoc/openssl/rdoc/OpenSSL/Cipher.html#class-OpenSSL::Cipher-label-Encrypting+and+decrypting+some+data
To use DES, run this command to see if your Ruby installation supports DES.
puts OpenSSL::Cipher.ciphers
According to this article : http://43n141e.blogspot.tw/2008/08/des-encryption-java-to-openssl-to-ruby.html , I try the following two steps :
1. Calculate iv value in Java:
String key = "123456"
final byte[] rgbIV = key.getBytes();
final IvParameterSpec iv = new IvParameterSpec(rgbIV);
byte[] ivBytes = iv.getIV();
StringBuffer sbuf = new StringBuffer();
for (byte b : ivBytes) {
sbuf.append(String.format("%02x", (b & 0xFF)));
}
System.out.println("iv: " + sbuf);
2. Decrypt in Ruby :
def decode(encryptedString, key, iv)
decrypt = OpenSSL::Cipher::Cipher.new('des-cbc')
decrypt.decrypt
decrypt.key = key
decrypt.iv = iv.scan(/../).map{|b|b.hex}.pack('c*')
decrypt.update(encryptedString) + decrypt.final
end
and it works !

What is the default signature algorithm of bouncycastle CMSSignedDataGenerator if not explicitly specified

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.

SHA1 with salt on windows phone 7

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.

Resources