예제 #1
0
  public static final void main(String[] args) throws Exception {

    // Generate a PBE key
    SecretKeyFactory skFac = SecretKeyFactory.getInstance("PBE");
    SecretKey skey = skFac.generateSecret(new PBEKeySpec("test123".toCharArray()));

    // Initialize the PBE cipher
    Cipher cipher = Cipher.getInstance(ALGO);
    cipher.init(Cipher.ENCRYPT_MODE, skey);

    // Permit access to the Cipher.spi field (a CipherSpi object)
    Field spi = Cipher.class.getDeclaredField("spi");
    spi.setAccessible(true);
    Object value = spi.get(cipher);

    // Permit access to the CipherSpi.engineGetKeySize method
    Method engineGetKeySize =
        PKCS12PBECipherCore$PBEWithSHA1AndDESede.class.getDeclaredMethod(
            "engineGetKeySize", Key.class);
    engineGetKeySize.setAccessible(true);

    // Check the key size
    int keySize = (int) engineGetKeySize.invoke(value, skey);
    if (keySize == KEYSIZE) {
      System.out.println(ALGO + ".engineGetKeySize returns " + keySize + " bits, as expected");
      System.out.println("OK");
    } else {
      throw new Exception("ERROR: " + ALGO + " key size is incorrect");
    }
  }
예제 #2
0
파일: Util.java 프로젝트: gubo/slipwire
  /**
   * @param s
   * @return
   * @throws GeneralSecurityException
   * @throws UnsupportedEncodingException
   */
  public static String decrypt(final String s)
      throws GeneralSecurityException, UnsupportedEncodingException {
    String decrypted = null;

    try {
      if (s != null) {
        final SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        final SecretKey secretKey =
            secretKeyFactory.generateSecret(new PBEKeySpec(secret.toCharArray()));
        final Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey, new PBEParameterSpec(SALT, 20));
        final byte[] stringBytes = s.getBytes("UTF-8");
        final byte[] decodedBytes = Base64.decode(stringBytes, Base64.DEFAULT);
        final byte[] decryptedBytes = cipher.doFinal(decodedBytes);
        decrypted = new String(decryptedBytes, "UTF-8");
      }
    } catch (GeneralSecurityException x) {
      throw x;
    } catch (UnsupportedEncodingException x) {
      throw x;
    } catch (Exception x) {
      DBG.m(x);
    }

    return decrypted;
  }
예제 #3
0
  private static void runTest(boolean isUnlimited) throws Exception {
    System.out.println("Testing " + (isUnlimited ? "un" : "") + "limited policy...");

    String algo = "Blowfish";
    int keyLength = Cipher.getMaxAllowedKeyLength(algo);
    AlgorithmParameterSpec spec = Cipher.getMaxAllowedParameterSpec(algo);
    if (isUnlimited) {
      if ((keyLength != Integer.MAX_VALUE) || (spec != null)) {
        throw new Exception("Check for " + algo + " failed under unlimited policy");
      }
    } else {
      if ((keyLength != 128) || (spec != null)) {
        throw new Exception("Check for " + algo + " failed under default policy");
      }
    }
    algo = "RC5";
    keyLength = Cipher.getMaxAllowedKeyLength(algo);
    RC5ParameterSpec rc5param = (RC5ParameterSpec) Cipher.getMaxAllowedParameterSpec(algo);
    if (isUnlimited) {
      if ((keyLength != Integer.MAX_VALUE) || (rc5param != null)) {
        throw new Exception("Check for " + algo + " failed under unlimited policy");
      }
    } else {
      if ((keyLength != 128)
          || (rc5param.getRounds() != 12)
          || (rc5param.getVersion() != Integer.MAX_VALUE)
          || (rc5param.getWordSize() != Integer.MAX_VALUE)) {
        throw new Exception("Check for " + algo + " failed under default policy");
      }
    }
    System.out.println("All tests passed");
  }
예제 #4
0
  /*
   * Encrypt private key using Password-based encryption (PBE)
   * as defined in PKCS#5.
   *
   * NOTE: Currently pbeWithSHAAnd3-KeyTripleDES-CBC algorithmID is
   *       used to derive the key and IV.
   *
   * @return encrypted private key encoded as EncryptedPrivateKeyInfo
   */
  private byte[] encryptPrivateKey(byte[] data, char[] password)
      throws IOException, NoSuchAlgorithmException, UnrecoverableKeyException {
    byte[] key = null;

    try {
      // create AlgorithmParameters
      AlgorithmParameters algParams = getAlgorithmParameters("PBEWithSHA1AndDESede");

      // Use JCE
      SecretKey skey = getPBEKey(password);
      Cipher cipher = Cipher.getInstance("PBEWithSHA1AndDESede");
      cipher.init(Cipher.ENCRYPT_MODE, skey, algParams);
      byte[] encryptedKey = cipher.doFinal(data);

      // wrap encrypted private key in EncryptedPrivateKeyInfo
      // as defined in PKCS#8
      AlgorithmId algid = new AlgorithmId(pbeWithSHAAnd3KeyTripleDESCBC_OID, algParams);
      EncryptedPrivateKeyInfo encrInfo = new EncryptedPrivateKeyInfo(algid, encryptedKey);
      key = encrInfo.getEncoded();
    } catch (Exception e) {
      UnrecoverableKeyException uke =
          new UnrecoverableKeyException("Encrypt Private Key failed: " + e.getMessage());
      uke.initCause(e);
      throw uke;
    }

    return key;
  }
예제 #5
0
  public void run() {
    try {
      ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
      ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());

      BigInteger bg = dhSpec.getG();
      BigInteger bp = dhSpec.getP();
      oos.writeObject(bg);
      oos.writeObject(bp);

      KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH");
      kpg.initialize(1024);
      KeyPair kpa = (KeyPair) ois.readObject();
      KeyAgreement dh = KeyAgreement.getInstance("DH");
      KeyPair kp = kpg.generateKeyPair();

      oos.writeObject(kp);

      dh.init(kp.getPrivate());
      Key pk = dh.doPhase(kpa.getPublic(), true);

      MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
      byte[] rawbits = sha256.digest(dh.generateSecret());

      Cipher c = Cipher.getInstance(CIPHER_MODE);
      SecretKey key = new SecretKeySpec(rawbits, 0, 16, "AES");
      byte ivbits[] = (byte[]) ois.readObject();
      IvParameterSpec iv = new IvParameterSpec(ivbits);
      c.init(Cipher.DECRYPT_MODE, key, iv);

      Mac m = Mac.getInstance("HmacSHA1");
      SecretKey mackey = new SecretKeySpec(rawbits, 16, 16, "HmacSHA1");
      m.init(mackey);

      byte ciphertext[], cleartext[], mac[];
      try {
        while (true) {
          ciphertext = (byte[]) ois.readObject();
          mac = (byte[]) ois.readObject();
          if (Arrays.equals(mac, m.doFinal(ciphertext))) {
            cleartext = c.update(ciphertext);
            System.out.println(ct + " : " + new String(cleartext, "UTF-8"));
          } else {
            // System.exit(1);
            System.out.println(ct + "error");
          }
        }
      } catch (EOFException e) {
        cleartext = c.doFinal();
        System.out.println(ct + " : " + new String(cleartext, "UTF-8"));
        System.out.println("[" + ct + "]");
      } finally {
        if (ois != null) ois.close();
        if (oos != null) oos.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
예제 #6
0
파일: DESPlus.java 프로젝트: hebut/jxkh
 /**
  * 指定密钥构造方法
  *
  * @param strKey 指定的密钥
  * @throws Exception
  */
 public DESPlus(String strKey) throws Exception {
   Security.addProvider(new com.sun.crypto.provider.SunJCE());
   Key key = getKey(strKey.getBytes());
   encryptCipher = Cipher.getInstance("DES");
   encryptCipher.init(Cipher.ENCRYPT_MODE, key);
   decryptCipher = Cipher.getInstance("DES");
   decryptCipher.init(Cipher.DECRYPT_MODE, key);
 }
예제 #7
0
 public byte[] decrypt(final byte[] toDecrypt) {
   try {
     final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
     cipher.init(Cipher.DECRYPT_MODE, skey, sRand);
     return cipher.doFinal(toDecrypt);
   } catch (final Exception e) {
     throw new RuntimeException(e);
   }
 }
 public static byte[] encode(String paramString, byte[] paramArrayOfByte) {
   SecretKeySpec localSecretKeySpec = new SecretKeySpec(paramArrayOfByte, "AES");
   try {
     byte[] arrayOfByte1 = paramString.getBytes();
     Cipher localCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
     localCipher.init(Cipher.ENCRYPT_MODE, localSecretKeySpec);
     byte[] arrayOfByte2 = localCipher.doFinal(arrayOfByte1);
     return arrayOfByte2;
   } catch (Exception localException) {
   }
   return null;
 }
예제 #9
0
 public static void main(String[] args) throws Exception {
   // decide if the installed jurisdiction policy file is the
   // unlimited version
   boolean isUnlimited = true;
   Cipher c = Cipher.getInstance("AES", "SunJCE");
   try {
     c.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(new byte[24], "AES"));
   } catch (InvalidKeyException ike) {
     isUnlimited = false;
   }
   runTest(isUnlimited);
 }
 public static byte[] decode(byte[] paramArrayOfByte1, byte[] paramArrayOfByte2) {
   SecretKeySpec localSecretKeySpec = new SecretKeySpec(paramArrayOfByte2, "AES");
   try {
     Cipher localCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
     localCipher.init(Cipher.DECRYPT_MODE, localSecretKeySpec);
     byte[] arrayOfByte = localCipher.doFinal(paramArrayOfByte1);
     return arrayOfByte;
   } catch (Exception localException) {
     localException.printStackTrace();
   }
   return null;
 }
예제 #11
0
 /**
  * Reads the raw data from the input File, encrypts and saves its contents to the output File, and
  * then save the raw data of the SecretKey used to the SecretKey File.
  *
  * @param input the File to be read and encrypted
  * @param output the File the encrypted data will be saved to
  * @param keyFile the File the SecretKey data will be saved to
  * @throws InvalidKeyException if the given key is inappropriate for initializing this cipher, or
  *     if this cipher is being initialized for decryption and requires algorithm parameters that
  *     cannot be determined from the given key, or if the given key has a keysize that exceeds the
  *     maximum allowable keysize (as determined from the configured jurisdiction policy files).
  * @throws IOException if any of the files do not exist, are a directory rather than a regular
  *     file, or for some other reason cannot be opened for reading or if an I/O error occurs.
  * @throws IllegalBlockSizeException if the cipher is a block cipher, no padding has been
  *     requested (only in encryption mode), and the total input length of the data processed by
  *     this cipher is not a multiple of block size; or if this encryption algorithm is unable to
  *     process the input data provided.
  * @throws BadPaddingException if the cipher is in decryption mode, and (un)padding has been
  *     requested, but the decrypted data is not bounded by the appropriate padding bytes
  */
 public void encrypt(File input, File output, File keyFile)
     throws InvalidKeyException, IOException, IllegalBlockSizeException, BadPaddingException {
   if (debug) {
     System.out.println("Initializing encryption...");
   }
   cipher.init(Cipher.ENCRYPT_MODE, key);
   FileInputStream fis = null;
   try {
     fis = new FileInputStream(input);
     data = new byte[(int) input.length()];
     if (debug) {
       System.out.println("Reading data...");
     }
     fis.read(data);
   } finally {
     if (fis != null) {
       fis.close();
     }
   }
   if (debug) {
     System.out.println("Encrypting data...");
   }
   data = cipher.doFinal(data);
   FileOutputStream fos = null;
   try {
     fos = new FileOutputStream(output);
     if (debug) {
       System.out.println("Saving data...");
     }
     fos.write(data);
   } finally {
     if (fos != null) {
       fos.close();
     }
   }
   if (debug) {
     System.out.println("Saving key...");
   }
   data = key.getEncoded();
   fos = null;
   try {
     fos = new FileOutputStream(keyFile);
     fos.write(data);
   } finally {
     if (fos != null) {
       fos.close();
     }
   }
   if (debug) {
     System.out.println("Encryption complete!");
   }
   data = null;
 }
예제 #12
0
  // <editor-fold desc="Class Constructor" defaultstate="collapsed">
  public AES256Encrypt(char[] plaintext, char[] key)
      throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
          IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException {

    // We have to convert the real key into a hash that can fit into the AES algorithm.
    hash = new SHA256Hash(key);
    secretKey = new SecretKeySpec(hash.getHash().getEncoded(), encryptionAlgorithm);

    // Creating the actual cipher
    cipher = Cipher.getInstance(encryptionAlgorithm);
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);
    encryptedCipher = cipher.doFinal(new String(plaintext).getBytes());
  }
예제 #13
0
  public Encrypter() {
    try {
      SecretKey key = KeyGenerator.getInstance("DES").generateKey();
      ecipher = Cipher.getInstance("DES");
      dcipher = Cipher.getInstance("DES");
      ecipher.init(Cipher.ENCRYPT_MODE, key);
      dcipher.init(Cipher.DECRYPT_MODE, key);

    } catch (javax.crypto.NoSuchPaddingException e) {
    } catch (java.security.NoSuchAlgorithmException e) {
    } catch (java.security.InvalidKeyException e) {
    }
  }
 public static String encodeWithBase64(String paramString) {
   SecretKeySpec localSecretKeySpec = new SecretKeySpec(BaseSecretKey, "AES");
   try {
     byte[] arrayOfByte = paramString.getBytes();
     Cipher localCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
     localCipher.init(Cipher.ENCRYPT_MODE, localSecretKeySpec);
     //      String str = Base64.encodeBase64String(localCipher.doFinal(arrayOfByte));
     String str = new String(Base64.encode(localCipher.doFinal(arrayOfByte), Base64.DEFAULT));
     return str;
   } catch (Exception localException) {
   }
   return null;
 }
예제 #15
0
  /**
   * Decrypts the given input data.
   *
   * @param in data to decrypt
   * @param k secret key
   * @param a encryption algorithm
   * @param ivl initialization vector length
   * @return decrypted data
   * @throws NoSuchAlgorithmException ex
   * @throws NoSuchPaddingException ex
   * @throws InvalidKeyException ex
   * @throws InvalidAlgorithmParameterException ex
   * @throws IllegalBlockSizeException ex
   * @throws BadPaddingException ex
   */
  private static byte[] decrypt(final byte[] in, final byte[] k, final byte[] a, final int ivl)
      throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
          InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {

    final SecretKeySpec keySpec = new SecretKeySpec(k, string(a));
    final Cipher cipher = Cipher.getInstance(string(ALGN.get(lc(a))));

    // extract iv from message beginning
    final byte[] iv = substring(in, 0, ivl);
    final IvParameterSpec ivspec = new IvParameterSpec(iv);
    cipher.init(Cipher.DECRYPT_MODE, keySpec, ivspec);
    return cipher.doFinal(substring(in, ivl, in.length));
  }
예제 #16
0
 private static Cipher func_75886_a(int p_75886_0_, String p_75886_1_, Key p_75886_2_) {
   try {
     Cipher cipher = Cipher.getInstance(p_75886_1_);
     cipher.init(p_75886_0_, p_75886_2_);
     return cipher;
   } catch (InvalidKeyException invalidkeyexception) {
     invalidkeyexception.printStackTrace();
   } catch (NoSuchAlgorithmException nosuchalgorithmexception) {
     nosuchalgorithmexception.printStackTrace();
   } catch (NoSuchPaddingException nosuchpaddingexception) {
     nosuchpaddingexception.printStackTrace();
   }
   System.err.println("Cipher creation failed!");
   return null;
 }
  public static byte[] decode64(byte[] paramArrayOfByte) {
    SecretKeySpec localSecretKeySpec = new SecretKeySpec(BaseSecretKey, "AES");
    try {
      //      byte[] arrayOfByte1 = Base64.decodeBase64(paramArrayOfByte);
      byte[] arrayOfByte1 = Base64.decode(paramArrayOfByte, Base64.DEFAULT);

      Cipher localCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      localCipher.init(Cipher.DECRYPT_MODE, localSecretKeySpec);
      byte[] arrayOfByte2 = localCipher.doFinal(arrayOfByte1);
      return arrayOfByte2;
    } catch (Exception localException) {
      localException.printStackTrace();
    }
    return null;
  }
예제 #18
0
 void initCipher() {
   try {
     b64Decoder = new BASE64Decoder();
     b64Encoder = new BASE64Encoder();
     Provider sunJce = new com.sun.crypto.provider.SunJCE();
     Security.addProvider(sunJce);
     byte[] raw = b64Decoder.decodeBuffer(key);
     SecretKeySpec skeySpec = new SecretKeySpec(raw, "Blowfish");
     deCipher = Cipher.getInstance("Blowfish");
     deCipher.init(Cipher.DECRYPT_MODE, skeySpec);
     enCipher = Cipher.getInstance("Blowfish");
     enCipher.init(Cipher.ENCRYPT_MODE, skeySpec);
   } catch (Exception ex) {
     textPane.setText("Unable to create the cipher");
   }
 }
 /**
  * Extract the enclosed PKCS8EncodedKeySpec object from the encrypted data and return it.
  *
  * @return the PKCS8EncodedKeySpec object.
  * @exception InvalidKeySpecException if the given cipher is inappropriate for the encrypted data
  *     or the encrypted data is corrupted and cannot be decrypted.
  */
 public PKCS8EncodedKeySpec getKeySpec(Cipher c) throws InvalidKeySpecException {
   try {
     return new PKCS8EncodedKeySpec(c.doFinal(this.getEncryptedData()));
   } catch (Exception e) {
     throw new InvalidKeySpecException("can't get keySpec: " + e.toString());
   }
 }
 public static byte[] encryptData(Key key, byte[] toEncrypt) {
   try {
     Cipher cipher = Cipher.getInstance(key.getAlgorithm());
     cipher.init(Cipher.ENCRYPT_MODE, key);
     return cipher.doFinal(toEncrypt);
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (NoSuchPaddingException e) {
     e.printStackTrace();
   } catch (InvalidKeyException e) {
     e.printStackTrace();
   } catch (BadPaddingException e) {
     e.printStackTrace();
   } catch (IllegalBlockSizeException e) {
     e.printStackTrace();
   }
   return new byte[0];
 }
예제 #21
0
 private String decrypt(String s) {
   try {
     byte[] encrypted = b64Decoder.decodeBuffer(s);
     byte[] decrypted = deCipher.doFinal(encrypted);
     return new String(decrypted);
   } catch (Exception ex) {
     return "error";
   }
 }
예제 #22
0
 public String decrypt(String str) {
   try {
     return new String(cipherDecrypt.doFinal(StringUtils.hex2byte(str)), "UTF8");
   } catch (UnsupportedEncodingException e) {
   } catch (BadPaddingException e) {
   } catch (IllegalBlockSizeException e) {
   }
   return null;
 }
예제 #23
0
 public String encrypt(String str) {
   try {
     return StringUtils.byte2hex(cipherEncrypt.doFinal(str.getBytes("UTF8")));
   } catch (UnsupportedEncodingException e) {
   } catch (BadPaddingException e) {
   } catch (IllegalBlockSizeException e) {
   }
   return null;
 }
예제 #24
0
파일: DESPlus.java 프로젝트: hebut/jxkh
 /**
  * 加密字节数组
  *
  * @param arrB 需加密的字节数组
  * @return 加密后的字节数组
  * @throws Exception
  */
 public byte[] encrypt(byte[] arrB) {
   try {
     return encryptCipher.doFinal(arrB);
   } catch (IllegalBlockSizeException e) {
     e.printStackTrace();
   } catch (BadPaddingException e) {
     e.printStackTrace();
   }
   return arrB;
 }
예제 #25
0
 @SuppressWarnings("restriction")
 public String getencrypt(String p) throws Exception {
   String encrypted = "";
   try {
     KeyGenerator kgen = KeyGenerator.getInstance("AES");
     kgen.init(128, new SecureRandom(KEY.getBytes()));
     SecretKey skey = kgen.generateKey();
     byte[] raw = skey.getEncoded();
     SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
     Cipher cipher = Cipher.getInstance("AES");
     cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
     byte[] encrypt = cipher.doFinal(p.getBytes());
     encrypted = new BASE64Encoder().encodeBuffer(encrypt).trim();
     // System.out.println("encrypted="+encrypted);
   } // try
   catch (Exception e) {
     System.out.println(e);
   }
   return encrypted; // return 密文
 }
예제 #26
0
  /**
   * Encrypts the given input data.
   *
   * @param in input data to encrypt
   * @param k key
   * @param a encryption algorithm
   * @param ivl initialization vector length
   * @return encrypted input data
   * @throws InvalidKeyException ex
   * @throws InvalidAlgorithmParameterException ex
   * @throws NoSuchAlgorithmException ex
   * @throws NoSuchPaddingException ex
   * @throws IllegalBlockSizeException ex
   * @throws BadPaddingException ex
   */
  private static byte[] encrypt(final byte[] in, final byte[] k, final byte[] a, final int ivl)
      throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
          NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {

    final Cipher cipher = Cipher.getInstance(string(ALGN.get(lc(a))));
    final SecretKeySpec kspec = new SecretKeySpec(k, string(a));
    // generate random iv. random iv is necessary to make the encryption of a
    // string look different every time it is encrypted.
    final byte[] iv = new byte[ivl];
    // create new random iv if encrypting
    final SecureRandom rand = SecureRandom.getInstance("SHA1PRNG");
    rand.nextBytes(iv);
    final IvParameterSpec ivspec = new IvParameterSpec(iv);

    // encrypt/decrypt
    cipher.init(Cipher.ENCRYPT_MODE, kspec, ivspec);
    final byte[] t = cipher.doFinal(in);
    // initialization vector is appended to the message for later decryption
    return concat(iv, t);
  }
예제 #27
0
  /** Creates a new instance of Encrypter */
  public AltEncrypter(String passPhrase) {

    try {
      SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
      sr.setSeed(passPhrase.getBytes("UTF8"));
      KeyGenerator kGen = KeyGenerator.getInstance("DESEDE");
      kGen.init(168, sr);
      Key key = kGen.generateKey();

      cipherEncrypt = Cipher.getInstance("DESEDE/ECB/PKCS5Padding");
      cipherEncrypt.init(Cipher.ENCRYPT_MODE, key);

      cipherDecrypt = Cipher.getInstance("DESEDE/ECB/PKCS5Padding");
      cipherDecrypt.init(Cipher.DECRYPT_MODE, key);
    } catch (UnsupportedEncodingException e) {
    } catch (NoSuchPaddingException e) {
    } catch (NoSuchAlgorithmException e) {
    } catch (InvalidKeyException e) {
    }
  }
  public String get_K() {
    if (rsa_key.length() < 2) return null;
    Cipher localCipher;
    byte[] arrayOfByte = null;

    PublicKey localPublicKey;
    try {
      //		byte[] b = Base64.decode(rsa_key);
      byte[] b = Base64.decode(rsa_key, Base64.DEFAULT);
      X509EncodedKeySpec sp = new X509EncodedKeySpec(b);
      localPublicKey = KeyFactory.getInstance("RSA").generatePublic(sp);
      localCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
      localCipher.init(Cipher.ENCRYPT_MODE, localPublicKey);
      arrayOfByte = localCipher.doFinal(aes_key.getBytes("utf-8"));
    } catch (Exception e) {
      // e.printStackTrace();
      return null;
    }
    //	return new String(Base64.encode(arrayOfByte));
    return new String(Base64.encode(arrayOfByte, Base64.DEFAULT));
  }
예제 #29
0
  public String getdecrypt(String base64) throws Exception {
    String decrypted = "";
    try {
      @SuppressWarnings("restriction")
      byte[] b = new BASE64Decoder().decodeBuffer(base64);
      KeyGenerator kgen2 = KeyGenerator.getInstance("AES");
      kgen2.init(128, new SecureRandom(KEY.getBytes()));
      SecretKey skey2 = kgen2.generateKey();
      byte[] raw2 = skey2.getEncoded();
      SecretKeySpec skeySpec2 = new SecretKeySpec(raw2, "AES");
      Cipher cipher2 = Cipher.getInstance("AES");
      cipher2.init(Cipher.DECRYPT_MODE, skeySpec2);
      byte[] decrypt = cipher2.doFinal(b);
      decrypted = new String(decrypt);
      // System.out.println("decrypted="+decrypted);

    } catch (Exception e) {
      System.out.println(e);
    }
    return decrypted;
  }
예제 #30
0
  /**
   * Uses a cipher to transform the bytes in an input stream and sends the transformed bytes to an
   * output stream.
   *
   * @param in the input stream
   * @param out the output stream
   * @param cipher the cipher that transforms the bytes
   */
  public static void crypt(InputStream in, OutputStream out, Cipher cipher)
      throws IOException, GeneralSecurityException {
    int blockSize = cipher.getBlockSize();
    int outputSize = cipher.getOutputSize(blockSize);
    byte[] inBytes = new byte[blockSize];
    byte[] outBytes = new byte[outputSize];

    int inLength = 0;
    ;
    boolean more = true;
    while (more) {
      inLength = in.read(inBytes);
      if (inLength == blockSize) {
        int outLength = cipher.update(inBytes, 0, blockSize, outBytes);
        out.write(outBytes, 0, outLength);
      } else more = false;
    }
    if (inLength > 0) outBytes = cipher.doFinal(inBytes, 0, inLength);
    else outBytes = cipher.doFinal();
    out.write(outBytes);
  }