-
-
Save kctang/2cfdf66c7f11391ae11b to your computer and use it in GitHub Desktop.
Sample code used to create signed URLs. Gist created to support troubleshooting question at http://stackoverflow.com/questions/19890062/put-files-to-google-cloud-storage-gcs-via-signed-urls.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.apache.commons.codec.binary.Base64; | |
import java.io.FileInputStream; | |
import java.io.IOException; | |
import java.net.URLEncoder; | |
import java.security.KeyStore; | |
import java.security.PrivateKey; | |
import java.security.Signature; | |
import java.security.UnrecoverableKeyException; | |
// http://commons.apache.org/codec/ | |
public class GcsSigner { | |
public static void main(String[] args) throws Exception { | |
// hardcode the values for testing purpose | |
String keyFile = "/mypath/privatekey.p12"; | |
String keyPassword = "notasecret"; | |
String stringToSign = "PUT\n" + | |
"\n" + | |
"text/plain\n" + | |
"1384084959392\n" + | |
"x-goog-api-version:2\n" + | |
"x-goog-project-id:1234\n" + | |
"/test-bucket/bob.txt"; | |
PrivateKey key = loadKeyFromPkcs12(keyFile, keyPassword.toCharArray()); | |
String signature = signData(key, stringToSign); | |
// URL encode signature | |
System.out.println(URLEncoder.encode(signature, "UTF-8")); | |
} | |
private static PrivateKey loadKeyFromPkcs12(String filename, char[] password) throws Exception { | |
FileInputStream fis = new FileInputStream(filename); | |
KeyStore ks = KeyStore.getInstance("PKCS12"); | |
try { | |
ks.load(fis, password); | |
} catch (IOException e) { | |
if (e.getCause() != null && e.getCause() instanceof UnrecoverableKeyException) { | |
System.err.println("Incorrect password"); | |
} | |
throw e; | |
} | |
return (PrivateKey)ks.getKey("privatekey", password); | |
} | |
private static String signData(PrivateKey key, String data) throws Exception { | |
Signature signer = Signature.getInstance("SHA256withRSA"); | |
signer.initSign(key); | |
signer.update(data.getBytes("UTF-8")); | |
byte[] rawSignature = signer.sign(); | |
String encodedSignature = new String(Base64.encodeBase64(rawSignature, false), "UTF-8"); | |
return encodedSignature; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment