Example usage for javax.crypto.spec IvParameterSpec IvParameterSpec

List of usage examples for javax.crypto.spec IvParameterSpec IvParameterSpec

Introduction

In this page you can find the example usage for javax.crypto.spec IvParameterSpec IvParameterSpec.

Prototype

public IvParameterSpec(byte[] iv) 

Source Link

Document

Creates an IvParameterSpec object using the bytes in iv as the IV.

Usage

From source file:compiler.downloader.MegaHandler.java

private String download(String url, String path, boolean verbose) throws NoSuchAlgorithmException,
        NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IOException,
        IllegalBlockSizeException, BadPaddingException, JSONException {
    String[] s = url.split("!");
    String file_id = s[1];//  ww w .j a  va2s . c  o m
    byte[] file_key = MegaCrypt.base64_url_decode_byte(s[2]);

    int[] intKey = MegaCrypt.aByte_to_aInt(file_key);
    JSONObject json = new JSONObject();
    try {
        json.put("a", "g");
        json.put("g", "1");
        json.put("p", file_id);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    JSONObject file_data = new JSONObject(api_request(json.toString()));
    int[] keyNOnce = new int[] { intKey[0] ^ intKey[4], intKey[1] ^ intKey[5], intKey[2] ^ intKey[6],
            intKey[3] ^ intKey[7], intKey[4], intKey[5] };
    byte[] key = MegaCrypt.aInt_to_aByte(keyNOnce[0], keyNOnce[1], keyNOnce[2], keyNOnce[3]);

    int[] iiv = new int[] { keyNOnce[4], keyNOnce[5], 0, 0 };
    byte[] iv = MegaCrypt.aInt_to_aByte(iiv);

    int file_size = file_data.getInt("s");
    String attribs = (file_data.getString("at"));

    attribs = new String(MegaCrypt.aes_cbc_decrypt(MegaCrypt.base64_url_decode_byte(attribs), key));
    //print(attribs.substring(4, attribs.length()));

    String file_name = new JSONObject(attribs.substring(4, attribs.length())).getString("n");
    //print("Filename->>" +file_name);
    final IvParameterSpec ivSpec = new IvParameterSpec(iv);
    final SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance("AES/CTR/nopadding");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec);
    InputStream is = null;
    String file_url = null;
    try {
        file_url = file_data.getString("g");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    FileOutputStream fos = new FileOutputStream(path + File.separator + file_name);
    final OutputStream cos = new CipherOutputStream(fos, cipher);
    final Cipher decipher = Cipher.getInstance("AES/CTR/NoPadding");
    decipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec);
    int read;
    final byte[] buffer = new byte[32767];
    try {
        URLConnection urlConn = new URL(file_url).openConnection();

        ProgressBar bar = new ProgressBar();
        //print(file_url);
        if (verbose) {
            bar.update(0, file_size, "");
        }
        //print("FILESIZE:" +file_size);
        is = urlConn.getInputStream();
        long mDownloaded = 0;
        double current_speed;
        long startTime = System.nanoTime();
        final double NANOS_PER_SECOND = 1000000000.0;
        final double BYTES_PER_MIB = 1024 * 1024;
        while ((read = is.read(buffer, 0, 1024)) > 0) {
            cos.write(buffer, 0, read);
            mDownloaded += read;
            //print(mDownloaded);
            long timeInSecs = (System.nanoTime() - startTime + 1);
            //print("Debug:" + mDownloaded + "/" + timeInSecs);
            current_speed = NANOS_PER_SECOND / BYTES_PER_MIB * mDownloaded / (timeInSecs);
            //print("Speed: "+ (current_speed) + " Mbps");
            if (verbose) {
                bar.update(mDownloaded, file_size, String.format("%.2f", current_speed) + " Mbps");
            }
        }
    } finally {
        try {
            cos.close();
            if (is != null) {
                is.close();
            }
        } finally {
            if (fos != null) {
                fos.close();
            }
        }
    }

    return file_name;
}

From source file:org.opensmartgridplatform.adapter.protocol.dlms.application.services.SecurityKeyService.java

/**
 * Encrypts a new M-Bus User key with the M-Bus Default key for use as M-Bus
 * Client Setup transfer_key parameter.//from w  ww  .j a v a 2 s.  c o m
 * <p>
 * Note that the specifics of the encryption of the M-Bus User key depend on
 * the M-Bus version the devices support. This method should be appropriate
 * for use with DSMR 4 M-Bus devices.
 * <p>
 * The encryption is performed by applying an AES/CBC/NoPadding cipher
 * initialized for encryption with the given mbusDefaultKey and an
 * initialization vector of 16 zero-bytes to the given mbusUserKey.
 *
 * @return the properly wrapped User key for a DSMR 4 M-Bus User key change.
 */
public byte[] encryptMbusUserKey(final byte[] mbusDefaultKey, final byte[] mbusUserKey)
        throws ProtocolAdapterException {

    final Key secretkeySpec = new SecretKeySpec(mbusDefaultKey, "AES");

    try {

        final Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");

        final IvParameterSpec params = new IvParameterSpec(new byte[16]);
        cipher.init(Cipher.ENCRYPT_MODE, secretkeySpec, params);

        return cipher.doFinal(mbusUserKey);

    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
            | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
        final String message = "Error encrypting M-Bus User key with M-Bus Default key for transfer.";
        LOGGER.error(message, e);
        throw new ProtocolAdapterException(message);
    }
}

From source file:com.tremolosecurity.idp.providers.OpenIDConnectIdP.java

private void refreshToken(HttpServletResponse response, String clientID, String clientSecret,
        String refreshToken, UrlHolder holder, HttpServletRequest request, AuthInfo authData)
        throws Exception, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, IOException,
        JoseException, InvalidJwtException, UnsupportedEncodingException {
    Gson gson = new Gson();
    String json = this.inflate(refreshToken);
    Token token = gson.fromJson(json, Token.class);

    byte[] iv = org.bouncycastle.util.encoders.Base64.decode(token.getIv());

    IvParameterSpec spec = new IvParameterSpec(iv);
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, GlobalEntries.getGlobalEntries().getConfigManager()
            .getSecretKey(this.trusts.get(clientID).getCodeLastmileKeyName()), spec);

    byte[] encBytes = org.bouncycastle.util.encoders.Base64.decode(token.getEncryptedRequest());
    String decryptedRefreshToken = new String(cipher.doFinal(encBytes));

    OIDCSession session = this.getSessionByRefreshToken(decryptedRefreshToken);

    if (session == null) {
        logger.warn("Session does not exist from refresh_token");
        AccessLog.log(AccessEvent.AzFail, holder.getApp(), (HttpServletRequest) request, authData, "NONE");
        response.sendError(401);//from  w  ww .j a v a2  s  . co m
        return;
    }

    OpenIDConnectTrust trust = this.trusts.get(session.getClientID());

    if (!trust.isPublicEndpoint()) {
        if (!trust.getClientSecret().equals(clientSecret)) {
            logger.warn("Invalid client_secret");
            AccessLog.log(AccessEvent.AzFail, holder.getApp(), (HttpServletRequest) request, authData, "NONE");
            response.sendError(401);
            return;
        }
    }

    JsonWebSignature jws = new JsonWebSignature();
    jws.setCompactSerialization(session.getIdToken());
    jws.setKey(GlobalEntries.getGlobalEntries().getConfigManager().getCertificate(this.jwtSigningKeyName)
            .getPublicKey());

    if (!jws.verifySignature()) {
        logger.warn("id_token tampered with");
        AccessLog.log(AccessEvent.AzFail, holder.getApp(), (HttpServletRequest) request, authData, "NONE");
        response.sendError(401);
        return;
    }

    JwtClaims claims = JwtClaims.parse(jws.getPayload());

    claims.setGeneratedJwtId(); // a unique identifier for the token
    claims.setIssuedAtToNow(); // when the token was issued/created (now)
    claims.setNotBeforeMinutesInThePast(trusts.get(clientID).getAccessTokenSkewMillis() / 1000 / 60); // time before which the token is not yet valid (2 minutes ago)
    claims.setExpirationTimeMinutesInTheFuture(trusts.get(clientID).getAccessTokenTimeToLive() / 1000 / 60); // time when the token will expire (10 minutes from now)

    jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setKey(GlobalEntries.getGlobalEntries().getConfigManager().getPrivateKey(this.jwtSigningKeyName));
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

    session.setIdToken(jws.getCompactSerialization());

    jws = new JsonWebSignature();
    jws.setKey(GlobalEntries.getGlobalEntries().getConfigManager().getCertificate(this.jwtSigningKeyName)
            .getPublicKey());
    jws.setCompactSerialization(session.getAccessToken());
    if (!jws.verifySignature()) {
        logger.warn("access_token tampered with");
        AccessLog.log(AccessEvent.AzFail, holder.getApp(), (HttpServletRequest) request, authData, "NONE");
        response.sendError(401);
        return;
    }

    claims = JwtClaims.parse(jws.getPayload());

    claims.setGeneratedJwtId(); // a unique identifier for the token
    claims.setIssuedAtToNow(); // when the token was issued/created (now)
    claims.setNotBeforeMinutesInThePast(trusts.get(clientID).getAccessTokenSkewMillis() / 1000 / 60); // time before which the token is not yet valid (2 minutes ago)
    claims.setExpirationTimeMinutesInTheFuture(trusts.get(clientID).getAccessTokenTimeToLive() / 1000 / 60); // time when the token will expire (10 minutes from now)

    jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setKey(GlobalEntries.getGlobalEntries().getConfigManager().getPrivateKey(this.jwtSigningKeyName));
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
    jws.setKeyIdHeaderValue(this.buildKID(
            GlobalEntries.getGlobalEntries().getConfigManager().getCertificate(this.jwtSigningKeyName)));
    session.setAccessToken(jws.getCompactSerialization());

    UUID newRefreshToken = UUID.randomUUID();
    session.setRefreshToken(newRefreshToken.toString());

    String b64 = encryptToken(trusts.get(clientID).getCodeLastmileKeyName(), gson, newRefreshToken);
    session.setEncryptedRefreshToken(b64);

    Session db = null;
    try {
        db = this.sessionFactory.openSession();

        OIDCSession loadSession = db.get(OIDCSession.class, session.getId());

        loadSession.setIdToken(session.getIdToken());
        loadSession.setAccessToken(session.getAccessToken());
        loadSession.setRefreshToken(session.getRefreshToken());
        loadSession.setEncryptedRefreshToken(session.getEncryptedRefreshToken());
        loadSession.setClientID(session.getClientID());
        loadSession.setUserDN(session.getUserDN());

        db.beginTransaction();
        db.save(loadSession);
        db.getTransaction().commit();

    } finally {
        if (db != null) {
            if (db.getTransaction() != null && db.getTransaction().isActive()) {
                db.getTransaction().rollback();
            }
            db.close();
        }
    }

    OpenIDConnectAccessToken access = new OpenIDConnectAccessToken();

    access.setAccess_token(session.getAccessToken());
    access.setExpires_in((int) (trusts.get(clientID).getAccessTokenTimeToLive() / 1000));
    access.setId_token(session.getIdToken());
    access.setToken_type("Bearer");
    access.setRefresh_token(session.getEncryptedRefreshToken());

    json = gson.toJson(access);

    response.setContentType("text/json");
    response.getOutputStream().write(json.getBytes());
    response.getOutputStream().flush();

    AuthInfo remUser = new AuthInfo();
    remUser.setUserDN(session.getUserDN());

    AccessLog.log(AccessEvent.AzSuccess, holder.getApp(), (HttpServletRequest) request, remUser, "NONE");
}

From source file:org.cesecore.util.StringTools.java

public static String pbeEncryptStringWithSha256Aes192(final String in)
        throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException,
        UnsupportedEncodingException {
    CryptoProviderTools.installBCProviderIfNotAvailable();
    if (CryptoProviderTools.isUsingExportableCryptography()) {
        log.warn("Obfuscation not possible due to weak crypto policy.");
        return in;
    }/*from  w  w  w.  j  a va2 s .  com*/
    final Digest digest = new SHA256Digest();

    final PKCS12ParametersGenerator pGen = new PKCS12ParametersGenerator(digest);
    pGen.init(PBEParametersGenerator.PKCS12PasswordToBytes(p), getSalt(), iCount);

    final ParametersWithIV params = (ParametersWithIV) pGen.generateDerivedParameters(192, 128);
    final SecretKeySpec encKey = new SecretKeySpec(((KeyParameter) params.getParameters()).getKey(), "AES");
    final Cipher c;
    c = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
    c.init(Cipher.ENCRYPT_MODE, encKey, new IvParameterSpec(params.getIV()));

    final byte[] enc = c.doFinal(in.getBytes("UTF-8"));

    final byte[] hex = Hex.encode(enc);
    return new String(hex);
}

From source file:com.mastercard.mcbp.utils.crypto.CryptoServiceImpl.java

/**
 * Perform the AES CTR No Padding Encryption and Decryption
 *
 * @param data    The input data to be encrypted / decrypted as byte[]
 * @param iv      The Initialization Vector (IV)
 * @param key     The encryption / decryption key
 * @param mode    True Encryption Mode (ENCRYPT or DECRYPT)
 * @return The encrypted / decrypted data
 *///from w w  w. ja va2  s .c o  m
private static byte[] aesCtrNoPadding(byte[] data, byte[] iv, byte[] key, Mode mode)
        throws McbpCryptoException {
    // Initialize the algorithm
    SecretKey secretKey = new SecretKeySpec(key, "AES");
    IvParameterSpec ivSpec = new IvParameterSpec(iv);
    Cipher cipherCtr;
    try {
        cipherCtr = Cipher.getInstance("AES/CTR/NoPadding");
        if (mode == Mode.ENCRYPT) {
            cipherCtr.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
        } else {
            cipherCtr.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
        }

        return cipherCtr.doFinal(data);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
            | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
        throw new McbpCryptoException(e.getMessage());
    }
}

From source file:com.owncloud.android.utils.EncryptionUtils.java

/**
 * Decrypt private key with symmetric AES encryption, GCM mode mode and no padding
 *
 * @param privateKey byte64 encoded string representation of private key, IV separated with "|"
 * @param keyPhrase  key used for encryption, e.g. 12 random words
 *                   {@link EncryptionUtils#getRandomWords(int, Context)}
 * @return decrypted string//from ww w.j  a v  a 2  s .  com
 */
public static String decryptPrivateKey(String privateKey, String keyPhrase)
        throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException,
        IllegalBlockSizeException, InvalidKeySpecException, InvalidAlgorithmParameterException {

    // split up iv, salt
    String[] strings = privateKey.split(ivDelimiter);
    String realPrivateKey = strings[0];
    byte[] iv = decodeStringToBase64Bytes(strings[1]);
    byte[] salt = decodeStringToBase64Bytes(strings[2]);

    Cipher cipher = Cipher.getInstance(AES_CIPHER);
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec spec = new PBEKeySpec(keyPhrase.toCharArray(), salt, iterationCount, keyStrength);
    SecretKey tmp = factory.generateSecret(spec);
    SecretKeySpec key = new SecretKeySpec(tmp.getEncoded(), AES);

    cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));

    byte[] bytes = decodeStringToBase64Bytes(realPrivateKey);
    byte[] decrypted = cipher.doFinal(bytes);

    String pemKey = decodeBase64BytesToString(decrypted);

    return pemKey.replaceAll("\n", "").replace("-----BEGIN PRIVATE KEY-----", "")
            .replace("-----END PRIVATE KEY-----", "");
}

From source file:com.goodhustle.ouyaunitybridge.OuyaUnityActivity.java

public void requestPurchase(final String productId)
        throws GeneralSecurityException, UnsupportedEncodingException, JSONException {
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

    // This is an ID that allows you to associate a successful purchase with
    // it's original request. The server does nothing with this string except
    // pass it back to you, so it only needs to be unique within this instance
    // of your app to allow you to pair responses with requests.
    String uniqueId = Long.toHexString(sr.nextLong());
    JSONObject purchaseRequest = new JSONObject();
    purchaseRequest.put("uuid", uniqueId);
    purchaseRequest.put("identifier", productId);
    purchaseRequest.put("testing", "true"); // This value is only needed for testing, not setting it results in a live purchase
    String purchaseRequestJson = purchaseRequest.toString();
    byte[] keyBytes = new byte[16];
    sr.nextBytes(keyBytes);/*w w  w .  ja v a 2 s.c o m*/
    SecretKey key = new SecretKeySpec(keyBytes, "AES");
    byte[] ivBytes = new byte[16];
    sr.nextBytes(ivBytes);
    IvParameterSpec iv = new IvParameterSpec(ivBytes);
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, key, iv);
    byte[] payload = cipher.doFinal(purchaseRequestJson.getBytes("UTF-8"));
    cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, mPublicKey);
    byte[] encryptedKey = cipher.doFinal(keyBytes);
    Purchasable purchasable = new Purchasable(productId, Base64.encodeToString(encryptedKey, Base64.NO_WRAP),
            Base64.encodeToString(ivBytes, Base64.NO_WRAP), Base64.encodeToString(payload, Base64.NO_WRAP));
    synchronized (mOutstandingPurchaseRequests) {
        mOutstandingPurchaseRequests.put(uniqueId, productId);
    }
    ouyaFacade.requestPurchase(purchasable, new PurchaseListener(productId));
}

From source file:org.structr.util.StructrLicenseManager.java

private byte[] encryptData(final byte[] data, final SecretKey sessionKey, final byte[] ivSpec)
        throws NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, InvalidKeyException,
        BadPaddingException, UnsupportedEncodingException, InvalidAlgorithmParameterException {

    // setup//from  w ww.j  a  va2  s  .com
    final Cipher cipher = Cipher.getInstance(DataEncryptionAlgorithm);

    cipher.init(Cipher.ENCRYPT_MODE, sessionKey, new IvParameterSpec(ivSpec));

    return cipher.doFinal(data);
}

From source file:org.apache.pdfbox.pdmodel.encryption.StandardSecurityHandler.java

private byte[] computeEncryptedKeyRev56(byte[] password, boolean isOwnerPassword, byte[] o, byte[] u, byte[] oe,
        byte[] ue, int encRevision) throws IOException {
    byte[] hash, fileKeyEnc;

    if (isOwnerPassword) {
        byte[] oKeySalt = new byte[8];
        System.arraycopy(o, 40, oKeySalt, 0, 8);

        if (encRevision == 5) {
            hash = computeSHA256(password, oKeySalt, u);
        } else {//from  w  w w  .  j a  v a  2s.  com
            hash = computeHash2A(password, oKeySalt, u);
        }

        fileKeyEnc = oe;
    } else {
        byte[] uKeySalt = new byte[8];
        System.arraycopy(u, 40, uKeySalt, 0, 8);

        if (encRevision == 5) {
            hash = computeSHA256(password, uKeySalt, null);
        } else {
            hash = computeHash2A(password, uKeySalt, null);
        }

        fileKeyEnc = ue;
    }
    try {
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(hash, "AES"), new IvParameterSpec(new byte[16]));
        return cipher.doFinal(fileKeyEnc);
    } catch (GeneralSecurityException e) {
        logIfStrongEncryptionMissing();
        throw new IOException(e);
    }
}

From source file:cn.ctyun.amazonaws.services.s3.internal.crypto.EncryptionUtils.java

/**
 * Creates a symmetric cipher in the specified mode from the given symmetric key and IV.  The given
 * crypto provider will provide the encryption implementation.  If the crypto provider is null, then
 * the default JCE crypto provider will be used.
 *//*  w  w  w . j  a va2  s.c o  m*/
public static Cipher createSymmetricCipher(SecretKey symmetricCryptoKey, int encryptMode,
        Provider cryptoProvider, byte[] initVector) {
    try {
        Cipher cipher;
        if (cryptoProvider != null) {
            cipher = Cipher.getInstance(JceEncryptionConstants.SYMMETRIC_CIPHER_METHOD, cryptoProvider);
        } else {
            cipher = Cipher.getInstance(JceEncryptionConstants.SYMMETRIC_CIPHER_METHOD);
        }
        if (initVector != null) {
            cipher.init(encryptMode, symmetricCryptoKey, new IvParameterSpec(initVector));
        } else {
            cipher.init(encryptMode, symmetricCryptoKey);
        }
        return cipher;
    } catch (Exception e) {
        throw new AmazonClientException("Unable to build cipher: " + e.getMessage()
                + "\nMake sure you have the JCE unlimited strength policy files installed and "
                + "configured for your JVM: http://www.ngs.ac.uk/tools/jcepolicyfiles", e);
    }
}