Esempio n. 1
0
  private void testCipherNameWithWrap(String name, String simpleName) throws Exception {
    KeyGenerator kg = KeyGenerator.getInstance("AES");
    kg.init(new SecureRandom());
    SecretKey key = kg.generateKey();

    byte[] salt = {
      (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c,
      (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99
    };
    char[] password = {'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};

    PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 20);
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    SecretKeyFactory keyFac = SecretKeyFactory.getInstance(name);
    SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
    Cipher pbeEncryptCipher = Cipher.getInstance(name, "SC");

    pbeEncryptCipher.init(Cipher.WRAP_MODE, pbeKey, pbeParamSpec);

    byte[] symKeyBytes = pbeEncryptCipher.wrap(key);

    Cipher simpleCipher = Cipher.getInstance(simpleName, "SC");

    simpleCipher.init(Cipher.UNWRAP_MODE, pbeKey, pbeParamSpec);

    SecretKey unwrappedKey = (SecretKey) simpleCipher.unwrap(symKeyBytes, "AES", Cipher.SECRET_KEY);

    if (!Arrays.areEqual(unwrappedKey.getEncoded(), key.getEncoded())) {
      fail("key mismatch on unwrapping");
    }
  }
Esempio n. 2
0
  /**
   * Generate a new MWK
   *
   * @return Hex String of the new encrypted MWK ready for transmission to ValueLink
   */
  public byte[] generateMwk() {
    KeyGenerator keyGen = null;
    try {
      keyGen = KeyGenerator.getInstance("DES");
    } catch (NoSuchAlgorithmException e) {
      Debug.logError(e, module);
    }

    // generate the DES key 1
    SecretKey des1 = keyGen.generateKey();
    SecretKey des2 = keyGen.generateKey();

    if (des1 != null && des2 != null) {
      byte[] desByte1 = des1.getEncoded();
      byte[] desByte2 = des2.getEncoded();
      byte[] desByte3 = des1.getEncoded();

      // check for weak keys
      try {
        if (DESKeySpec.isWeak(des1.getEncoded(), 0) || DESKeySpec.isWeak(des2.getEncoded(), 0)) {
          return generateMwk();
        }
      } catch (Exception e) {
        Debug.logError(e, module);
      }

      byte[] des3 = copyBytes(desByte1, copyBytes(desByte2, desByte3, 0), 0);
      return generateMwk(des3);
    } else {
      Debug.logInfo("Null DES keys returned", module);
    }

    return null;
  }
 /**
  * Generates a random secret key using the algorithm specified in the first DataReference URI
  *
  * @param dataRefURIs
  * @param doc
  * @param wsDocInfo
  * @return
  * @throws WSSecurityException
  */
 private static byte[] getRandomKey(List<String> dataRefURIs, Document doc, WSDocInfo wsDocInfo)
     throws WSSecurityException {
   try {
     String alg = "AES";
     int size = 16;
     if (!dataRefURIs.isEmpty()) {
       String uri = dataRefURIs.iterator().next();
       Element ee = ReferenceListProcessor.findEncryptedDataElement(doc, uri);
       String algorithmURI = X509Util.getEncAlgo(ee);
       alg = JCEMapper.getJCEKeyAlgorithmFromURI(algorithmURI);
       size = WSSecurityUtil.getKeyLength(algorithmURI);
     }
     KeyGenerator kgen = KeyGenerator.getInstance(alg);
     kgen.init(size * 8);
     SecretKey k = kgen.generateKey();
     return k.getEncoded();
   } catch (Throwable ex) {
     // Fallback to just using AES to avoid attacks on EncryptedData algorithms
     try {
       KeyGenerator kgen = KeyGenerator.getInstance("AES");
       kgen.init(128);
       SecretKey k = kgen.generateKey();
       return k.getEncoded();
     } catch (NoSuchAlgorithmException e) {
       throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, e);
     }
   }
 }
  protected KeySpec engineGetKeySpec(SecretKey key, Class keySpec) throws InvalidKeySpecException {
    if (keySpec == null) {
      throw new InvalidKeySpecException("keySpec parameter is null");
    }
    if (key == null) {
      throw new InvalidKeySpecException("key parameter is null");
    }

    if (SecretKeySpec.class.isAssignableFrom(keySpec)) {
      return new SecretKeySpec(key.getEncoded(), algName);
    }

    try {
      Class[] parameters = {byte[].class};

      Constructor c = keySpec.getConstructor(parameters);
      Object[] p = new Object[1];

      p[0] = key.getEncoded();

      return (KeySpec) c.newInstance(p);
    } catch (Exception e) {
      throw new InvalidKeySpecException(e.toString());
    }
  }
Esempio n. 5
0
    protected KeySpec engineGetKeySpec(SecretKey key, Class keySpec)
        throws InvalidKeySpecException {
      if (keySpec == null) {
        throw new InvalidKeySpecException("keySpec parameter is null");
      }
      if (key == null) {
        throw new InvalidKeySpecException("key parameter is null");
      }

      if (SecretKeySpec.class.isAssignableFrom(keySpec)) {
        return new SecretKeySpec(key.getEncoded(), algName);
      } else if (DESedeKeySpec.class.isAssignableFrom(keySpec)) {
        byte[] bytes = key.getEncoded();

        try {
          if (bytes.length == 16) {
            byte[] longKey = new byte[24];

            System.arraycopy(bytes, 0, longKey, 0, 16);
            System.arraycopy(bytes, 0, longKey, 16, 8);

            return new DESedeKeySpec(longKey);
          } else {
            return new DESedeKeySpec(bytes);
          }
        } catch (Exception e) {
          throw new InvalidKeySpecException(e.toString());
        }
      }

      throw new InvalidKeySpecException("Invalid KeySpec");
    }
Esempio n. 6
0
 public void checkKey() throws Exception {
   SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
   KeySpec spec = new PBEKeySpec("123".toCharArray(), "123".getBytes(), 10, 128);
   SecretKey tmp = factory.generateSecret(spec);
   SecretKeySpec key = new SecretKeySpec(tmp.getEncoded(), "AES"); // TODO: get appropriate key
   key = new SecretKeySpec(tmp.getEncoded(), "Blowfish"); // TODO: get appropriate key
   key = new SecretKeySpec(tmp.getEncoded(), "DES"); // TODO: get appropriate key
   // Blowfish, DES
 }
Esempio n. 7
0
  protected String decrypt(String content, String key) {

    if (content.length() < 1) return null;
    byte[] byteRresult = new byte[content.length() / 2];
    for (int i = 0; i < content.length() / 2; i++) {
      int high = Integer.parseInt(content.substring(i * 2, i * 2 + 1), 16);
      int low = Integer.parseInt(content.substring(i * 2 + 1, i * 2 + 2), 16);
      byteRresult[i] = (byte) (high * 16 + low);
    }
    try {
      KeyGenerator kgen = KeyGenerator.getInstance("AES");
      kgen.init(128, new SecureRandom(key.getBytes()));
      SecretKey secretKey = kgen.generateKey();
      byte[] enCodeFormat = secretKey.getEncoded();
      SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
      Cipher cipher = Cipher.getInstance("AES");
      cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
      byte[] result = cipher.doFinal(byteRresult);
      return new String(result);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (NoSuchPaddingException e) {
      e.printStackTrace();
    } catch (InvalidKeyException e) {
      e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
      e.printStackTrace();
    } catch (BadPaddingException e) {
      e.printStackTrace();
    }
    return null;
  }
 @SideOnly(Side.CLIENT)
 public Packet252SharedKey(
     SecretKey par1SecretKey, PublicKey par2PublicKey, byte[] par3ArrayOfByte) {
   this.sharedKey = par1SecretKey;
   this.sharedSecret = CryptManager.encryptData(par2PublicKey, par1SecretKey.getEncoded());
   this.verifyToken = CryptManager.encryptData(par2PublicKey, par3ArrayOfByte);
 }
Esempio n. 9
0
 @Override
 public int hashCode() {
   int result = id;
   result = 31 * result + (int) (expirationDate ^ (expirationDate >>> 32));
   result = 31 * result + ((secret == null) ? 0 : Arrays.hashCode(secret.getEncoded()));
   return result;
 }
Esempio n. 10
0
  /**
   * Get the signing key unique to this installation, or create it if it doesn't exist. The purpose
   * of this key is to allow signing of backup files (and any other such files) to ensure they are
   * not modified by some other program. Of course, if the other program has root then it can modify
   * or read this key anyway, so all bets are off.
   *
   * @return secret key for signing and verification
   */
  public SecretKey getOrCreateSigningKey() {
    String signingKey = this.prefs.getString(BACKUP_SIGNING_KEY, null);
    SecretKey secretKey = null;
    if (signingKey != null) {
      secretKey =
          new SecretKeySpec(
              Base64.decode(signingKey, Base64.DEFAULT),
              0,
              Base64.decode(signingKey, Base64.DEFAULT).length,
              "HmacSHA1");
    } else {
      // supporting multiple algorithms would be good, but then we also need to store the key
      // type...
      try {
        secretKey = KeyGenerator.getInstance("HmacSHA1").generateKey();
      } catch (NoSuchAlgorithmException e) {
      }

      Editor editor = this.prefs.edit();
      editor.putString(
          BACKUP_SIGNING_KEY, Base64.encodeToString(secretKey.getEncoded(), Base64.DEFAULT));
      editor.commit();
    }

    return secretKey;
  }
Esempio n. 11
0
    /**
     * Seal session key with RSA public key in a SealedObject.
     *
     * @return SealedObject of session key
     */
    public SealedObject getSessionKey() {

      SealedObject object = null;

      try {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, bryanPubKey);
        byte[] sessionKeyBytes = sessionKey.getEncoded();
        object = new SealedObject(sessionKeyBytes, cipher);
      } catch (NoSuchAlgorithmException e) {
        System.out.println("Error: No algorithm entered exists.");
        System.exit(1);
      } catch (NoSuchPaddingException e) {
        System.out.println("Error: transformation contains a padding scheme is not available.");
        System.exit(1);
      } catch (InvalidKeyException e) {
        System.out.println("Error: the public key is invalid.");
        System.exit(1);
      } catch (IllegalBlockSizeException e) {
        System.out.println("Error: the block size is invalid.");
        System.exit(1);
      } catch (IOException e) {
        System.out.println("Error: cannot create SealedObject");
        System.exit(1);
      }

      return object;
    }
Esempio n. 12
0
 public RSAJweEncryption(RSAPublicKey publicKey, SecretKey secretKey, byte[] iv) {
   this(
       publicKey,
       secretKey,
       Algorithm.toJwtName(secretKey.getAlgorithm(), secretKey.getEncoded().length * 8),
       iv);
 }
  /**
   * This method broadcasts a payload onto the given topic.
   *
   * @param topic the topic to broadcast onto
   * @param visibility the visibility of the message
   * @param payload the payload of the message
   */
  public void broadcast(String topic, Visibility visibility, byte[] payload) throws IOException {
    byte[] payloadToSend = payload;
    SecureMessage message = new SecureMessage();
    message.setVisibility(visibility);
    if (isProduction) {
      try {
        // Generate a new symmetric key and encrypt the message
        Cipher cipher = Cipher.getInstance(ALGO);
        KeyGenerator gen = KeyGenerator.getInstance(ALGO);
        gen.init(256);
        SecretKey key = gen.generateKey();
        cipher.init(Cipher.ENCRYPT_MODE, key);
        payloadToSend = cipher.doFinal(payload);

        // Get topic crypto object, encrypt the key and embed it into the message
        RSAKeyCrypto crypto = topicKeys.get(topic);
        message.setKey(crypto.encrypt(key.getEncoded()));
      } catch (Exception e) {
        log.error("Could not encrypt message for topic [{}].", topic, e);
        throw new RuntimeException(e);
      }
    }
    message.setContent(payloadToSend);
    byte[] serializedMessage;
    try {
      serializedMessage = ThriftUtils.serialize(message);
    } catch (TException e) {
      throw new IOException("Could not serialize message", e);
    }
    broadcastImpl(topic, serializedMessage);
  }
Esempio n. 14
0
  /**
   * Initialises the Ciphers for both encryption and decryption using the generated or supplied
   * secret key.
   *
   * @param algorithm
   * @param secret
   * @throws Exception
   */
  private void initSymCiphers(String algorithm, SecretKey secret) throws Exception {
    log.debug("initializing symmetric ciphers (pool size=%d)", cipher_pool_size);

    for (int i = 0; i < cipher_pool_size; i++) {
      encoding_ciphers[i] =
          symProvider != null && !symProvider.trim().isEmpty()
              ? Cipher.getInstance(algorithm, symProvider)
              : Cipher.getInstance(algorithm);
      encoding_ciphers[i].init(Cipher.ENCRYPT_MODE, secret);

      decoding_ciphers[i] =
          symProvider != null && !symProvider.trim().isEmpty()
              ? Cipher.getInstance(algorithm, symProvider)
              : Cipher.getInstance(algorithm);
      decoding_ciphers[i].init(Cipher.DECRYPT_MODE, secret);

      encoding_locks[i] = new ReentrantLock();
      decoding_locks[i] = new ReentrantLock();
    }

    // set the version
    MessageDigest digest = MessageDigest.getInstance("MD5");
    digest.reset();
    digest.update(secret.getEncoded());

    byte[] tmp = digest.digest();
    symVersion = Arrays.copyOf(tmp, tmp.length);
    // symVersion = byteArrayToHexString(digest.digest());
    log.debug("initialized symmetric ciphers with secret key (" + symVersion.length + " bytes)");
  }
Esempio n. 15
0
 protected String encrypt(String content, String key) {
   try {
     KeyGenerator kgen = KeyGenerator.getInstance("AES");
     kgen.init(128, new SecureRandom(key.getBytes()));
     SecretKey secretKey = kgen.generateKey();
     byte[] enCodeFormat = secretKey.getEncoded();
     SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
     Cipher cipher = Cipher.getInstance("AES");
     byte[] byteContent = content.getBytes("utf-8");
     cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
     byte[] byteRresult = cipher.doFinal(byteContent);
     StringBuffer sb = new StringBuffer();
     for (int i = 0; i < byteRresult.length; i++) {
       String hex = Integer.toHexString(byteRresult[i] & 0xFF);
       if (hex.length() == 1) {
         hex = '0' + hex;
       }
       sb.append(hex.toUpperCase());
     }
     return sb.toString();
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (NoSuchPaddingException e) {
     e.printStackTrace();
   } catch (InvalidKeyException e) {
     e.printStackTrace();
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   } catch (IllegalBlockSizeException e) {
     e.printStackTrace();
   } catch (BadPaddingException e) {
     e.printStackTrace();
   }
   return null;
 }
Esempio n. 16
0
  private static byte[] doAes(int mode, byte[] input, String password) {
    try {
      KeyGenerator keygen = KeyGenerator.getInstance(AES_ALGORITHM_NAME);
      keygen.init(128, new SecureRandom(password.getBytes()));
      SecretKey secretKey = keygen.generateKey();

      byte[] enCodeFormat = secretKey.getEncoded();
      SecretKeySpec key = new SecretKeySpec(enCodeFormat, AES_ALGORITHM_NAME);

      Cipher cipher = Cipher.getInstance(AES_ALGORITHM_NAME);
      cipher.init(Cipher.DECRYPT_MODE, key);

      return cipher.doFinal(input);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (NoSuchPaddingException e) {
      e.printStackTrace();
    } catch (InvalidKeyException e) {
      e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
      e.printStackTrace();
    } catch (BadPaddingException e) {
      e.printStackTrace();
    }
    return null;
  }
Esempio n. 17
0
 public static byte[] getShared(SecretKey key, PublicKey pubkey)
     throws BadPaddingException, IllegalBlockSizeException, InvalidKeyException,
         NoSuchAlgorithmException, NoSuchPaddingException {
   Cipher cipher = Cipher.getInstance("RSA");
   cipher.init(Cipher.ENCRYPT_MODE, pubkey);
   return cipher.doFinal(key.getEncoded());
 }
Esempio n. 18
0
  public static boolean isAuthenticated(String username, String connectionHash, SecretKey shared)
      throws NoSuchAlgorithmException, IOException {
    String encName = URLEncoder.encode(username, "UTF-8");

    MessageDigest sha = MessageDigest.getInstance("SHA-1");
    for (byte[] bit :
        new byte[][] {
          connectionHash.getBytes("ISO_8859_1"), shared.getEncoded(), keys.getPublic().getEncoded()
        }) {
      sha.update(bit);
    }

    String encodedHash = URLEncoder.encode(new BigInteger(sha.digest()).toString(16), "UTF-8");
    String authURL =
        "http://session.minecraft.net/game/checkserver.jsp?user="******"&serverId="
            + encodedHash;
    String reply;
    try (BufferedReader in =
        new BufferedReader(new InputStreamReader(new URL(authURL).openStream()))) {
      reply = in.readLine();
    }

    return "YES".equals(reply);
  }
 /**
  * Encrypts a symmetric key using the provided encryption materials and returns it in raw byte
  * array form.
  *
  * @deprecated no longer used and will be removed in the future
  */
 @Deprecated
 public static byte[] getEncryptedSymmetricKey(
     SecretKey toBeEncrypted, EncryptionMaterials materials, Provider cryptoProvider) {
   Key keyToDoEncryption;
   if (materials.getKeyPair() != null) {
     // Do envelope encryption with public key from key pair
     keyToDoEncryption = materials.getKeyPair().getPublic();
   } else {
     // Do envelope encryption with symmetric key
     keyToDoEncryption = materials.getSymmetricKey();
   }
   try {
     Cipher cipher;
     byte[] toBeEncryptedBytes = toBeEncrypted.getEncoded();
     if (cryptoProvider != null) {
       cipher = Cipher.getInstance(keyToDoEncryption.getAlgorithm(), cryptoProvider);
     } else {
       cipher = Cipher.getInstance(keyToDoEncryption.getAlgorithm()); // Use default JCE Provider
     }
     cipher.init(Cipher.ENCRYPT_MODE, keyToDoEncryption);
     return cipher.doFinal(toBeEncryptedBytes);
   } catch (Exception e) {
     throw new AmazonClientException("Unable to encrypt symmetric key: " + e.getMessage(), e);
   }
 }
Esempio n. 20
0
  public static Message encrypt(PublicKey pubKey, byte[] input) throws CryptoException {
    Message message = new Message();
    message.pubKey = pubKey.getEncoded();

    KeyGenerator keyGen;
    try {
      keyGen = KeyGenerator.getInstance("AES");
    } catch (NoSuchAlgorithmException e) {
      throw new CryptoException(e);
    }
    keyGen.init(128);
    SecretKey secretKey = keyGen.generateKey();

    try {
      Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
      rsaCipher.init(Cipher.ENCRYPT_MODE, pubKey);
      message.sessionKey = rsaCipher.doFinal(secretKey.getEncoded());

      Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      aesCipher.init(Cipher.ENCRYPT_MODE, secretKey);
      AlgorithmParameters params = aesCipher.getParameters();
      message.iv = params.getParameterSpec(IvParameterSpec.class).getIV();
      message.ciphertext = aesCipher.doFinal(input);
    } catch (NoSuchAlgorithmException
        | NoSuchPaddingException
        | InvalidKeyException
        | IllegalBlockSizeException
        | BadPaddingException
        | InvalidParameterSpecException e) {
      throw new CryptoException(e);
    }

    return message;
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Bitmap bm = null;
    bm.compress(Bitmap.CompressFormat.PNG, 100, baos); // bm is the bitmap object
    byte[] b = baos.toByteArray();

    byte[] keyStart = "this is a key".getBytes();
    KeyGenerator kgen;
    try {
      kgen = KeyGenerator.getInstance("AES");
      SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
      sr.setSeed(keyStart);
      kgen.init(128, sr); // 192 and 256 bits may not be available
      SecretKey skey = kgen.generateKey();
      byte[] key = skey.getEncoded();

      // encrypt
      byte[] encryptedData = encrypt(key, b);
      // decrypt
      byte[] decryptedData = decrypt(key, encryptedData);
    } catch (NoSuchAlgorithmException e) {
      // TODO 自動產生的 catch 區塊
      e.printStackTrace();
    } catch (Exception e) {
      // TODO 自動產生的 catch 區塊
      e.printStackTrace();
    }
  }
Esempio n. 22
0
 /**
  * 加密
  *
  * @param content 需要加密的内容
  * @param password 加密密码
  * @return
  */
 public static byte[] encryptAES(String content, String password) {
   try {
     KeyGenerator kgen = KeyGenerator.getInstance("AES");
     kgen.init(128, new SecureRandom(password.getBytes()));
     SecretKey secretKey = kgen.generateKey();
     byte[] enCodeFormat = secretKey.getEncoded();
     SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
     Cipher cipher = Cipher.getInstance("AES"); // 创建密码器
     byte[] byteContent = content.getBytes("utf-8");
     cipher.init(Cipher.ENCRYPT_MODE, key); // 初始化
     byte[] result = cipher.doFinal(byteContent);
     return result; // 加密
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (NoSuchPaddingException e) {
     e.printStackTrace();
   } catch (InvalidKeyException e) {
     e.printStackTrace();
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   } catch (IllegalBlockSizeException e) {
     e.printStackTrace();
   } catch (BadPaddingException e) {
     e.printStackTrace();
   }
   return null;
 }
  private DERObject createDERForRecipient(byte[] in, X509Certificate cert)
      throws IOException, GeneralSecurityException {

    String s = "1.2.840.113549.3.2";

    AlgorithmParameterGenerator algorithmparametergenerator =
        AlgorithmParameterGenerator.getInstance(s);
    AlgorithmParameters algorithmparameters = algorithmparametergenerator.generateParameters();
    ByteArrayInputStream bytearrayinputstream =
        new ByteArrayInputStream(algorithmparameters.getEncoded("ASN.1"));
    ASN1InputStream asn1inputstream = new ASN1InputStream(bytearrayinputstream);
    DERObject derobject = asn1inputstream.readObject();
    KeyGenerator keygenerator = KeyGenerator.getInstance(s);
    keygenerator.init(128);
    SecretKey secretkey = keygenerator.generateKey();
    Cipher cipher = Cipher.getInstance(s);
    cipher.init(1, secretkey, algorithmparameters);
    byte[] abyte1 = cipher.doFinal(in);
    DEROctetString deroctetstring = new DEROctetString(abyte1);
    KeyTransRecipientInfo keytransrecipientinfo =
        computeRecipientInfo(cert, secretkey.getEncoded());
    DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo));
    AlgorithmIdentifier algorithmidentifier =
        new AlgorithmIdentifier(new DERObjectIdentifier(s), derobject);
    EncryptedContentInfo encryptedcontentinfo =
        new EncryptedContentInfo(PKCSObjectIdentifiers.data, algorithmidentifier, deroctetstring);
    EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, null);
    ContentInfo contentinfo = new ContentInfo(PKCSObjectIdentifiers.envelopedData, env);
    return contentinfo.getDERObject();
  }
  private static boolean writeKeyToFile(Context context, String basename, SecretKey key) {
    File file = context.getFileStreamPath(basename);
    byte[] keyBytes = key.getEncoded();
    FileOutputStream output = null;
    if (MAC_KEY_BYTE_COUNT != keyBytes.length) {
      Log.e(
          TAG,
          "writeKeyToFile got key encoded bytes length "
              + keyBytes.length
              + "; expected "
              + MAC_KEY_BYTE_COUNT);
      return false;
    }

    try {
      output = new FileOutputStream(file);
      output.write(keyBytes);
      return true;
    } catch (Exception e) {
      Log.e(TAG, "Could not write key to '" + file + "': " + e);
      return false;
    } finally {
      try {
        if (output != null) {
          output.close();
        }
      } catch (IOException e) {
        Log.e(TAG, "Could not close key output stream '" + file + "': " + e);
      }
    }
  }
  private static AlgorithmIdentifier determineKeyEncAlg(SecretKey key) {
    String algorithm = key.getAlgorithm();

    if (algorithm.startsWith("DES")) {
      return new AlgorithmIdentifier(
          new DERObjectIdentifier("1.2.840.113549.1.9.16.3.6"), new DERNull());
    } else if (algorithm.startsWith("RC2")) {
      return new AlgorithmIdentifier(
          new DERObjectIdentifier("1.2.840.113549.1.9.16.3.7"), new DERInteger(58));
    } else if (algorithm.startsWith("AES")) {
      int length = key.getEncoded().length * 8;
      DERObjectIdentifier wrapOid;

      if (length == 128) {
        wrapOid = NISTObjectIdentifiers.id_aes128_wrap;
      } else if (length == 192) {
        wrapOid = NISTObjectIdentifiers.id_aes192_wrap;
      } else if (length == 256) {
        wrapOid = NISTObjectIdentifiers.id_aes256_wrap;
      } else {
        throw new IllegalArgumentException("illegal keysize in AES");
      }

      return new AlgorithmIdentifier(wrapOid); // parameters absent
    } else if (algorithm.startsWith("SEED")) {
      // parameters absent
      return new AlgorithmIdentifier(KISAObjectIdentifiers.id_npki_app_cmsSeed_wrap);
    } else if (algorithm.startsWith("Camellia")) {
      int length = key.getEncoded().length * 8;
      DERObjectIdentifier wrapOid;

      if (length == 128) {
        wrapOid = NTTObjectIdentifiers.id_camellia128_wrap;
      } else if (length == 192) {
        wrapOid = NTTObjectIdentifiers.id_camellia192_wrap;
      } else if (length == 256) {
        wrapOid = NTTObjectIdentifiers.id_camellia256_wrap;
      } else {
        throw new IllegalArgumentException("illegal keysize in Camellia");
      }

      return new AlgorithmIdentifier(wrapOid); // parameters must be
      // absent
    } else {
      throw new IllegalArgumentException("unknown algorithm");
    }
  }
Esempio n. 26
0
  @Test
  public void testAESCipherByteArrayByteArray() {
    try {
      byte[] encrypted = AESCipher.encrypt(MESSAGE, SECRET_KEY.getEncoded());
      assertNotNull(encrypted);
      assertTrue(encrypted.length > 0);

      byte[] result = AESCipher.decrypt(encrypted, SECRET_KEY.getEncoded());
      assertNotNull(result);
      assertTrue(result.length > 0);

      assertArrayEquals(MESSAGE.getBytes(CHARSET), result);
      assertEquals(MESSAGE, new String(result, CHARSET));
    } catch (AESCipherException | UnsupportedEncodingException e) {
      fail(e.getMessage());
    }
  }
Esempio n. 27
0
 // using PBKDF2 from Sun, an alternative is https://github.com/wg/scrypt
 // cf. http://www.unlimitednovelty.com/2012/03/dont-use-bcrypt.html
 private static String hash(String password, byte[] salt) throws Exception {
   if (password == null || password.length() == 0)
     throw new IllegalArgumentException("Empty passwords are not supported.");
   SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
   SecretKey key =
       f.generateSecret(new PBEKeySpec(password.toCharArray(), salt, iterations, desiredKeyLen));
   return Base64.encodeToString(key.getEncoded(), Base64.DEFAULT);
 }
 public byte[] deCryptData(byte[] toDecrypt, SecretKey key)
     throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException,
         BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException {
   Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
   cipher.init(
       Cipher.DECRYPT_MODE, new SecretKeySpec(key.getEncoded(), "AES"), new IvParameterSpec(iv));
   return cipher.doFinal(toDecrypt);
 }
Esempio n. 29
0
  public static void main(String[] args) throws Exception {
    // Gen Key
    KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
    SecretKey key = keyGenerator.generateKey();
    bytesKey = key.getEncoded();

    jdkDES();
    bcDES();
  }
Esempio n. 30
0
 public static void setKeyCode() {
   try {
     KeyGenerator keygen = KeyGenerator.getInstance("DES");
     SecretKey deskey = keygen.generateKey();
     keyCode = baseEncode(deskey.getEncoded());
   } catch (Exception e) {
     e.printStackTrace();
   }
 }