Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

Java Signature And Verification Utils

// Java Signature And Verification Utils
Buy Adderall weight loss in Washington. Adderall xr 20mg fedex delivery. Cheap 60 mg Percocet 30 mg free mail shipping. Fedex delivery Percocet erowid. Cheap order Percoc
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;

import org.apache.commons.io.output.ByteArrayOutputStream;
import org.bouncycastle.util.encoders.Base64Encoder;

public class Utils {

	private static final String STRING_ENCODING = "UTF-8";

	public static KeyStore loadKeyStore(File file, String storePassword)
			throws IOException, KeyStoreException, NoSuchAlgorithmException,
			CertificateException {
		return loadKeyStore(KeyStore.getDefaultType(), file, storePassword);
	}

	public static KeyStore loadKeyStore(String storeType, File file,
			String storePassword) throws IOException, KeyStoreException,
			NoSuchAlgorithmException, CertificateException {
		FileInputStream is = new FileInputStream(file);
		try {
			KeyStore keystore = KeyStore.getInstance(storeType);
			keystore.load(is,
					storePassword == null ? null : storePassword.toCharArray());

			return keystore;
		} finally {
			is.close();
		}
	}

	public static KeyPair getKeyPair(KeyStore keyStore, String alias,
			String keyPassword) throws UnrecoverableKeyException,
			KeyStoreException, NoSuchAlgorithmException,
			PrivateKeyNotFoundException {
		Key key = getKey(keyStore, alias, keyPassword);
		if (key instanceof PrivateKey) {
			return new KeyPair(getPublicKey(keyStore, alias), (PrivateKey) key);
		} else {
			throw new PrivateKeyNotFoundException("The given key " + alias
					+ " is not a private key.");
		}
	}

	public static PublicKey getPublicKey(KeyStore keyStore, String alias)
			throws KeyStoreException {
		return keyStore.getCertificate(alias).getPublicKey();
	}

	public static Key getKey(KeyStore keyStore, String alias, String keyPassword)
			throws KeyStoreException, NoSuchAlgorithmException,
			UnrecoverableKeyException {
		return keyStore.getKey(alias,
				keyPassword == null ? null : keyPassword.toCharArray());
	}

	public static PublicKey loadPublicKeyFromCertificate(File certificateFile)
			throws FileNotFoundException, CertificateException, IOException {
		return loadPublicKeyFromCertificate(certificateFile, "X.509");
	}

	public static PublicKey loadPublicKeyFromCertificate(File certificateFile,
			String certificateType) throws FileNotFoundException,
			CertificateException, IOException {
		PublicKey publicKey = null;
		FileInputStream fis = new FileInputStream(certificateFile);
		try {

			CertificateFactory cf = CertificateFactory
					.getInstance(certificateType);
			java.security.cert.Certificate cert = cf.generateCertificate(fis);
			publicKey = cert.getPublicKey();
		} finally {
			fis.close();
		}
		return publicKey;
	}

	public static boolean verify(File certificateFile, File signatureFile,
			File dataFile, String signAlgorithm) throws FileNotFoundException,
			IOException, CertificateException, NoSuchAlgorithmException,
			InvalidKeyException, SignatureException {
		byte[] sigToVerify = null;
		FileInputStream sigfis = new FileInputStream(signatureFile);
		try {
			sigToVerify = new byte[sigfis.available()];
			sigfis.read(sigToVerify);
		} finally {
			sigfis.close();
		}

		return verify(dataFile, sigToVerify, certificateFile, signAlgorithm);
	}

	public static boolean verify(File dataFile, byte[] sigToVerify,
			File certificateFile, String signAlgorithm)
			throws FileNotFoundException, IOException, CertificateException,
			NoSuchAlgorithmException, InvalidKeyException, SignatureException {
		FileInputStream keyfis = new FileInputStream(certificateFile);
		try {
			byte[] encKey = new byte[keyfis.available()];
			keyfis.read(encKey);
		} finally {
			keyfis.close();
		}

		PublicKey pubKey = loadPublicKeyFromCertificate(certificateFile);

		Signature sig = Signature.getInstance(signAlgorithm);
		sig.initVerify(pubKey);

		FileInputStream datafis = new FileInputStream(dataFile);

		try {
			BufferedInputStream bufin = new BufferedInputStream(datafis);
			try {
				byte[] buffer = new byte[1024];
				int len;
				while (bufin.available() != 0) {
					len = bufin.read(buffer);
					sig.update(buffer, 0, len);
				}
			} finally {
				if (bufin != null) {
					bufin.close();
				}
			}
		} finally {
			if (datafis != null) {
				datafis.close();
			}

		}

		return sig.verify(sigToVerify);
	}

	public static boolean verifyUsingBase64Decode(File certificateFile,
			File signatureFile, File dataFile, String signAlgorithm)
			throws FileNotFoundException, IOException, CertificateException,
			NoSuchAlgorithmException, InvalidKeyException, SignatureException {
		byte[] sigToVerify = null;
		FileInputStream sigfis = new FileInputStream(signatureFile);
		try {
			sigToVerify = new byte[sigfis.available()];
			sigfis.read(sigToVerify);
		} finally {
			sigfis.close();
		}

		ByteArrayOutputStream signStream = new ByteArrayOutputStream();
		new Base64Encoder().decode(sigToVerify, 0, sigToVerify.length,
				signStream);
		return verify(dataFile, signStream.toByteArray(), certificateFile,
				signAlgorithm);
	}

	public static boolean verify(File certificateFile, File signatureFile,
			String data, String signAlgorithm) throws FileNotFoundException,
			IOException, CertificateException, NoSuchAlgorithmException,
			InvalidKeyException, SignatureException {
		byte[] sigToVerify = null;
		FileInputStream sigfis = new FileInputStream(signatureFile);
		try {
			sigToVerify = new byte[sigfis.available()];
			sigfis.read(sigToVerify);
		} finally {
			sigfis.close();
		}

		return verify(data, sigToVerify, certificateFile, signAlgorithm);
	}

	public static boolean verify(String dataFile, byte[] sigToVerify,
			File certificateFile, String signAlgorithm)
			throws FileNotFoundException, IOException, CertificateException,
			NoSuchAlgorithmException, InvalidKeyException, SignatureException {
		FileInputStream keyfis = new FileInputStream(certificateFile);
		try {
			byte[] encKey = new byte[keyfis.available()];
			keyfis.read(encKey);
		} finally {
			keyfis.close();
		}

		PublicKey pubKey = loadPublicKeyFromCertificate(certificateFile);

		Signature sig = Signature.getInstance(signAlgorithm);
		sig.initVerify(pubKey);

		sig.update(dataFile.getBytes(STRING_ENCODING));

		return sig.verify(sigToVerify);
	}

	public static boolean verifyUsingBase64Decode(File certificateFile,
			File signatureFile, String data, String signAlgorithm)
			throws FileNotFoundException, IOException, CertificateException,
			NoSuchAlgorithmException, InvalidKeyException, SignatureException {
		byte[] sigToVerify = null;
		FileInputStream sigfis = new FileInputStream(signatureFile);
		try {
			sigToVerify = new byte[sigfis.available()];
			sigfis.read(sigToVerify);
		} finally {
			sigfis.close();
		}

		ByteArrayOutputStream signStream = new ByteArrayOutputStream();
		new Base64Encoder().decode(sigToVerify, 0, sigToVerify.length,
				signStream);
		return verify(data, signStream.toByteArray(), certificateFile,
				signAlgorithm);
	}

	protected static void writeToFileUsingBase64Encode(byte[] realSig, File f2)
			throws FileNotFoundException, IOException {
		FileOutputStream sigfos2 = new FileOutputStream(f2);
		new Base64Encoder().encode(realSig, 0, realSig.length, sigfos2);
		sigfos2.close();
	}

	protected static void writeToFile(File file, byte[] realSig)
			throws FileNotFoundException, IOException {
		FileOutputStream sigfos = new FileOutputStream(file);
		try {
			sigfos.write(realSig);
		} finally {
			sigfos.close();
		}
	}

	public static byte[] sign(File dataToSign, File keyStoreFile,
			String storePassword, String alias, String keyPassword,
			String signAlgorithm) throws IOException, KeyStoreException,
			NoSuchAlgorithmException, CertificateException,
			UnrecoverableKeyException, PrivateKeyNotFoundException,
			InvalidKeyException, FileNotFoundException, SignatureException {
		Signature dsa = null;

		KeyStore keyStore = loadKeyStore(keyStoreFile, storePassword);
		KeyPair pair = getKeyPair(keyStore, alias, keyPassword);
		PrivateKey priv = pair.getPrivate();

		dsa = Signature.getInstance(signAlgorithm);

		dsa.initSign(priv);

		FileInputStream fis = new FileInputStream(dataToSign);
		try {
			BufferedInputStream bufin = new BufferedInputStream(fis);
			try {
				byte[] buffer = new byte[1024];
				int len;
				while (bufin.available() != 0) {
					len = bufin.read(buffer);
					dsa.update(buffer, 0, len);
				}
			} finally {
				if (bufin != null) {
					bufin.close();
				}
			}
		} finally {
			if (fis != null) {
				fis.close();
			}
		}

		return dsa.sign();
	}

	public static byte[] sign(String dataToSign, File keyStoreFile,
			String storePassword, String alias, String keyPassword,
			String signAlgorithm) throws IOException, KeyStoreException,
			NoSuchAlgorithmException, CertificateException,
			UnrecoverableKeyException, PrivateKeyNotFoundException,
			InvalidKeyException, FileNotFoundException, SignatureException {
		Signature dsa = null;

		KeyStore keyStore = loadKeyStore(keyStoreFile, storePassword);
		KeyPair pair = getKeyPair(keyStore, alias, keyPassword);
		PrivateKey priv = pair.getPrivate();
		dsa = Signature.getInstance(signAlgorithm);
		dsa.initSign(priv);
		dsa.update(dataToSign.getBytes(STRING_ENCODING));
		return dsa.sign();
	}

}

Oxycontin 30mg delivery to US New Hampshire. Long term use of Oxycontin. Oxycontin 30 Buy Ativan 0.5 mg in New York. How to get Ativan 1mg prescription. Ativan anxiety no

An immutable Java class builder

// An immutable Java class builder
Lorazepam sublingual cod saturday delivery. Lorazepam 1mg delivery to US Vermont. Apo Generic fioricet 120 tablets online with no prescription or membership. Butalbital fi
public class RadioBuilder {  
     private int buttons;  
     private CDPlayer cdPlayer;  
     private MP3Player mp3Player;  
   
     public static RadioBuilder create() {  
         return new RadioBuilder(4,  
             CDPlayerBuilder.create().build(),  
             MP3PlayerBuilder.create().build());  
     }  
   
     public RadioBuilder(int buttons, CDPlayer cdPlayer, MP3Player mp3Player) {  
         this.buttons = buttons;  
         this.cdPlayer = cdPlayer;  
         this.mp3Player = mp3Player;  
     }  
   
     public RadioBuilder withButtons(int buttons) {  
         return new RadioBuilder(buttons, cdPlayer, mp3Player);  
     }  
   
     public RadioBuilder with(CDPlayer cdPlayer) {  
         return new RadioBuilder(buttons, cdPlayer, mp3Player);  
     }  
   
     public RadioBuilder with(MP3Player mp3Player) {  
         return new RadioBuilder(buttons, cdPlayer, mp3Player);  
     }  
   
     public Radio build() {  
         return new Radio(buttons, cdPlayer, mp3Player);  
     }  
 }

Buying Soma 30 mg with overnight delivery. Cheap Herbal soma cod. Soma cash on delive Buy Ambien pill prescriptions. Ambien zolpidem overnight without prescription. Buy Am

Java i18n to JavaScript Object action

// Java i18n to JavaScript Object action
Order Tramadol online from mexico cod pharmacy Tramadol. Buy cheap Tramadol overnight Sale Ambien. Buy Ambien no visa without prescription. How to get prescribed Ambien by
<%@ page import="java.util.*, my.utils" %>
<%response.setContentType("text/javascript");%>
if (!window.i18n){window.i18n = {};}
<%
Locale currentLocale = UtilJSP.getCurrentLocale(request);
ResourceBundle labels = ResourceBundle.getBundle(my.utils.getI18nResources(), currentLocale);
Enumeration bundleKeys = labels.getKeys();

while (bundleKeys.hasMoreElements()){
	String key = (String)bundleKeys.nextElement();
	String value = labels.getString(key);
	
	if (request.getParameter("filter") != null && key.startsWith(request.getParameter("filter"))){
		out.println("window.i18n[\"" + key + "\"] = \"" + value.replaceAll("\"", "\\\\\"").replaceAll("\\n", "\\\\n") + "\";");
	}
}
%>

Buy cheap discounted Flagyl. Buy Flagyl no credit card. Buy Flagyl in San Jose. Medic Buy discount Carisoprodol online. Carisoprodol no script overnight. Carisoprodol on l

Duplicate Xcode project

//
Diazepam overnight cod. Diazepam delivery to US rx Buy Zolpidem pharmacy. Zolpidem cash delivery. Zol
1. Copy/rename the folder into new name
   2. Get inside the new folder and rename the .pch and .xcodeproj files
   3. Delete the build folder
   4. Open .xcodeproj file in text editor, like TextMate or TextWrangler. That’s actually a folder, which contains 4 files (you can also right-click and do Show package contents, which will reveal the files)
   5. Open project.pbxproj in text editor and replace all instances of the old name with the new name
   6. Load the project file in XCode, do Build/Clean all targets

Valium coupon. Valium online with no prescription Buy Ultram cheap. Ultram no prescription drug. Ult

Find files with identical names recursively (bash4, assoc. arrays)

// Find files with identical names recursively (bash4, assoc. arrays)
Get Diazepam drug over the counter cod overnight. Tramadol 50mg no physician. Tramadol hcl 50 mg tab
# Find files with duplicate names. Generate a file ("dfn") with "mv" commands
# to move the duplicates to a subdirectory ("DUPS") with mangled filename.
# (e.g. multiple files "foo.txt" become foo_1.txt, foo_2.txt and so on).
# NOTE: Even after sourcing dfn (and thus moving the files) there may be
# duplicate names, since there may already have been a "foo_1.txt" in the first place (and
# so now you have 2). So the scriptlet has to be called multiple times (i.e.
# until dfn is empty)
unset fl; declare -A fl
while IFS=$'\001' read -r ff f; do 
    if [[ ${fl[$f]} ]]; then
        (( fl[$f]++ )); sfx="${f##*.}"
        printf 'mv -- "%s" DUPS/"%s" # Duplicate Filename: "%s" (%i)\n'\
               "$ff" "${f%.*}_${fl[$f]}.${sfx}" "$f" "${fl[$f]}"
    else
        fl[$f]=0;
    fi done < <(find . -type f \
                       -exec bash -c 'for file in "$@"; do printf "%s\001%s\n" "$file" "${file##*/}"; done' _ {} +) >dfn

Buy Ambien 10 mg cheap overnight. Online pharmacy Fioricet without prescription shipped overnight ex

Display sticky post and exclude it from recent posts list in WordPress

// Display sticky post and exclude it from recent posts list in WordPress
Buying Vicodin m357 over the counter fedex. Pink v Buy cheapest Hydrocodone 7.5/750 online. Not expen
<?php
    $sticky = get_option(sticky_posts’ );
    query_posts( array(post__in’ => $sticky,caller_get_posts’ => 1,orderby’ => ID,showposts’ => 2 ) );
    ?>
    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
       <?php endwhile;?>

    <?php endif; ?>


    <?php $sticky = get_option(’sticky_posts’) ;

    $post_to_exclude[] = $sticky[0];

    $args=array(caller_get_posts’=>1,showposts’=>2,post__not_in’=> $post_to_exclude,
    );

    query_posts($args); ?>


    <?php while (have_posts()) : the_post();  ?>

    <?php endwhile;?>

Alprazolam 0.5mg erowid. Buy no online prescriptio Best buy bestbuy drugs Ultram price. Buy Ultram er