Ejemplo n.º 1
0
  /** This encryption/decryption code doesn't match outputs with the Python code. It needs fixed. */
  public byte[] encrypt(String input) {
    byte[] encryptedBytes;
    try {
      SecretKeySpec key = generatekey();
      // Cipher encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      Cipher encryptCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
      encryptCipher.init(Cipher.ENCRYPT_MODE, key);
      iv = encryptCipher.getIV();
      // Encrypt
      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
      CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, encryptCipher);
      cipherOutputStream.write(input.getBytes());
      cipherOutputStream.flush();
      cipherOutputStream.close();
      encryptedBytes = outputStream.toByteArray();
      outputStream.close();
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    } catch (NoSuchPaddingException e) {
      e.printStackTrace();
      return null;
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      return null;
    } catch (InvalidKeyException e) {
      e.printStackTrace();
      return null;
    }

    return encryptedBytes;
  }
  /* (non-Javadoc)
   * @see com.amazonaws.services.s3.AmazonS3Client#initiateMultipartUpload(com.amazonaws.services.s3.model.InitiateMultipartUploadRequest)
   */
  @Override
  public InitiateMultipartUploadResult initiateMultipartUpload(
      InitiateMultipartUploadRequest initiateMultipartUploadRequest)
      throws AmazonClientException, AmazonServiceException {

    appendUserAgent(initiateMultipartUploadRequest, USER_AGENT);

    // Generate a one-time use symmetric key and initialize a cipher to encrypt object data
    SecretKey envelopeSymmetricKey = EncryptionUtils.generateOneTimeUseSymmetricKey();
    Cipher symmetricCipher =
        EncryptionUtils.createSymmetricCipher(
            envelopeSymmetricKey, Cipher.ENCRYPT_MODE, cryptoConfig.getCryptoProvider(), null);

    if (cryptoConfig.getStorageMode() == CryptoStorageMode.ObjectMetadata) {
      EncryptionMaterials encryptionMaterials =
          encryptionMaterialsProvider.getEncryptionMaterials();
      // Encrypt the envelope symmetric key
      byte[] encryptedEnvelopeSymmetricKey =
          EncryptionUtils.getEncryptedSymmetricKey(
              envelopeSymmetricKey, encryptionMaterials, cryptoConfig.getCryptoProvider());

      // Store encryption info in metadata
      ObjectMetadata metadata =
          EncryptionUtils.updateMetadataWithEncryptionInfo(
              initiateMultipartUploadRequest,
              encryptedEnvelopeSymmetricKey,
              symmetricCipher,
              encryptionMaterials.getMaterialsDescription());

      // Update the request's metadata to the updated metadata
      initiateMultipartUploadRequest.setObjectMetadata(metadata);
    }

    InitiateMultipartUploadResult result =
        super.initiateMultipartUpload(initiateMultipartUploadRequest);
    EncryptedUploadContext encryptedUploadContext =
        new EncryptedUploadContext(
            initiateMultipartUploadRequest.getBucketName(),
            initiateMultipartUploadRequest.getKey(),
            envelopeSymmetricKey);
    encryptedUploadContext.setNextInitializationVector(symmetricCipher.getIV());
    encryptedUploadContext.setFirstInitializationVector(symmetricCipher.getIV());
    currentMultipartUploadSecretKeys.put(result.getUploadId(), encryptedUploadContext);

    return result;
  }
Ejemplo n.º 3
0
  private void runTest(String name) throws Exception {
    String lCode = "ABCDEFGHIJKLMNOPQRSTUVWXY0123456789";
    KeyGenerator kGen;

    if (name.indexOf('/') < 0) {
      kGen = KeyGenerator.getInstance(name, "BC");
    } else {
      kGen = KeyGenerator.getInstance(name.substring(0, name.indexOf('/')), "BC");
    }

    Cipher in = Cipher.getInstance(name, "BC");
    Cipher out = Cipher.getInstance(name, "BC");
    Key key = kGen.generateKey();
    ByteArrayInputStream bIn = new ByteArrayInputStream(lCode.getBytes());
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();

    in.init(Cipher.ENCRYPT_MODE, key);
    if (in.getIV() != null) {
      out.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(in.getIV()));
    } else {
      out.init(Cipher.DECRYPT_MODE, key);
    }

    CipherInputStream cIn = new CipherInputStream(bIn, in);
    CipherOutputStream cOut = new CipherOutputStream(bOut, out);

    int c;

    while ((c = cIn.read()) >= 0) {
      cOut.write(c);
    }

    cIn.close();

    cOut.flush();
    cOut.close();

    String res = new String(bOut.toByteArray());

    if (!res.equals(lCode)) {
      fail("Failed - decrypted data doesn't match.");
    }
  }
Ejemplo n.º 4
0
 public byte[] encrypt(byte[] str) {
   try {
     c.init(Cipher.ENCRYPT_MODE, key);
     byte encrypted[] = c.doFinal(str);
     iv = c.getIV();
     return encrypted;
   } catch (Exception e) {
     e.printStackTrace();
   }
   return null;
 }
Ejemplo n.º 5
0
  private byte[] getEncryptedBody(Cipher cipher, byte[] body)
      throws IllegalBlockSizeException, BadPaddingException {
    byte[] encrypted = cipher.doFinal(body);
    byte[] iv = cipher.getIV();

    byte[] ivAndBody = new byte[iv.length + encrypted.length];
    System.arraycopy(iv, 0, ivAndBody, 0, iv.length);
    System.arraycopy(encrypted, 0, ivAndBody, iv.length, encrypted.length);

    return ivAndBody;
  }
Ejemplo n.º 6
0
  public String[] encrypt(String value) throws Exception {
    try {
      KeyGenerator kgen = KeyGenerator.getInstance("AES");
      SecureRandom sran = new SecureRandom();

      kgen.init(128, sran);

      SecretKey skey = kgen.generateKey();
      byte[] raw = skey.getEncoded();

      String key = asHex(raw);

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

      IvParameterSpec ivSpec = createCtrIvForAES(1, sran);

      cipher.init(Cipher.ENCRYPT_MODE, skey, ivSpec);

      byte[] encrypted = cipher.doFinal(padWithZeros(value.getBytes()));

      String vector = asHex(cipher.getIV());

      String encryptedValue = asHex(encrypted);

      return new String[] {encryptedValue, key, vector};

    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();

      throw new Exception("Encrypt error!", e);
    } catch (NoSuchPaddingException e) {
      e.printStackTrace();

      throw new Exception("Encrypt error!", e);
    } catch (InvalidKeyException e) {
      e.printStackTrace();

      throw new Exception("Encrypt error!", e);
    } catch (IllegalBlockSizeException e) {
      e.printStackTrace();

      throw new Exception("Encrypt error!", e);
    } catch (BadPaddingException e) {
      e.printStackTrace();

      throw new Exception("Encrypt error!", e);
    } catch (InvalidAlgorithmParameterException e) {
      e.printStackTrace();

      throw new Exception("Encrypt error!", e);
    }
  }
Ejemplo n.º 7
0
  private static byte[] testParams(AlgorithmParameters rc2Params, RC2ParameterSpec rc2Spec)
      throws Exception {

    // test getParameterSpec returns object equal to input
    rc2Params.init(rc2Spec);
    RC2ParameterSpec rc2OtherSpec =
        (RC2ParameterSpec) rc2Params.getParameterSpec(RC2ParameterSpec.class);
    if (!rc2Spec.equals(rc2OtherSpec)) {
      throw new Exception("AlgorithmParameterSpecs should be equal");
    }

    // test RC2ParameterSpec with RC2 Cipher
    Cipher rc2Cipher = Cipher.getInstance("RC2/CBC/PKCS5PADDING", "SunJCE");
    rc2Cipher.init(
        Cipher.ENCRYPT_MODE, new SecretKeySpec("secret".getBytes("ASCII"), "RC2"), rc2Spec);

    // get IV
    byte[] iv = rc2Cipher.getIV();
    if (!Arrays.equals(iv, rc2Spec.getIV())) {
      throw new Exception("ivs should be equal");
    }

    // test encoding and decoding
    byte[] encoded = rc2Params.getEncoded();
    AlgorithmParameters params = AlgorithmParameters.getInstance("RC2");
    params.init(encoded);

    // test RC2 AlgorithmParameters with RC2 Cipher
    rc2Cipher.init(
        Cipher.ENCRYPT_MODE, new SecretKeySpec("secret".getBytes("ASCII"), "RC2"), params);

    // get IV
    iv = rc2Cipher.getIV();
    if (!Arrays.equals(iv, rc2Spec.getIV())) {
      throw new Exception("ivs should be equal");
    }
    return encoded;
  }
Ejemplo n.º 8
0
  private void testGCMGeneric(byte[] K, byte[] N, byte[] A, byte[] P, byte[] C)
      throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException,
          IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException,
          NoSuchProviderException, IOException, InvalidParameterSpecException {
    Cipher eax = Cipher.getInstance("AES/GCM/NoPadding", "BC");
    SecretKeySpec key = new SecretKeySpec(K, "AES");

    // GCMParameterSpec mapped to AEADParameters and overrides default MAC
    // size
    GCMParameterSpec spec = new GCMParameterSpec(128, N);
    eax.init(Cipher.ENCRYPT_MODE, key, spec);

    eax.updateAAD(A);
    byte[] c = eax.doFinal(P);

    if (!areEqual(C, c)) {
      fail("JCE encrypt with additional data and GCMParameterSpec failed.");
    }

    eax = Cipher.getInstance("GCM", "BC");
    eax.init(Cipher.DECRYPT_MODE, key, spec);
    eax.updateAAD(A);
    byte[] p = eax.doFinal(C);

    if (!areEqual(P, p)) {
      fail("JCE decrypt with additional data and GCMParameterSpec failed.");
    }

    AlgorithmParameters algParams = eax.getParameters();

    byte[] encParams = algParams.getEncoded();

    GCMParameters gcmParameters = GCMParameters.getInstance(encParams);

    if (!Arrays.areEqual(spec.getIV(), gcmParameters.getNonce())
        || spec.getTLen() != gcmParameters.getIcvLen()) {
      fail("parameters mismatch");
    }

    GCMParameterSpec gcmSpec = algParams.getParameterSpec(GCMParameterSpec.class);

    if (!Arrays.areEqual(gcmSpec.getIV(), gcmParameters.getNonce())
        || gcmSpec.getTLen() != gcmParameters.getIcvLen() * 8) {
      fail("spec parameters mismatch");
    }

    if (!Arrays.areEqual(eax.getIV(), gcmParameters.getNonce())) {
      fail("iv mismatch");
    }
  }
Ejemplo n.º 9
0
  public String encrypt(String plainText, String _key)
      throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
          InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
          InvalidAlgorithmParameterException {

    byte[] keybytes = Base64.decodeBase64(_key);
    Key key = new SecretKeySpec(keybytes, "AES");

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, key);

    String iv = Base64.encodeBase64String(cipher.getIV());

    byte[] encMsg = cipher.doFinal(plainText.getBytes());
    return iv + delim + Base64.encodeBase64String(encMsg);
  }
Ejemplo n.º 10
0
  public EncryptedMessage(byte[]... bytes) throws Exception {
    final KeyGenerator kGen = KeyGenerator.getInstance("AES");
    kGen.init(128);

    encryptedBytes = new byte[bytes.length][];
    SecretKey key = kGen.generateKey();
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    SecretKeySpec kSpec;
    aeskey = key.getEncoded();
    kSpec = new SecretKeySpec(aeskey, "AES/CBC/PKCS5Padding");

    cipher.init(Cipher.ENCRYPT_MODE, kSpec);
    iv = cipher.getIV();
    for (int i = 0; i < bytes.length; i++) {
      encryptedBytes[i] = cipher.doFinal(bytes[i]);
    }
  }
Ejemplo n.º 11
0
  /**
   * Generates a random IV and encrypts this plain text with the given key. Then attaches a hashed
   * MAC, which is contained in the CipherTextIvMac class.
   *
   * @param plaintext The text that will be encrypted
   * @param secretKeys The combined AES & HMAC keys with which to encrypt
   * @return a tuple of the IV, ciphertext, mac
   * @throws GeneralSecurityException if AES is not implemented on this system
   */
  public static CipherTextIvMac encrypt(byte[] plaintext, SecretKeys secretKeys)
      throws GeneralSecurityException {
    byte[] iv = generateIv();
    Cipher aesCipherForEncryption = Cipher.getInstance(CIPHER_TRANSFORMATION);
    aesCipherForEncryption.init(
        Cipher.ENCRYPT_MODE, secretKeys.getConfidentialityKey(), new IvParameterSpec(iv));

    /*
     * Now we get back the IV that will actually be used. Some Android
     * versions do funny stuff w/ the IV, so this is to work around bugs:
     */
    iv = aesCipherForEncryption.getIV();
    byte[] byteCipherText = aesCipherForEncryption.doFinal(plaintext);
    byte[] ivCipherConcat = CipherTextIvMac.ivCipherConcat(iv, byteCipherText);

    byte[] integrityMac = generateMac(ivCipherConcat, secretKeys.getIntegrityKey());
    return new CipherTextIvMac(byteCipherText, iv, integrityMac);
  }
Ejemplo n.º 12
0
  /** @deprecated no longer used and will be removed in the future */
  @Deprecated
  private static void updateMetadata(
      ObjectMetadata metadata,
      byte[] keyBytesToStoreInMetadata,
      Cipher symmetricCipher,
      Map<String, String> materialsDescription) {
    // If we generated a symmetric key to encrypt the data, store it in the object metadata.
    if (keyBytesToStoreInMetadata != null) {
      metadata.addUserMetadata(
          Headers.CRYPTO_KEY, Base64.encodeAsString(keyBytesToStoreInMetadata));
    }

    // Put the cipher initialization vector (IV) into the object metadata
    metadata.addUserMetadata(Headers.CRYPTO_IV, Base64.encodeAsString(symmetricCipher.getIV()));

    // Put the materials description into the object metadata as JSON
    JSONObject descriptionJSON = new JSONObject(materialsDescription);
    metadata.addUserMetadata(Headers.MATERIALS_DESCRIPTION, descriptionJSON.toString());
  }
Ejemplo n.º 13
0
  public static void encryptPassword(String password) throws Exception {
    KeyGenerator kg = KeyGenerator.getInstance("DES");
    kg.init(new SecureRandom());
    SecretKey key = kg.generateKey();
    SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
    Class spec = Class.forName("javax.crypto.spec.DESKeySpec");
    DESKeySpec ks = (DESKeySpec) skf.getKeySpec(key, spec);
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("keyfile"));
    oos.writeObject(ks.getKey());

    Cipher c = Cipher.getInstance("DES/CFB8/NoPadding");
    c.init(Cipher.ENCRYPT_MODE, key);
    CipherOutputStream cos = new CipherOutputStream(new FileOutputStream("ciphertext"), c);
    PrintWriter pw = new PrintWriter(new OutputStreamWriter(cos));
    pw.println(password);
    pw.close();
    oos.writeObject(c.getIV());
    oos.close();
  }
  /**
   * @tests javax.crypto.Cipher#getIV()
   * @tests javax.crypto.Cipher#init(int, java.security.Key, java.security.AlgorithmParameters)
   */
  public void test_getIV() throws Exception {
    /*
     * If this test is changed, implement the following:
     * test_initILjava_security_KeyLjava_security_AlgorithmParameters()
     */

    SecureRandom sr = new SecureRandom();
    Cipher cipher = null;

    byte[] iv = new byte[8];
    sr.nextBytes(iv);
    AlgorithmParameters ap = AlgorithmParameters.getInstance(algorithm);
    ap.init(iv, "RAW");

    cipher = Cipher.getInstance(algorithm + "/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, cipherKey, ap);

    byte[] cipherIV = cipher.getIV();

    assertTrue("IVs differ", Arrays.equals(cipherIV, iv));
  }
  public static void main(String[] args) throws Exception {

    Security.addProvider(new BouncyCastleProvider());

    String keyString = "12c4U05:)a201i5iya2A";
    String messageString =
        "And the band begins to play... We all live in a yellow submarine yellow submarine";

    byte[] keyBytes = keyString.getBytes(Charset.forName("UTF-8"));
    System.out.println(keyBytes.length);
    byte[] messageBytes = messageString.getBytes(Charset.forName("UTF-8"));

    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec spec = new PBEKeySpec(keyString.toCharArray(), "123456789".getBytes(), 4096, 128);
    SecretKey tmp = factory.generateSecret(spec);
    SecretKey key = new SecretKeySpec(tmp.getEncoded(), "AES");

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");

    System.out.println("input text : " + messageString);

    // encryption pass
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] ciphertext = cipher.doFinal(messageBytes);
    byte[] iv = cipher.getIV();
    System.out.println("iv :" + Utils.toHex(iv));
    System.out.println("cipher text: " + Utils.toHex(ciphertext) + " bytes: " + ciphertext.length);

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

    //		String bla = "a2838036d47ec016d112916f10ff21b2e6da27c68e8a3f64835e08f2f4290fa8";
    //		byte[] test = DatatypeConverter.parseHexBinary(bla);
    //
    //		byte[] plaintext = cipher.doFinal(test);
    byte[] plaintext = cipher.doFinal(ciphertext);

    System.out.println("plain text : " + new String(plaintext) + " bytes: " + plaintext.length);
  }
Ejemplo n.º 16
0
  @Override
  public void run() {

    ChukasaModel chukasaModel = chukasaModelManagementComponent.get(adaptiveBitrateStreaming);
    String streamPath = chukasaModel.getStreamPath();
    String tempEncPath = chukasaModel.getTempEncPath();
    int tsPacketLength = chukasaModel.getHlsConfiguration().getMpeg2TsPacketLength();

    int seqTsEnc = 0; // getSeqTsEnc();
    seqTsEnc = chukasaModel.getSeqTsEnc();
    if (chukasaModel.getChukasaSettings().getStreamingType() == StreamingType.OKKAKE) {
      seqTsEnc = chukasaModel.getSeqTsOkkake() - 1;
    }
    if (chukasaModel.isFlagLastTs()) {
      seqTsEnc = chukasaModel.getSeqTsLast();
    }

    Key sKey;
    Cipher c;
    FileOutputStream keyOut;
    FileWriter ivOut;
    FileInputStream fis;
    BufferedInputStream bis;
    FileOutputStream fos;
    CipherOutputStream cos;

    try {
      Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

      sKey = makeKey(128); // Key length is 128bit
      c = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");

      c.init(Cipher.ENCRYPT_MODE, sKey);

      // Set Key File Name at random
      String keyPre = RandomStringUtils.randomAlphabetic(10);
      keyOut = new FileOutputStream(streamPath + FILE_SEPARATOR + keyPre + seqTsEnc + ".key");

      chukasaModel.getKeyArrayList().add(keyPre);
      chukasaModel = chukasaModelManagementComponent.update(adaptiveBitrateStreaming, chukasaModel);

      byte[] keyOutByte = sKey.getEncoded();
      keyOut.write(keyOutByte);
      keyOut.close();

      byte[] iv = c.getIV();

      String ivHex = "";
      for (int i = 0; i < iv.length; i++) {
        String ivHexTmp = String.format("%02x", iv[i]).toUpperCase();
        ivHex = ivHex + ivHexTmp;
      }

      String ivPre = RandomStringUtils.randomAlphabetic(10);
      ivOut = new FileWriter(streamPath + FILE_SEPARATOR + ivPre + seqTsEnc + ".iv");
      ivOut.write(ivHex);
      ivOut.close();

      chukasaModel.getIvArrayList().add(ivHex);
      chukasaModel = chukasaModelManagementComponent.update(adaptiveBitrateStreaming, chukasaModel);

      fis =
          new FileInputStream(
              tempEncPath
                  + FILE_SEPARATOR
                  + chukasaModel.getChukasaConfiguration().getStreamFileNamePrefix()
                  + seqTsEnc
                  + chukasaModel.getHlsConfiguration().getStreamExtension());
      bis = new BufferedInputStream(fis);
      fos =
          new FileOutputStream(
              streamPath
                  + FILE_SEPARATOR
                  + chukasaModel.getChukasaConfiguration().getStreamFileNamePrefix()
                  + seqTsEnc
                  + chukasaModel.getHlsConfiguration().getStreamExtension());
      cos = new CipherOutputStream(fos, c);
      if (chukasaModel.getChukasaSettings().getStreamingType() == StreamingType.OKKAKE) {
        // TODO:
        fis =
            new FileInputStream(
                tempEncPath
                    + FILE_SEPARATOR
                    + "fileSequenceEncoded"
                    + seqTsEnc
                    + chukasaModel.getHlsConfiguration().getStreamExtension());
        bis = new BufferedInputStream(fis);
        fos =
            new FileOutputStream(
                streamPath
                    + FILE_SEPARATOR
                    + chukasaModel.getChukasaConfiguration().getStreamFileNamePrefix()
                    + seqTsEnc
                    + chukasaModel.getHlsConfiguration().getStreamExtension());
        cos = new CipherOutputStream(fos, c);
      }

      byte[] buf = new byte[tsPacketLength];

      int ch;
      while ((ch = bis.read(buf)) != -1) {
        cos.write(buf, 0, ch);
      }
      cos.close();
      fos.close();
      bis.close();
      fis.close();

    } catch (InvalidKeyException e) {
      e.printStackTrace();
    } catch (NoSuchPaddingException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (NoSuchProviderException e) {
      e.printStackTrace();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }