I am unable to do this in my android app using java language. I am using the retrofit library for this but the problem is the signature. unable to generate proper signature which gives me an error. It is working in POSTMAN and getting proper responses. Help me to convert this in JAVA.
Documentation of API - https://docs.wazirx.com/#fund-details-user_data
POSTMAN PRE-REQUEST SCRIPT
MAIN PARAMS --> BASE_URL, API_KEY, SECRET_KEY, SIGNATURE & TIMESTAMP in miliseconds.
var navigator = {}; //fake a navigator object for the lib
var window = {}; //fake a window object for the lib
const privateKey = pm.environment.get("rsa_private_key");
const secretKey = pm.environment.get("secret_key");
// Set Current Time
var time = new Date().getTime()
postman.setEnvironmentVariable("current_time", time)
query_a = pm.request.url.query.toObject(true)
// Generate Request Payload
let query_string_array = []
Object.keys(query_a).forEach(function(key) {
if (key == 'signature') { return }
if (key == 'timestamp') {
query_string_array.push(key + "=" + time)
}
else if (typeof query_a[key] == "string") {
query_string_array.push(key + "=" + query_a[key])
} else {
query_a[key].forEach(function(value){
query_string_array.push(key + "=" + value)
})
}
})
const payload = query_string_array.join("&")
console.log("Request Payload = ", payload)
if(secretKey) {
const signature = CryptoJS.HmacSHA256(payload, secretKey) + ''
pm.environment.set("signature", signature)
console.log("Signature = "+signature);
} else {
// Download RSA Library
pm.sendRequest(pm.environment.get("rsa_library_js"), function (err, res) {
if (err){
console.log("Error: " + err);
}
else {
// Compile & Run RSA Library
eval(res.text())();
// Sign Payload
var signatureLib = new KJUR.crypto.Signature({"alg": "SHA256withRSA"});
signatureLib.init(privateKey);
signatureLib.updateString(payload);
var signatureHash = hex2b64(signatureLib.sign());
console.log("Signature = ", signatureHash)
// Assign Values
pm.environment.set("signature", encodeURIComponent(signatureHash, "UTF-8"))
}
})
}
Java Code:
//REQUEST CLASS START -->
public class Request {
String baseUrl;
String apiKey="1***uR7";
String apiSecret="b1**qVmh";
Signature sign = new Signature();
public Request(String baseUrl, String apiKey, String apiSecret) {
this.baseUrl = baseUrl;
this.apiKey = apiKey;
this.apiSecret = apiSecret;
}
private void printResponse(HttpURLConnection con) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}
private void printError(HttpURLConnection con) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getErrorStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}
private String getTimeStamp() {
long timestamp = System.currentTimeMillis();
return "timestamp=" + timestamp;
}
//concatenate query parameters
private String joinQueryParameters(HashMap<String,String> parameters) {
String urlPath = "";
boolean isFirst = true;
for (Map.Entry mapElement : parameters.entrySet()) {
if (isFirst) {
isFirst = false;
urlPath += mapElement.getKey() + "=" + mapElement.getValue();
} else {
urlPath += "&" + mapElement.getKey() + "=" + mapElement.getValue();
}
}
return urlPath;
}
private void send(URL obj, String httpMethod) throws Exception {
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
if (httpMethod != null) {
con.setRequestMethod(httpMethod);
}
//add API_KEY to header content
con.setRequestProperty("X-API-KEY", apiKey);
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // success
printResponse(con);
} else {
printError(con);
}
}
public void sendPublicRequest(HashMap<String,String> parameters, String urlPath) throws Exception {
String queryPath = joinQueryParameters(parameters);
URL obj = new URL(baseUrl + urlPath + "?" + queryPath);
System.out.println("url:" + obj.toString());
send(obj, null);
}
public void sendSignedRequest(HashMap<String,String> parameters, String urlPath, String httpMethod) throws Exception {
String queryPath = "";
String signature = "";
if (!parameters.isEmpty()) {
queryPath += joinQueryParameters(parameters) + "&" + getTimeStamp();
} else {
queryPath += getTimeStamp();
}
try {
signature = sign.getSignature(queryPath, apiSecret);
}
catch (Exception e) {
System.out.println("Please Ensure Your Secret Key Is Set Up Correctly! " + e);
System.exit(0);
}
queryPath += "&signature=" + signature;
URL obj = new URL(baseUrl + urlPath + "?" + queryPath);
System.out.println("url:" + obj.toString());
send(obj, httpMethod);
}
}
//REQUEST CLASS END -->
//SPOT CLASS START -->
public class Spot {
private static final String API_KEY = System.getenv("1***57");
private static final String API_SECRET = System.getenv("b****n8");
HashMap<String,String> parameters = new HashMap<String,String>();
Request httpRequest;
public Spot() {
String baseUrl = "https://api.wazirx.com";
httpRequest = new Request(baseUrl, API_KEY, API_SECRET);
}
public void account() throws Exception {
httpRequest.sendSignedRequest(parameters, "/sapi/v1/funds", "GET");
}
}
//SPOT CLASS END-->
//SIGNATURE CLASS START-->
public class Signature {
final String HMAC_SHA256 = "HmacSHA256";
//convert byte array to hex string
private String bytesToHex(byte[] bytes) {
final char[] hexArray = "0123456789abcdef".toCharArray();
char[] hexChars = new char[bytes.length * 2];
for (int j = 0, v; j < bytes.length; j++) {
v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
public String getSignature(String data, String key) {
byte[] hmacSha256 = null;
try {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), HMAC_SHA256);
Mac mac = Mac.getInstance(HMAC_SHA256);
mac.init(secretKeySpec);
hmacSha256 = mac.doFinal(data.getBytes());
} catch (Exception e) {
throw new RuntimeException("Failed to calculate hmac-sha256", e);
}
return bytesToHex(hmacSha256);
}
}
//SIGNATURE CLASS END-->
I have successfully generate pkcs7 signature ECDSAwithSHA256 using C# , but then i failed to verify signature using java
Here is sample class
public class TestVerify {
public static void main(String[] args) {
String Signature = "MIIHFwYJKoZIhvcNAQcCoIIHCDCCBwQCAQExDzANBglghkgBZQMEAgEFADALBgkqhkiG9w0BBwGgggV3MIIC+TCCAp+gAwIBAgIQDO8RREz6FwFvoLhaHz4ybzAKBggqhkjOPQQDAjB8MQswCQYDVQQGEwJNWTEkMCIGA1UEChMbTVNDIFRydXN0Z2F0ZS5jb20gU2RuLiBCaGQuMR8wHQYDVQQLExZGb3IgVGVzdCBQdXJwb3Nlcy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IoxhhWz0E0tmZdtnR79VYzIi8iNrJLokqV2PWmjlIxggJNMIICSQIBATCBhjByMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMTEwLwYDVQQDEyhEaWdpQ2VydCBTSEEyIEFzc3VyZWQgSUQgVGltZXN0YW1waW5nIENBAhAEzT+FaK52xhuw/nFgzKdtMA0GCWCGSAFlAwQCAQUAoIGYMBoGCSqGSIb3DQEJAzENBgsqhkiG9w0BCRABBDAcBgkqhkiG9w0BCQUxDxcNMjAxMDI2MTYzNTM0WjArBgsqhkiG9w0BCRACDDEcMBowGDAWBBQDJb1QXtqWMC3CL0+gHkwovig0xTAvBgkqhkiG9w0BCQQxIgQgYN8efCT/4ewuiiMU3leIE9oQPicVR0oD2djP82NuWzswDQYJKoZIhvcNAQEBBQAEggEAsFGcnfha6umvrl+CEkrF10NJYynmAfYWQDnxgt+/B4gJlehJgGvxp3qAMhwCJE2ni4+/kfpRKAPYmxKriUiqDTAZeneV7Mm3gR2msfmSblcmZYHkAcI3S1tTuuWcKulur0boOwzqu6KxISyYtEhpbX9Wg5bdyf4TaLphp+jY4SFBw1EwY4Wdg5dQ6bx2NDauXxyBgOFBxD/5goRpGfM6AvNe9lD416xQty0pvIVjzhRBjkxp4hzSqI7zUA/H/L2nByvthY77MltL3BSqdrEa8/r4CxmMMx0y3Y5kGozbU9ur61QJsxYXmV+NENjhCRo6H6OUhgSHbluTCO1wjvSCZAAAAAA=";
String pdfhash = "faadTnFU4cOBsl+sW98ie7KInSbbw0HDbgFeOcsRCAQ=";
CMSSignedData signedDataTSToken = null;
TimeStampToken tstoken = null;
byte[] sigDataBytes = null;
Date sigDate = null;
CMSSignerHelper cmsHelper = new CMSSignerHelper();
CMSSignedData cmsData;
try {
sigDataBytes = Base64.getDecoder().decode(Signature);
cmsData = new CMSSignedData(sigDataBytes);
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
sigDate = formatter.parse(SigDateTime);
byte[] tsTokenDataBytes = Base64.getDecoder().decode(TimestampToken);
signedDataTSToken = new CMSSignedData(tsTokenDataBytes);
tstoken = new TimeStampToken(signedDataTSToken);
verifyCMSSignatureMTID(sigDataBytes, sigDate, TimestampToken, pdfhash);
} catch (Exception e) {
System.out.println("Exception : " + e);
}
}
public static void verifyCMSSignatureMTID(byte[] signature, Date signing_date, String encodedTimestampToken, String PdfHash) throws OperatorCreationException, CMSException, CertificateException, NoSuchAlgorithmException, ParseException, TSPException, IOException, Exception {
String fName="[verifyCMSSignatureMTID] ";
VSInfo vsi=new VSInfo();
String initErr="CMS";
//******************** VERIFY SGNATURE VS SIGNER PUBLICKEY **********************
// Verify signature
byte[] HashByte = Base64.getDecoder().decode(PdfHash);
CMSProcessableByteArray processable = new CMSProcessableByteArray(HashByte);
CMSSignedData cmsData = new CMSSignedData(signature);
X509CertificateHolder certHolder_v=null;
Security.addProvider(new BouncyCastleProvider());
try {
Store store = cmsData.getCertificates();
ByteArrayInputStream stream = new ByteArrayInputStream(signature);
CMSSignedData cms = new CMSSignedData(processable, stream);
SignerInformationStore signers = cms.getSignerInfos();
Collection c_v = signers.getSigners();
Iterator it_v = c_v.iterator();
while (it_v.hasNext()) {
SignerInformation signer_v = (SignerInformation) it_v.next();
Collection certCollection_v = store.getMatches(signer_v.getSID());
Iterator certIt_v = certCollection_v.iterator();
certHolder_v = (X509CertificateHolder) certIt_v.next();
X509Certificate certFromSignedData_v = new JcaX509CertificateConverter().getCertificate(certHolder_v);
if (signer_v.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build(certFromSignedData_v))) {
System.out.println(fName + "Signature verified");
} else {
System.out.println(fName + "Error CMS200 Signature is invalid");
System.out.println(initErr+"200");
System.out.println("Signature is invalid");
return;
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(fName + "Error CMS200 Signature is invalid : " + e);
System.out.println("200");
System.out.println("Signature is invalid");
return;
}
System.out.println("000");
System.out.println("Signature is valid");
return;
}
}
Error
org.bouncycastle.operator.RuntimeOperatorException: exception
obtaining signature: error decoding signature bytes.
However, i have succesfully verify RSAwithSHA256 signature using this method. Can someone help me on this and kindly explain what that error is about. The signature length for those signature is 256byte for RSA and 64byte for ECDSA . is it correct?
I have written the below code to verify the signature of a file using a certificate that is there in my certificate store. But when I try to get its signature and pass it to the SignedData method, I am getting the below exception.
org.bouncycastle.cms.CMSException: Malformed content.
at org.bouncycastle.cms.CMSUtils.readContentInfo(Unknown Source)
at org.bouncycastle.cms.CMSUtils.readContentInfo(Unknown Source)
at org.bouncycastle.cms.CMSSignedData.<init>(Unknown Source)
at VerifyFinal.main(VerifyFinal.java:65)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: java.lang.IllegalArgumentException: unknown object in getInstance: org.bouncycastle.asn1.DERApplicationSpecific
at org.bouncycastle.asn1.ASN1Sequence.getInstance(Unknown Source)
at org.bouncycastle.asn1.cms.ContentInfo.getInstance(Unknown Source)
... 9 more
Below is the code I used to verify the signature of the file.
Security.addProvider(new BouncyCastleProvider());
KeyStore msCertStore = KeyStore.getInstance("Windows-MY", "SunMSCAPI");
msCertStore.load(null, null);
X509Certificate cer = ((X509Certificate) msCertStore.getCertificate("Software View Certificate Authority"));
PublicKey pubKey = cer.getPublicKey();
byte[] sigToVerify = cer.getSignature();
Signature signature = Signature.getInstance("SHA1WithRSA", "BC");
signature.initVerify(pubKey);
CMSSignedData cms = new CMSSignedData(cer.getSignature());
Store store = cms.getCertificates();
SignerInformationStore signers = cms.getSignerInfos();
Collection c = signers.getSigners();
Iterator it = c.iterator();
while (it.hasNext()) {
SignerInformation signer = (SignerInformation) it.next();
Collection certCollection = store.getMatches(signer.getSID());
Iterator certIt = certCollection.iterator();
X509CertificateHolder certHolder = (X509CertificateHolder) certIt.next();
X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);
if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))) {
System.out.println("verified");
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
In case you need, below is how I signed the file.
File file = new File("G:\\Projects\\test.zip");
fin = new FileInputStream(file);
byte fileContent[] = new byte[(int) file.length()];
Security.addProvider(new BouncyCastleProvider());
KeyStore ks = KeyStore.getInstance(KEYSTORE_INSTANCE);
ks.load(new FileInputStream(KEYSTORE_FILE), KEYSTORE_PWD.toCharArray());
Key key = ks.getKey(KEYSTORE_ALIAS, KEYSTORE_PWD.toCharArray());
//Sign
PrivateKey privKey = (PrivateKey) key;
Signature signature = Signature.getInstance("SHA1WithRSA", "BC");
signature.initSign(privKey);
signature.update(fileContent);
//Build CMS
X509Certificate cert = (X509Certificate) ks.getCertificate(KEYSTORE_ALIAS);
List certList = new ArrayList();
CMSTypedData msg = new CMSProcessableByteArray(signature.sign());
certList.add(cert);
Store certs = new JcaCertStore(certList);
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(privKey);
gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(sha1Signer, cert));
gen.addCertificates(certs);
CMSSignedData sigData = gen.generate(msg, true);
BASE64Encoder encoder = new BASE64Encoder();
String signedContent = encoder.encode((byte[]) sigData.getSignedContent().getContent());
System.out.println("Signed content: " + signedContent + "\n");
String envelopedData = encoder.encode(sigData.getEncoded());
System.out.println("Enveloped data: " + envelopedData);
AFTER COMMENTS FROM VOLKERK :
How I generate the signature+data file :
public static void main(String[] args) throws Exception {
// String text = "This is a message";
// File file = new
// File("C:\\Users\\mayooranM\\Desktop\\SignatureVerificationTest\\ProcessExplorer.zip");
// fin = new FileInputStream(file);
// byte fileContent[] = new byte[(int) file.length()];
Path filepath = Paths.get("G:\\IntelliJTestProjects\\googleplaces.zip");
byte[] fileContent = Files.readAllBytes(filepath);
Security.addProvider(new BouncyCastleProvider());
KeyStore ks = KeyStore.getInstance(KEYSTORE_INSTANCE);
ks.load(new FileInputStream(KEYSTORE_FILE), KEYSTORE_PWD.toCharArray());
Key key = ks.getKey(KEYSTORE_ALIAS, KEYSTORE_PWD.toCharArray());
// Sign
PrivateKey privKey = (PrivateKey) key;
Signature signature = Signature.getInstance("SHA1WithRSA", "BC");
signature.initSign(privKey);
signature.update(fileContent);
// Build CMS
X509Certificate cert = (X509Certificate) ks.getCertificate(KEYSTORE_ALIAS);
List certList = new ArrayList();
CMSTypedData msg = new CMSProcessableByteArray(signature.sign());
certList.add(cert);
Store certs = new JcaCertStore(certList);
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(privKey);
gen.addSignerInfoGenerator(
new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build())
.build(sha1Signer, cert));
gen.addCertificates(certs);
CMSSignedData sigData = gen.generate(msg, true);
BASE64Encoder encoder = new BASE64Encoder();
String signedContent = encoder.encode((byte[]) sigData.getSignedContent().getContent());
System.out.println("Signed content: " + signedContent + "\n");
String envelopedData = encoder.encode(sigData.getEncoded());
System.out.println("Enveloped data: " + envelopedData);
FileOutputStream fos = new FileOutputStream(
"G:\\IntelliJTestProjects\\SignedZip.zip");
fos.write(envelopedData.getBytes());
fos.close();
}
How I verify data:
public static void main(String[] args) {
try {
Security.addProvider(new BouncyCastleProvider());
Path path = Paths
.get("G:\\IntelliJTestProjects\\SignedZip.zip");
byte[] signedContent = Files.readAllBytes(path);
String output = new String(signedContent);
System.out.println("output: " + output);
CMSSignedData cms = new CMSSignedData(Base64.decode(signedContent));
Store store = cms.getCertificates();
SignerInformationStore signers = cms.getSignerInfos();
Collection c = signers.getSigners();
Iterator it = c.iterator();
while (it.hasNext()) {
SignerInformation signer = (SignerInformation) it.next();
Collection certCollection = store.getMatches(signer.getSID());
Iterator certIt = certCollection.iterator();
X509CertificateHolder certHolder = (X509CertificateHolder) certIt.next();
X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);
if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))) {
System.out.println("verified");
}
}
CMSProcessable origData = cms.getSignedContent() ;
byte[] originalContent = (byte[]) origData.getContent();
ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(originalContent));
ZipEntry entry = null;
while ((entry = zipStream.getNextEntry()) != null) {
String entryName = entry.getName();
FileOutputStream out = new FileOutputStream(entryName);
byte[] byteBuff = new byte[4096];
int bytesRead = 0;
while ((bytesRead = zipStream.read(byteBuff)) != -1)
{
out.write(byteBuff, 0, bytesRead);
}
out.close();
zipStream.closeEntry();
}
zipStream.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
Part 2
Ok, now that you've got a file containing the pkcs7 signed data, let's try to retrieve the contents and verify the integrity ...and validity.
The goal is again not to load the whole thing into memory. Looks like CMSSignedDataParser can do that.
Since the documentation says
Note: that because we are in a streaming mode [...] it is important that the methods on the parser are called in the appropriate order.
So, let's first look at what we actual got so far. For that I used a text file containing the line Mary had a little lamb as the input file, instead of the .m4v (or the .zip in your case) and passed the result to http://lapo.it/asn1js/ (you got to love this tool....)
So, the actual contents comes before the signature data and we have to read the entries in the order they appear in the file. Would be easier the other way round, but ...
The idea is to write the contents to the target file regardless of whether it checks out or not. If it doesn't just delete file. (Drawback: If it contains e.g. a virus a virus scanner might be triggered ...too bad. I leave handling that up to you.)
public class SignedDataTest {
... see Part 1
private static void verify(Path signedFile, Path extractToFile) throws Exception {
FileInputStream fis = new FileInputStream(signedFile.toFile());
DigestCalculatorProvider build = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build();
CMSSignedDataParser sp = new CMSSignedDataParser(build, fis);
// we have to read the whole stream sp.getSignedContent().getContentStream()
// just copy it to the target file
Files.copy(sp.getSignedContent().getContentStream(), extractToFile, StandardCopyOption.REPLACE_EXISTING);
// now we can go on with the other stuff.....
Store certStore = sp.getCertificates();
// the examples create a new instance of this for each certificate.
// I don't think that's necessary, but you might want to look into that...
JcaSimpleSignerInfoVerifierBuilder verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC");
for (Object objSigner : sp.getSignerInfos().getSigners()) {
SignerInformation signer = (SignerInformation) objSigner;
// as I understand it, there should be only one match ....but anyways....
for (Object objMatch : certStore.getMatches(signer.getSID())) {
X509CertificateHolder certHolder = (X509CertificateHolder) objMatch;
System.out.print("verifying against " + certHolder.getSubject().toString());
if (signer.verify(verifier.build(certHolder))) {
System.out.println(": verified");
} else {
System.out.println(": no match");
}
}
}
}
}
So, what does this actually do/test for? It fetches the signer info from the pkcs7 signedData and then checks the hash and the signature againt the certificates that are contained in the signedData. Not good enough, I and any other attacker can put any certificate in there; so I create a new KeyPiar generate a selfsigned certificate for that key pair and put just any zip file in there I like, preferably a nasty phishing tool.
That's most likely the reason why you've used KeyStore.getInstance("Windows-MY", "SunMSCAPI") in your code; a KeyStore which you implictly trust. So, let's do just that.
Instead of building the SignerInformationVerifier from the data in the signedData file, we pass a ready-made verfier to the method. And this verifier is primed with the certificate from the windows "KeyStore". Btw: you cannot mix the BC and the SunMSCAPI providers arbitrarily; but you can mix them this way, i.e. have BC check the data integrity and SunMSCAPI check whether the hash has been signed by something considered trustworthy.
(sorry, got to go. I'll post just the complete sample class; there's a lot to say about it though ....actually one could write books about that ...actually actually books have been written about that topic ;-) )
public class SignedDataTest {
private static final File KEYSTORE_FILE = new File("c:\\temp\\Software_View_Certificate_Authority.p12");
private static final String KEYSTORE_TYPE = "pkcs12";
private static final char[] KEYSTORE_PWD = "foobar".toCharArray();
private static final String KEYSTORE_ALIAS = "Software View Certificate Authority";
private static final Path CONTENT_SRC_PATH = Paths.get("c:\\temp\\test.txt");
private static final Path CONTENT_TARGET_PATH = Paths.get("c:\\temp\\test-retrieved.txt");
private static final Path SIGNEDDATA_TARGET_PATH = Paths.get("c:\\temp\\test.txt.signed.pkcs7");
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
doForth();
andBack();
}
private static void doForth() throws Exception {
KeyStore ks = KeyStore.getInstance(KEYSTORE_TYPE, "BC");
ks.load(new FileInputStream(KEYSTORE_FILE), KEYSTORE_PWD);
X500PrivateCredential creds = new X500PrivateCredential(
(X509Certificate) ks.getCertificate(KEYSTORE_ALIAS),
(PrivateKey) ks.getKey(KEYSTORE_ALIAS, KEYSTORE_PWD)
);
createSignature(CONTENT_SRC_PATH, creds, new FileOutputStream(SIGNEDDATA_TARGET_PATH.toFile()));
}
private static void andBack() throws Exception {
KeyStore msCertStore = KeyStore.getInstance("Windows-MY", "SunMSCAPI");
msCertStore.load(null, null);
SignerInformationVerifier verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider("SunMSCAPI")
.build(((X509Certificate) msCertStore.getCertificate("Software View Certificate Authority")));
verify(SIGNEDDATA_TARGET_PATH, CONTENT_TARGET_PATH, verifier);
}
private static void verify(Path signedFile, Path extractToFile, SignerInformationVerifier verifier) throws Exception {
FileInputStream fis = new FileInputStream(signedFile.toFile());
DigestCalculatorProvider build = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build();
CMSSignedDataParser sp = new CMSSignedDataParser(build, fis);
// we have to read the whole stream sp.getSignedContent().getContentStream()
// just copy it to the target file
Files.copy(sp.getSignedContent().getContentStream(), extractToFile, StandardCopyOption.REPLACE_EXISTING);
// now we can go on with the other stuff.....
Store certStore = sp.getCertificates();
// the examples create a new instance of this for each certificate.
// I don't think that's necessary, but you might want to look into that...
for (Object objSigner : sp.getSignerInfos().getSigners()) {
SignerInformation signer = (SignerInformation) objSigner;
if (signer.verify(verifier)) {
System.out.println("verified");
// now(!) you want to keep the target content file
} else {
// actually a "org.bouncycastle.cms.CMSSignerDigestMismatchException: message-digest attribute value does not match calculated value"
// exception will be thrown in case the contents has been altered
// So, you will need a try-catch(-finally?) construct to delete the target contents file in such cases....
System.out.println("no match");
}
}
}
private static void createSignature(Path srcfile, X500PrivateCredential creds, FileOutputStream target) throws Exception {
CMSSignedDataStreamGenerator gen = new CMSSignedDataStreamGenerator() {
{
addSignerInfoGenerator(
new JcaSignerInfoGeneratorBuilder(
new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()
).build(
new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(creds.getPrivateKey()),
creds.getCertificate()
)
);
addCertificates(new JcaCertStore(new ArrayList<X509Certificate>() {
{
add(creds.getCertificate());
}
}));
}
};
try (OutputStream sigOut = gen.open(target, true)) {
Files.copy(srcfile, sigOut);
}
}
}
Part 1
Let's start with some transformations of the code. (I wonder how long an answer can be....)
Step 1: Not much going on here; just setting up the "framework" - and as you can see: yes, I'm really running/testing the code ;-)
public class SignedDataTest {
private static final File KEYSTORE_FILE = new File("c:\\temp\\Software_View_Certificate_Authority.p12");
private static final String KEYSTORE_TYPE = "pkcs12";
private static final char[] KEYSTORE_PWD = "foobar".toCharArray();
private static final String KEYSTORE_ALIAS = "Software View Certificate Authority";
private static final Path CONTENT_SRC_PATH = Paths.get("c:\\temp\\Londo Buttons are melting.m4v");
private static final Path CONTENT_TARGET_PATH = Paths.get("c:\\temp\\Londo Buttons are melting-retrieved.m4v");
private static final Path SIGNEDDATA_TARGET_PATH = Paths.get("c:\\temp\\Londo Buttons are melting-retrieved.m4v.signed.pkcs7");
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
createSignature();
}
private static void createSignature() throws Exception {
byte[] fileContent = Files.readAllBytes(CONTENT_SRC_PATH);
KeyStore ks = KeyStore.getInstance(KEYSTORE_TYPE, "BC");
ks.load(new FileInputStream(KEYSTORE_FILE), KEYSTORE_PWD);
Key key = ks.getKey(KEYSTORE_ALIAS, KEYSTORE_PWD);
// Sign
PrivateKey privKey = (PrivateKey)key;
Signature signature = Signature.getInstance("SHA1WithRSA", "BC");
signature.initSign(privKey);
signature.update(fileContent);
// Build CMS
X509Certificate cert = (X509Certificate) ks.getCertificate(KEYSTORE_ALIAS);
List certList = new ArrayList();
CMSTypedData msg = new CMSProcessableByteArray(signature.sign());
certList.add(cert);
Store certs = new JcaCertStore(certList);
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(privKey);
gen.addSignerInfoGenerator(
new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build())
.build(sha1Signer, cert));
gen.addCertificates(certs);
CMSSignedData sigData = gen.generate(msg, true);
BASE64Encoder encoder = new BASE64Encoder();
String signedContent = encoder.encode((byte[]) sigData.getSignedContent().getContent());
System.out.println("Signed content: " + signedContent + "\n");
String envelopedData = encoder.encode(sigData.getEncoded());
System.out.println("Enveloped data: " + envelopedData);
FileOutputStream fos = new FileOutputStream(SIGNEDDATA_TARGET_PATH.toString());
fos.write(envelopedData.getBytes());
fos.close();
}
}
Step 2: This is probably the hardest; the transformation that makes the code look unlike your code the most. Take your time to understand what I'm doing here. I want to get rid of some of the unecessary stuff (e.g. the Base64 encoder) and get a bit more condensed code. This makes debugging a bit harder, since I removed most of the temporary variables, "hiding" them in the initializer block - doh, what's the proper name of that feature?)
public class SignedDataTest {
private static final File KEYSTORE_FILE = new File("c:\\temp\\Software_View_Certificate_Authority.p12");
private static final String KEYSTORE_TYPE = "pkcs12";
private static final char[] KEYSTORE_PWD = "foobar".toCharArray();
private static final String KEYSTORE_ALIAS = "Software View Certificate Authority";
private static final Path CONTENT_SRC_PATH = Paths.get("c:\\temp\\Londo Buttons are melting.m4v");
private static final Path CONTENT_TARGET_PATH = Paths.get("c:\\temp\\Londo Buttons are melting-retrieved.m4v");
private static final Path SIGNEDDATA_TARGET_PATH = Paths.get("c:\\temp\\Londo Buttons are melting-retrieved.m4v.signed.pkcs7");
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
doForth();
// doBack();
}
private static void doForth() throws Exception {
KeyStore ks = KeyStore.getInstance(KEYSTORE_TYPE, "BC");
ks.load(new FileInputStream(KEYSTORE_FILE), KEYSTORE_PWD);
X500PrivateCredential creds = new X500PrivateCredential(
(X509Certificate) ks.getCertificate(KEYSTORE_ALIAS),
(PrivateKey) ks.getKey(KEYSTORE_ALIAS, KEYSTORE_PWD)
);
createSignature(CONTENT_SRC_PATH, creds, new FileOutputStream(SIGNEDDATA_TARGET_PATH.toFile()));
}
private static void createSignature(Path srcfile, X500PrivateCredential creds, FileOutputStream target) throws Exception {
byte[] fileContent = Files.readAllBytes(CONTENT_SRC_PATH);
// Sign
Signature signature = Signature.getInstance("SHA1WithRSA", "BC");
signature.initSign(creds.getPrivateKey());
signature.update(fileContent);
CMSSignedDataGenerator gen = new CMSSignedDataGenerator() {
{
addSignerInfoGenerator(
new JcaSignerInfoGeneratorBuilder(
new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()
).build(
new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(creds.getPrivateKey()),
creds.getCertificate()
)
);
addCertificates(new JcaCertStore(new ArrayList<X509Certificate>() {
{
add(creds.getCertificate());
}
}));
}
};
// Build CMS
CMSTypedData msg = new CMSProcessableByteArray(signature.sign());
CMSSignedData sigData = gen.generate(msg, true);
// write raw data instead of base64
target.write(sigData.getEncoded());
}
}
Step 3: This is probably the most important step: It changes the code from "cannot work as intended on a fundamental level" to "in principle this might work". You're creating a signature manually and then pass that signature to the CMSSignedDataGenerator as the message. In effect you're creating a signature of a signature; the "real" contents is lost. What you actually want to do is create a signature of the (file) contents:
private static void createSignature(Path srcfile, X500PrivateCredential creds, FileOutputStream target) throws Exception {
byte[] fileContent = Files.readAllBytes(CONTENT_SRC_PATH);
CMSSignedDataGenerator gen = new CMSSignedDataGenerator() {
...
};
// Build CMS
CMSTypedData msg = new CMSProcessableByteArray(fileContent);
CMSSignedData sigData = gen.generate(msg, true);
// write raw data instead of base64
target.write(sigData.getEncoded());
}
Step 4: You read the complete contents into memory. That might not be a good idea for a large input file.
private static void createSignature(Path srcfile, X500PrivateCredential creds, FileOutputStream target) throws Exception {
CMSSignedDataGenerator gen = new CMSSignedDataGenerator() {
...
};
// see https://www.bouncycastle.org/docs/pkixdocs1.4/org/bouncycastle/cms/CMSProcessableFile.html
CMSProcessableFile msg = new CMSProcessableFile(srcfile.toFile());
CMSSignedData sigData = gen.generate(msg, true);
// write raw data instead of base64
target.write(sigData.getEncoded());
}
Step 5: Again memory usage: gen.generate(msg, true): The true parameter means that the complete msg is included in the asn1-structure. When you call .getEncoded() you get a byte array of the complete asn1-structure, i.e. you have the complete file in memory again. RAM is cheap, but let's try to avoid that anyway. There's another generator called CMSSignedDataStreamGenerator which seems to offer what we need. Instead of working on byte arrays, you give it an OutputStream it can write the result to, and you get OutputStream you can write the contents to:
private static void createSignature(Path srcfile, X500PrivateCredential creds, FileOutputStream target) throws Exception {
CMSSignedDataStreamGenerator gen = new CMSSignedDataStreamGenerator() {
{
addSignerInfoGenerator(
new JcaSignerInfoGeneratorBuilder(
new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()
).build(
new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(creds.getPrivateKey()),
creds.getCertificate()
)
);
addCertificates(new JcaCertStore(new ArrayList<X509Certificate>() {
{
add(creds.getCertificate());
}
}));
}
};
try (OutputStream sigOut = gen.open(target, true)) {
Files.copy(srcfile, sigOut);
}
}
So much for creating the signed message. I will post the verify-part in another answer - but have to work for real/for a living for a while.....
edit: There's probably still room to post the complete/final sample class
public class SignedDataTest {
private static final File KEYSTORE_FILE = new File("c:\\temp\\Software_View_Certificate_Authority.p12");
private static final String KEYSTORE_TYPE = "pkcs12";
private static final char[] KEYSTORE_PWD = "foobar".toCharArray();
private static final String KEYSTORE_ALIAS = "Software View Certificate Authority";
private static final Path CONTENT_SRC_PATH = Paths.get("c:\\temp\\Londo Buttons are melting.m4v");
private static final Path CONTENT_TARGET_PATH = Paths.get("c:\\temp\\Londo Buttons are melting-retrieved.m4v");
private static final Path SIGNEDDATA_TARGET_PATH = Paths.get("c:\\temp\\Londo Buttons are melting-retrieved.m4v.signed.pkcs7");
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
doForth();
//doBack();
}
private static void doForth() throws Exception {
KeyStore ks = KeyStore.getInstance(KEYSTORE_TYPE, "BC");
ks.load(new FileInputStream(KEYSTORE_FILE), KEYSTORE_PWD);
X500PrivateCredential creds = new X500PrivateCredential(
(X509Certificate) ks.getCertificate(KEYSTORE_ALIAS),
(PrivateKey) ks.getKey(KEYSTORE_ALIAS, KEYSTORE_PWD)
);
createSignature(CONTENT_SRC_PATH, creds, new FileOutputStream(SIGNEDDATA_TARGET_PATH.toFile()));
}
private static void createSignature(Path srcfile, X500PrivateCredential creds, FileOutputStream target) throws Exception {
CMSSignedDataStreamGenerator gen = new CMSSignedDataStreamGenerator() {
{
addSignerInfoGenerator(
new JcaSignerInfoGeneratorBuilder(
new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()
).build(
new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(creds.getPrivateKey()),
creds.getCertificate()
)
);
addCertificates(new JcaCertStore(new ArrayList<X509Certificate>() {
{
add(creds.getCertificate());
}
}));
}
};
try (OutputStream sigOut = gen.open(target, true)) {
Files.copy(srcfile, sigOut);
}
}
}
I am unable to connect the google storage api through java class. any one provide sample code for this
#SuppressWarnings("serial")
public class GoogleServlet {
private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
private static final String PROJECT_ID = "";
public static String Base64Encoding()
throws java.security.SignatureException, UnsupportedEncodingException {
String access_id = "GOOG37E2YNNQW6FIGGDS ";
String secret_key = URLEncoder.encode("","UTF-8");
String bucket = "";
String version_header = "x-goog-api-version:1";
String project_header = "x-goog-project-id:"+PROJECT_ID;
String canonicalizedResources = "/"+bucket+"/";
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, 30);
long expiration = calendar.getTimeInMillis();
String stringToSign = URLEncoder.encode("GET\n\n\n"+expiration+"\n"+version_header+"\n"+project_header+"\n"+canonicalizedResources,"UTF-8");
//String stringToSign = URLEncoder.encode("GET\n\n\n"+getdate()+"\n"+version_header+"\n"+project_header+"\n"+canonicalizedResources,"UTF-8");
String authSignature="";
try {
SecretKeySpec signingKey = new SecretKeySpec(secret_key.getBytes(),HMAC_SHA1_ALGORITHM);
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);
// compute the hmac on input data bytes
byte[] rawHmac = mac.doFinal(stringToSign.getBytes("UTF-8"));
// base64-encode the hmac
authSignature = new String(Base64.encodeBase64(rawHmac));
} catch (Exception e) {
throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
}
authSignature = (access_id +":"+ authSignature);
return authSignature;
}
public static void main(String[] args) {
ClientConfig config = new DefaultClientConfig();-->ClientConfig cannot be resolved to a type
Client client = Client.create(config);
String authSignature = null;
try {
authSignature = "GOOG1 "+ Base64Encoding();
} catch (SignatureException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
WebResource service = client.resource(getBaseURI());
ClientResponse response = service.accept(MediaType.APPLICATION_XML)-->ClientResponse cannot be resolved to a type
.header("Authorization",authSignature)
.header("Date", getdate())
.header("Content-Length", "0")
.header("x-goog-api-version", "1")
.header("x-goog-project-id", PROJECT_ID)
.get(ClientResponse.class);
System.out.println(response.getClientResponseStatus().getFamily());
System.out.println("response1 :: " + response.getEntity(String.class));
}
private static URI getBaseURI() {
String url = "https://storage.cloud.google.com/mss/";
return UriBuilder.fromUri(url).build();--->The method resource(URI) is undefined for the type Client
}
private static String getdate(){
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z ", new Locale("US"));
Calendar cal = Calendar.getInstance(new SimpleTimeZone(0, "GMT"));
format.setCalendar(cal);
return format.format(new Date(0));
}
}
Error:
StringToSign : GET%0A%0A%0A1375378824994%0Ax-goog-api-version%3A1%0Ax-goog-project-id%3A883684764795%0A%2Fmss%2F
Auth Signature : GOOG1 GOOG37E2YNNQW6FIGGDS:3WcA0BQodfq0NrFenFilgJi1tq8=
CLIENT_ERROR
response1 :: <?xml version='1.0' encoding='UTF-8'?><Error><Code>SignatureDoesNotMatch</Code><Message>The request signature we calculated does not match the signature you provided. Check your Google secret key and signing method.</Message><StringToSign>GET
Your secret key is empty:
String secret_key = URLEncoder.encode("","UTF-8");
So signing key is also wrong
SecretKeySpec signingKey = new SecretKeySpec(secret_key.getBytes(),HMAC_SHA1_ALGORITHM);
I need to export/download all files of the other domain users. I used the client login with administer account to see the all files of domain users. however,only document can be export/download,others are fail.
so what is the download url format of the others(For File,pdf,presentation and spreadsheet)??
my document download url is
https://docs.google.com/feeds/download/documents/Export?xoauth_requestor=admin#domain.com&docId=<id>&exportFormat=doc
my program is as following:
public class AuthExample {
private static DocsService docService = new DocsService("Auth Example");
public static void main(String[] args)
throws Exception
{
String adminUser = admin;
String adminPassword = adminpasswd;
String impersonatedUser = "user#domain.com";
docService.setUserCredentials(adminUser, adminPassword);
URL url = new URL( "https://docs.google.com/feeds/" + impersonatedUser + "/private/full");
DocumentListFeed feed = docService.getFeed(url, DocumentListFeed.class);
for (DocumentListEntry entry : feed.getEntries()) {
String title = entry.getTitle().getPlainText();
System.out.println( title );
String type = entry.getType();
if ( type.equals("document") )
{
String encodedAdminUser = URLEncoder.encode(adminUser);
String resourceId = entry.getResourceId();
String resourceIdNoPrefix = resourceId.substring( resourceId.indexOf(':')+1 );
String downloadUrl =
"https://docs.google.com/feeds/download/documents/Export" +
"?xoauth_requestor=" + encodedAdminUser +
"&docId=" + resourceIdNoPrefix +
"&exportFormat=doc";
downloadFile( downloadUrl, title + ".doc" );
}
}
}
// Method pasted directly from Google documentation
public static void downloadFile(String exportUrl, String filepath)
throws IOException, MalformedURLException, ServiceException
{
System.out.println("Exporting document from: " + exportUrl);
MediaContent mc = new MediaContent();
mc.setUri(exportUrl);
MediaSource ms = docService.getMedia(mc);
InputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = ms.getInputStream();
outStream = new FileOutputStream(filepath);
int c;
while ((c = inStream.read()) != -1) {
outStream.write(c);
}
} finally {
if (inStream != null) {
inStream.close();
}
if (outStream != null) {
outStream.flush();
outStream.close();
}
}
}
}
Don't build the download link manually, instead use the entry's content link as explained in the docs:
https://developers.google.com/google-apps/documents-list/#downloading_documents_and_files