Created
October 26, 2012 18:50
-
-
Save saltnlight5/3960666 to your computer and use it in GitHub Desktop.
security.groovy
This file contains hidden or 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
// http://docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html | |
// MessageDisgest | |
// - Take input text/bytes and produce a fixe length digest | |
// - MD5, MD2, msgDigest-1 | |
// | |
// Cipher | |
// - Take cleartext text and key and produce a ciphertext | |
// - Symmetric uses secret key (fast): DES, 3DES are fixed key length | |
// - Asysmmetric uses public/private key (slow): AES, RSA are variable length | |
// | |
// Print list of all available algorithms from providers | |
//java.security.Security.providers.each{p->p.getServices().each{s->println s}} | |
/*// MessageDigest example | |
import java.security.* | |
def msgDigest = MessageDigest.getInstance("MD5") | |
def inputBytes = "Hello World!".getBytes("UTF-8") | |
msgDigest.update(inputBytes) | |
def hashBytes = msgDigest.digest(); | |
hashBytes.each{b->printf("%X",b)} | |
println()*/ | |
/*// KeyStore examples | |
import java.security.* | |
def certFilename = System.getProperty("java.home") + "/lib/security/cacerts" | |
def password = "changeit" | |
def keyStore = KeyStore.getInstance("JKS") | |
new File(certFilename).withInputStream{inStream-> | |
keyStore.load(inStream, password.toCharArray()) | |
} | |
// // Print all keyStore alias | |
// keyStore.aliases().sort().each{a-> | |
// def isCert = keyStore.isCertificateEntry(a) | |
// def isKey = keyStore.isKeyEntry(a) | |
// println "$a, cert=$isCert, key=$isKey" | |
// } | |
// Get Key or Cert | |
//def key = keyStore.getKey("mykey", password.toCharArray()) | |
def cert = keyStore.getCertificate("verisignuniversalrootca") | |
println cert*/ | |
// Cipher example - using custom secret key | |
import java.security.* | |
import javax.crypto.* | |
import javax.crypto.spec.* | |
def input = "Hello World!" | |
def secretBytes = "salt and light".getBytes("UTF-8") | |
def sha = MessageDigest.getInstance("SHA-1") | |
def keyBytes = sha.digest(secretBytes) | |
keyBytes = Arrays.copyOf(keyBytes, 16) // use only first 128 bit | |
def secretKey = new SecretKeySpec(keyBytes, "AES") // or DESede (keySize=24, padSize=8) | |
// param=transformation => "algorithm/mode/padding" or "algorithm" | |
def cipher = Cipher.getInstance("AES/ECB/NoPadding") | |
cipher.init(Cipher.ENCRYPT_MODE, secretKey) | |
def padSize = 16 | |
def cipherLen = input.length() % padSize | |
input = input + (" " * (padSize - cipherLen)) | |
def cipherBytes = cipher.doFinal(input.getBytes("UTF-8")) | |
cipherBytes.each{b->printf("%X",b)} | |
println() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment