List of usage examples for javax.crypto Mac getMacLength
public final int getMacLength()
From source file:MainClass.java
public static void main(String[] args) throws Exception { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); SecureRandom random = new SecureRandom(); IvParameterSpec ivSpec = createCtrIvForAES(); Key key = createKeyForAES(256, random); Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC"); String input = "12345678"; Mac mac = Mac.getInstance("DES", "BC"); byte[] macKeyBytes = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; Key macKey = new SecretKeySpec(macKeyBytes, "DES"); cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec); byte[] cipherText = new byte[cipher.getOutputSize(input.length() + mac.getMacLength())]; int ctLength = cipher.update(input.getBytes(), 0, input.length(), cipherText, 0); mac.init(macKey);/*from w w w . java 2 s .c o m*/ mac.update(input.getBytes()); ctLength += cipher.doFinal(mac.doFinal(), 0, mac.getMacLength(), cipherText, ctLength); cipher.init(Cipher.DECRYPT_MODE, key, ivSpec); byte[] plainText = cipher.doFinal(cipherText, 0, ctLength); int messageLength = plainText.length - mac.getMacLength(); mac.init(macKey); mac.update(plainText, 0, messageLength); byte[] messageHash = new byte[mac.getMacLength()]; System.arraycopy(plainText, messageLength, messageHash, 0, messageHash.length); System.out.println("plain : " + new String(plainText) + " verified: " + MessageDigest.isEqual(mac.doFinal(), messageHash)); }
From source file:MainClass.java
public static void main(String[] args) throws Exception { Security.addProvider(new BouncyCastleProvider()); SecureRandom random = new SecureRandom(); IvParameterSpec ivSpec = createCtrIvForAES(1, random); Key key = createKeyForAES(256, random); Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC"); String input = "www.java2s.com"; Mac mac = Mac.getInstance("DES", "BC"); byte[] macKeyBytes = "12345678".getBytes(); Key macKey = new SecretKeySpec(macKeyBytes, "DES"); System.out.println("input : " + input); // encryption step cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec); byte[] cipherText = new byte[cipher.getOutputSize(input.length() + mac.getMacLength())]; int ctLength = cipher.update(input.getBytes(), 0, input.length(), cipherText, 0); mac.init(macKey);/*from ww w . j ava2 s . co m*/ mac.update(input.getBytes()); ctLength += cipher.doFinal(mac.doFinal(), 0, mac.getMacLength(), cipherText, ctLength); System.out.println("cipherText : " + new String(cipherText)); // decryption step cipher.init(Cipher.DECRYPT_MODE, key, ivSpec); byte[] plainText = cipher.doFinal(cipherText, 0, ctLength); int messageLength = plainText.length - mac.getMacLength(); mac.init(macKey); mac.update(plainText, 0, messageLength); byte[] messageHash = new byte[mac.getMacLength()]; System.arraycopy(plainText, messageLength, messageHash, 0, messageHash.length); System.out.println("plain : " + new String(plainText) + " verified: " + MessageDigest.isEqual(mac.doFinal(), messageHash)); }
From source file:Main.java
private static void derivePKCS5S2Helper(Mac hMac, byte[] P, byte[] S, int c, byte[] iBuf, byte[] out, int outOff) throws GeneralSecurityException { byte[] state = new byte[hMac.getMacLength()]; SecretKeySpec param = new SecretKeySpec(P, "SHA1"); hMac.init(param);//w ww . j a v a 2 s .c o m if (S != null) { hMac.update(S, 0, S.length); } hMac.update(iBuf, 0, iBuf.length); hMac.doFinal(state, 0); System.arraycopy(state, 0, out, outOff, state.length); if (c == 0) { throw new IllegalArgumentException("iteration count must be at least 1."); } for (int count = 1; count < c; count++) { hMac.init(param); hMac.update(state, 0, state.length); hMac.doFinal(state, 0); for (int j = 0; j != state.length; j++) { out[outOff + j] ^= state[j]; } } }
From source file:com.otaupdater.utils.Utils.java
public static String hmac(String str, String key) { try {// ww w . jav a 2 s .c om Mac mac = Mac.getInstance(Config.HMAC_ALGORITHM); String salt = randomSaltString(mac.getMacLength()); mac.init(new SecretKeySpec(key.getBytes(), mac.getAlgorithm())); return byteArrToStr(mac.doFinal((salt + str + salt).getBytes("UTF-8"))) + salt; } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:org.apache.nifi.processors.standard.util.crypto.scrypt.Scrypt.java
/** * Implementation of PBKDF2 (RFC2898).// www . j a va2 s. c om * * @param mac the pre-initialized {@link Mac} instance to use * @param s the salt * @param c the iteration count * @param dk the byte array that derived key will be placed in * @param dkLen the intended length, in octets, of the derived key * @throws GeneralSecurityException if the key length is too long */ private static void pbkdf2(Mac mac, byte[] s, int c, byte[] dk, int dkLen) throws GeneralSecurityException { int hLen = mac.getMacLength(); if (dkLen > (Math.pow(2, 32) - 1) * hLen) { throw new GeneralSecurityException("Requested key length too long"); } byte[] U = new byte[hLen]; byte[] T = new byte[hLen]; byte[] block1 = new byte[s.length + 4]; int l = (int) Math.ceil((double) dkLen / hLen); int r = dkLen - (l - 1) * hLen; arraycopy(s, 0, block1, 0, s.length); for (int i = 1; i <= l; i++) { block1[s.length + 0] = (byte) (i >> 24 & 0xff); block1[s.length + 1] = (byte) (i >> 16 & 0xff); block1[s.length + 2] = (byte) (i >> 8 & 0xff); block1[s.length + 3] = (byte) (i >> 0 & 0xff); mac.update(block1); mac.doFinal(U, 0); arraycopy(U, 0, T, 0, hLen); for (int j = 1; j < c; j++) { mac.update(U); mac.doFinal(U, 0); for (int k = 0; k < hLen; k++) { T[k] ^= U[k]; } } arraycopy(T, 0, dk, (i - 1) * hLen, (i == l ? r : hLen)); } }
From source file:org.apache.myfaces.shared_ext202patch.util.StateUtils.java
public static byte[] encrypt(byte[] insecure, ExternalContext ctx) { if (ctx == null) throw new NullPointerException("ExternalContext ctx"); testConfiguration(ctx);//w w w . j a v a 2 s .c o m SecretKey secretKey = (SecretKey) getSecret(ctx); String algorithm = findAlgorithm(ctx); String algorithmParams = findAlgorithmParams(ctx); byte[] iv = findInitializationVector(ctx); SecretKey macSecretKey = (SecretKey) getMacSecret(ctx); String macAlgorithm = findMacAlgorithm(ctx); try { // keep local to avoid threading issue Mac mac = Mac.getInstance(macAlgorithm); mac.init(macSecretKey); Cipher cipher = Cipher.getInstance(algorithm + "/" + algorithmParams); if (iv != null) { IvParameterSpec ivSpec = new IvParameterSpec(iv); cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec); } else { cipher.init(Cipher.ENCRYPT_MODE, secretKey); } if (log.isLoggable(Level.FINE)) { log.fine("encrypting w/ " + algorithm + "/" + algorithmParams); } //EtM Composition Approach int macLenght = mac.getMacLength(); byte[] secure = new byte[cipher.getOutputSize(insecure.length) + macLenght]; int secureCount = cipher.doFinal(insecure, 0, insecure.length, secure); mac.update(secure, 0, secureCount); mac.doFinal(secure, secureCount); return secure; } catch (Exception e) { throw new FacesException(e); } }
From source file:org.apache.myfaces.shared_ext202patch.util.StateUtils.java
public static byte[] decrypt(byte[] secure, ExternalContext ctx) { if (ctx == null) throw new NullPointerException("ExternalContext ctx"); testConfiguration(ctx);/*from www. j av a 2 s .c o m*/ SecretKey secretKey = (SecretKey) getSecret(ctx); String algorithm = findAlgorithm(ctx); String algorithmParams = findAlgorithmParams(ctx); byte[] iv = findInitializationVector(ctx); SecretKey macSecretKey = (SecretKey) getMacSecret(ctx); String macAlgorithm = findMacAlgorithm(ctx); try { // keep local to avoid threading issue Mac mac = Mac.getInstance(macAlgorithm); mac.init(macSecretKey); Cipher cipher = Cipher.getInstance(algorithm + "/" + algorithmParams); if (iv != null) { IvParameterSpec ivSpec = new IvParameterSpec(iv); cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec); } else { cipher.init(Cipher.DECRYPT_MODE, secretKey); } if (log.isLoggable(Level.FINE)) { log.fine("decrypting w/ " + algorithm + "/" + algorithmParams); } //EtM Composition Approach int macLenght = mac.getMacLength(); mac.update(secure, 0, secure.length - macLenght); byte[] signedDigestHash = mac.doFinal(); boolean isMacEqual = true; for (int i = 0; i < signedDigestHash.length; i++) { if (signedDigestHash[i] != secure[secure.length - macLenght + i]) { isMacEqual = false; // MYFACES-2934 Must compare *ALL* bytes of the hash, // otherwise a side-channel timing attack is theorically possible // but with a very very low probability, because the // comparison time is too small to be measured compared to // the overall request time and in real life applications, // there are too many uncertainties involved. //break; } } if (!isMacEqual) { throw new ViewExpiredException(); } return cipher.doFinal(secure, 0, secure.length - macLenght); } catch (Exception e) { throw new FacesException(e); } }
From source file:org.apache.myfaces.shared.util.StateUtils.java
public static byte[] encrypt(byte[] insecure, ExternalContext ctx) { if (ctx == null) { throw new NullPointerException("ExternalContext ctx"); }/* w w w . j a v a 2 s . c o m*/ testConfiguration(ctx); SecretKey secretKey = (SecretKey) getSecret(ctx); String algorithm = findAlgorithm(ctx); String algorithmParams = findAlgorithmParams(ctx); byte[] iv = findInitializationVector(ctx); SecretKey macSecretKey = (SecretKey) getMacSecret(ctx); String macAlgorithm = findMacAlgorithm(ctx); try { // keep local to avoid threading issue Mac mac = Mac.getInstance(macAlgorithm); mac.init(macSecretKey); Cipher cipher = Cipher.getInstance(algorithm + "/" + algorithmParams); if (iv != null) { IvParameterSpec ivSpec = new IvParameterSpec(iv); cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec); } else { cipher.init(Cipher.ENCRYPT_MODE, secretKey); } if (log.isLoggable(Level.FINE)) { log.fine("encrypting w/ " + algorithm + "/" + algorithmParams); } //EtM Composition Approach int macLenght = mac.getMacLength(); byte[] secure = new byte[cipher.getOutputSize(insecure.length) + macLenght]; int secureCount = cipher.doFinal(insecure, 0, insecure.length, secure); mac.update(secure, 0, secureCount); mac.doFinal(secure, secureCount); return secure; } catch (Exception e) { throw new FacesException(e); } }
From source file:org.apache.myfaces.shared.util.StateUtils.java
public static byte[] decrypt(byte[] secure, ExternalContext ctx) { if (ctx == null) { throw new NullPointerException("ExternalContext ctx"); }/*from w w w.j av a2 s. c om*/ testConfiguration(ctx); SecretKey secretKey = (SecretKey) getSecret(ctx); String algorithm = findAlgorithm(ctx); String algorithmParams = findAlgorithmParams(ctx); byte[] iv = findInitializationVector(ctx); SecretKey macSecretKey = (SecretKey) getMacSecret(ctx); String macAlgorithm = findMacAlgorithm(ctx); try { // keep local to avoid threading issue Mac mac = Mac.getInstance(macAlgorithm); mac.init(macSecretKey); Cipher cipher = Cipher.getInstance(algorithm + "/" + algorithmParams); if (iv != null) { IvParameterSpec ivSpec = new IvParameterSpec(iv); cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec); } else { cipher.init(Cipher.DECRYPT_MODE, secretKey); } if (log.isLoggable(Level.FINE)) { log.fine("decrypting w/ " + algorithm + "/" + algorithmParams); } //EtM Composition Approach int macLenght = mac.getMacLength(); mac.update(secure, 0, secure.length - macLenght); byte[] signedDigestHash = mac.doFinal(); boolean isMacEqual = true; for (int i = 0; i < signedDigestHash.length; i++) { if (signedDigestHash[i] != secure[secure.length - macLenght + i]) { isMacEqual = false; // MYFACES-2934 Must compare *ALL* bytes of the hash, // otherwise a side-channel timing attack is theorically possible // but with a very very low probability, because the // comparison time is too small to be measured compared to // the overall request time and in real life applications, // there are too many uncertainties involved. //break; } } if (!isMacEqual) { throw new ViewExpiredException(); } return cipher.doFinal(secure, 0, secure.length - macLenght); } catch (Exception e) { throw new FacesException(e); } }
From source file:uk.ac.ox.webauth.crypto.Des3CbcSha1Kd.java
@Override public ASN1Encodable decrypt(byte[] cipherData) throws IOException, GeneralSecurityException { // derive our decryption and hmac keys as per RFC 3961 // first work out the "well known constant"s for the different keys byte[] wkcKe = new byte[5]; wkcKe[0] = (byte) ((keyUsage >> 24) & 0xFF); wkcKe[1] = (byte) ((keyUsage >> 16) & 0xFF); wkcKe[2] = (byte) ((keyUsage >> 8) & 0xFF); wkcKe[3] = (byte) (keyUsage & 0xFF); wkcKe[4] = (byte) 0xAA; byte[] wkcKi = (byte[]) wkcKe.clone(); wkcKi[4] = (byte) 0x55; // then make the keys // RFC 3961: Derived Key = DK(Base Key, Well-Known Constant) SecretKey ke = new SecretKeySpec(dk(key.getEncoded(), wkcKe), "DESede"); SecretKey ki = new SecretKeySpec(dk(key.getEncoded(), wkcKi), "DESede"); // set up the HMAC object so we can get the length Mac hmacSHA1 = Mac.getInstance("HmacSHA1"); hmacSHA1.init(ki);//from ww w. jav a2s. c om int hmacLength = hmacSHA1.getMacLength(); // first split the checksum off the data InputStream is = new ByteArrayInputStream(cipherData); byte[] data = new byte[cipherData.length - hmacLength]; if (is.read(data) != data.length) { throw new IOException("Couldn't read all the encrypted data."); } byte[] checksum = new byte[hmacLength]; if (is.read(checksum) != checksum.length) { throw new IOException("Couldn't read all the checksum data."); } // then decrypt the data Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding"); cipher.init(DECRYPT_MODE, ke, IV); byte[] decrypted = cipher.doFinal(data); // check the HMAC byte[] newChecksum = hmacSHA1.doFinal(decrypted); if (!Arrays.equals(checksum, newChecksum)) { throw new GeneralSecurityException("Checksum failure."); //System.out.println("Checksum failed."); } // throw away the confounder and then return an ASN.1 encodable object is = new ByteArrayInputStream(decrypted); is.skip(cipher.getBlockSize()); ASN1InputStream ais = new ASN1InputStream(is); return (ASN1Encodable) ais.readObject(); }