Java 类javax.crypto.SecretKey 实例源码

项目:GOF    文件:AesEncryptionStrategy.java   
@Override
public void encryptData(String plaintext) {
   System.out.println("-------Encrypting data using AES algorithm-------");
   try {
       KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
       keyGenerator.init(128);
       SecretKey secretKey = keyGenerator.generateKey();
       byte[] plaintTextByteArray = plaintext.getBytes("UTF8");

       Cipher cipher = Cipher.getInstance("AES");
       cipher.init(Cipher.ENCRYPT_MODE, secretKey);
       byte[] cipherText = cipher.doFinal(plaintTextByteArray);

       System.out.println("Original data: " + plaintext);
       System.out.println("Encrypted data:");
       for (int i = 0; i < cipherText.length; i++) {
           System.out.print(cipherText[i] + " ");

       }
   }
       catch(Exception ex){
           ex.printStackTrace();
       }
   }
项目:Spring-Boot-Server    文件:DES.java   
/**
* 加密
* @param datasource byte[]
* @param password String
* @return byte[]
*/
public static String encrypt(String datasource, String password) {
    try {
        if(StringUtils.trimToNull(datasource) == null){
            return null;
        }
        SecureRandom random = new SecureRandom();
        DESKeySpec desKey = new DESKeySpec(password.getBytes());
        // 创建一个密匙工厂,然后用它把DESKeySpec转换成
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey securekey = keyFactory.generateSecret(desKey);
        // Cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance("DES");
        // 用密匙初始化Cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
        // 现在,获取数据并加密
        // 正式执行加密操作
         return new BASE64Encoder().encode(cipher.doFinal(datasource.getBytes()));

    } catch (Throwable e) {
        e.printStackTrace();
    }
    return null;
}
项目:plugin-sso-salt    文件:SaltedAuthenticationResource.java   
/**
 * Encrypt the message with the given key.
 * 
 * @param message
 *            Ciphered message.
 * @param secretKey
 *            The secret key.
 * @return the original message.
 */
protected String encrypt(final String message, final String secretKey) throws Exception { // NOSONAR
    // SSO digest algorithm used for password. This
    final MessageDigest md = MessageDigest.getInstance(getDigest());
    final byte[] digestOfPassword = md.digest(secretKey.getBytes(StandardCharsets.UTF_8));
    final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);

    // Cipher implementation.
    final String algo = get("sso.crypt", DEFAULT_IMPL);

    final SecretKey key = new SecretKeySpec(keyBytes, algo);
    final Cipher cipher = Cipher.getInstance(algo);
    cipher.init(Cipher.ENCRYPT_MODE, key);
    final byte[] plainTextBytes = message.getBytes(StandardCharsets.UTF_8);
    final byte[] buf = cipher.doFinal(plainTextBytes);
    final byte[] base64Bytes = Base64.encodeBase64(buf);
    return new String(base64Bytes, StandardCharsets.UTF_8);
}
项目:Android_Code_Arbiter    文件:ConstantIv.java   
public static void encryptIvNotInitialize2(String message) throws Exception {

        //IV
        IvParameterSpec ivSpec = new IvParameterSpec(new byte[] {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16});  //Oups. Static

        //Key
        KeyGenerator generator = KeyGenerator.getInstance("AES");
        generator.init(128);
        SecretKey secretKey = generator.generateKey();

        //Encrypt
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
        cipher.update(message.getBytes());

        byte[] data = cipher.doFinal();
        System.out.println(HexUtil.toString(data));
    }
项目:openjdk-jdk10    文件:SecretKeySpec.java   
/**
 * Tests for equality between the specified object and this
 * object. Two SecretKeySpec objects are considered equal if
 * they are both SecretKey instances which have the
 * same case-insensitive algorithm name and key encoding.
 *
 * @param obj the object to test for equality with this object.
 *
 * @return true if the objects are considered equal, false if
 * <code>obj</code> is null or otherwise.
 */
public boolean equals(Object obj) {
    if (this == obj)
        return true;

    if (!(obj instanceof SecretKey))
        return false;

    String thatAlg = ((SecretKey)obj).getAlgorithm();
    if (!(thatAlg.equalsIgnoreCase(this.algorithm))) {
        if ((!(thatAlg.equalsIgnoreCase("DESede"))
             || !(this.algorithm.equalsIgnoreCase("TripleDES")))
            && (!(thatAlg.equalsIgnoreCase("TripleDES"))
                || !(this.algorithm.equalsIgnoreCase("DESede"))))
        return false;
    }

    byte[] thatKey = ((SecretKey)obj).getEncoded();

    return MessageDigest.isEqual(this.key, thatKey);
}
项目:jdk8u-jdk    文件:HandshakeMessage.java   
private static void updateDigest(MessageDigest md,
        byte[] pad1, byte[] pad2,
        SecretKey masterSecret) {
    // Digest the key bytes if available.
    // Otherwise (sensitive key), try digesting the key directly.
    // That is currently only implemented in SunPKCS11 using a private
    // reflection API, so we avoid that if possible.
    byte[] keyBytes = "RAW".equals(masterSecret.getFormat())
                    ? masterSecret.getEncoded() : null;
    if (keyBytes != null) {
        md.update(keyBytes);
    } else {
        digestKey(md, masterSecret);
    }
    md.update(pad1);
    byte[] temp = md.digest();

    if (keyBytes != null) {
        md.update(keyBytes);
    } else {
        digestKey(md, masterSecret);
    }
    md.update(pad2);
    md.update(temp);
}
项目:jdk8u-jdk    文件:SecretKeySpec.java   
/**
 * Tests for equality between the specified object and this
 * object. Two SecretKeySpec objects are considered equal if
 * they are both SecretKey instances which have the
 * same case-insensitive algorithm name and key encoding.
 *
 * @param obj the object to test for equality with this object.
 *
 * @return true if the objects are considered equal, false if
 * <code>obj</code> is null or otherwise.
 */
public boolean equals(Object obj) {
    if (this == obj)
        return true;

    if (!(obj instanceof SecretKey))
        return false;

    String thatAlg = ((SecretKey)obj).getAlgorithm();
    if (!(thatAlg.equalsIgnoreCase(this.algorithm))) {
        if ((!(thatAlg.equalsIgnoreCase("DESede"))
             || !(this.algorithm.equalsIgnoreCase("TripleDES")))
            && (!(thatAlg.equalsIgnoreCase("TripleDES"))
                || !(this.algorithm.equalsIgnoreCase("DESede"))))
        return false;
    }

    byte[] thatKey = ((SecretKey)obj).getEncoded();

    return MessageDigest.isEqual(this.key, thatKey);
}
项目:GravityBox    文件:FingerprintLauncher.java   
private void initFingerprintManager() throws Throwable {
    mFpManager = (FingerprintManager) mContext.getSystemService(Context.FINGERPRINT_SERVICE);
    if (!mFpManager.isHardwareDetected())
        throw new IllegalStateException("Fingerprint hardware not present");

    KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
    KeyGenerator keyGenerator = KeyGenerator.getInstance(
            KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
    keyStore.load(null);
    keyGenerator.init(new KeyGenParameterSpec.Builder(
            KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
            .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
            .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
            .build());
    keyGenerator.generateKey();

    Cipher cipher = Cipher.getInstance(
            KeyProperties.KEY_ALGORITHM_AES + "/" +
            KeyProperties.BLOCK_MODE_CBC + "/" +
            KeyProperties.ENCRYPTION_PADDING_PKCS7);
    SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME, null);
    cipher.init(Cipher.ENCRYPT_MODE, key);

    mFpHandler = new FingerprintHandler(cipher);

    if (DEBUG) log("Fingeprint manager initialized");
}
项目:OpenJSharp    文件:SslMacCore.java   
/**
 * Initializes the Mac with the given secret key and algorithm parameters.
 *
 * @param key the secret key.
 * @param params the algorithm parameters.
 *
 * @exception InvalidKeyException if the given key is inappropriate for
 * initializing this MAC.
 * @exception InvalidAlgorithmParameterException if the given algorithm
 * parameters are inappropriate for this MAC.
 */
void init(Key key, AlgorithmParameterSpec params)
        throws InvalidKeyException, InvalidAlgorithmParameterException {

    if (params != null) {
        throw new InvalidAlgorithmParameterException
            ("SslMac does not use parameters");
    }

    if (!(key instanceof SecretKey)) {
        throw new InvalidKeyException("Secret key expected");
    }

    secret = key.getEncoded();
    if (secret == null || secret.length == 0) {
        throw new InvalidKeyException("Missing key data");
    }

    reset();
}
项目:TIIEHenry-Android-SDK    文件:DESUtils.java   
/**
 * DES
 * @param src
 * @param password
 * @return
 */
public static byte[] decrypt(byte []src, String password) {
    try {
        // DES算法要求有一个可信任的随机数源
        SecureRandom random = new SecureRandom();
        // 创建一个DESKeySpec对象
        DESKeySpec desKey = new DESKeySpec(password.getBytes());
        // 创建一个密匙工厂
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        // 将DESKeySpec对象转换成SecretKey对象
        SecretKey securekey = keyFactory.generateSecret(desKey);
        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance("DES");
        // 用密匙初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, securekey, random);
        // 真正开始解密操作
        return cipher.doFinal(src);
    } catch (Throwable e) {
        e.printStackTrace();
    }

    return null;
}
项目:openjdk-jdk10    文件:KeyInfoReferenceResolver.java   
/** {@inheritDoc}. */
public SecretKey engineLookupAndResolveSecretKey(Element element, String baseURI, StorageResolver storage)
    throws KeyResolverException {

    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName());
    }

    if (!engineCanResolve(element, baseURI, storage)) {
        return null;
    }

    try {
        KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage);
        if (referent != null) {
            return referent.getSecretKey();
        }
    } catch (XMLSecurityException e) {
        if (log.isLoggable(java.util.logging.Level.FINE)) {
            log.log(java.util.logging.Level.FINE, "XMLSecurityException", e);
        }
    }

    return null;
}
项目:openjdk-jdk10    文件:DESedeKey.java   
public boolean equals(Object obj) {
    if (this == obj)
        return true;

    if (!(obj instanceof SecretKey))
        return false;

    String thatAlg = ((SecretKey)obj).getAlgorithm();
    if (!(thatAlg.equalsIgnoreCase("DESede"))
        && !(thatAlg.equalsIgnoreCase("TripleDES")))
        return false;

    byte[] thatKey = ((SecretKey)obj).getEncoded();
    boolean ret = MessageDigest.isEqual(this.key, thatKey);
    java.util.Arrays.fill(thatKey, (byte)0x00);
    return ret;
}
项目:RISE-V2G    文件:SecurityUtils.java   
/**
    * Encrypts the private key of the contract certificate which is to be sent to the EVCC. First, the
    * shared secret based on the ECDH parameters is calculated, then the symmetric session key with which
    * the private key of the contract certificate is to be encrypted.
    * 
    * @param certificateECPublicKey The public key of either the OEM provisioning certificate (in case of 
    *                                CertificateInstallation) or the to be updated contract certificate
    *                                (in case of CertificateUpdate)
    * @param ecKeyPair The EC keypair
    * @param contractCertPrivateKey The private key of the contract certificate
    * @return The encrypted private key of the to be installed contract certificate
    */
public static ContractSignatureEncryptedPrivateKeyType encryptContractCertPrivateKey(
        ECPublicKey certificateECPublicKey, 
        KeyPair ecKeyPair,
        ECPrivateKey contractCertPrivateKey) {
    // Generate the shared secret by using the public key of either OEMProvCert or ContractCert
    byte[] sharedSecret = generateSharedSecret((ECPrivateKey) ecKeyPair.getPrivate(), certificateECPublicKey);

    if (sharedSecret == null) {
        getLogger().error("Shared secret could not be generated");
        return null;
    }

    // The session key is generated using the computed shared secret
    SecretKey sessionKey = generateSessionKey(sharedSecret);

    // Finally, the private key of the contract certificate is encrypted using the session key
    ContractSignatureEncryptedPrivateKeyType encryptedContractCertPrivateKey = 
            getContractSignatureEncryptedPrivateKey(sessionKey, contractCertPrivateKey);

    return encryptedContractCertPrivateKey;
}
项目:MyFire    文件:DESBase64Util.java   
/**
 * DES加密
 * 
 * @param src
 * @param key
 * @return
 * @throws Exception
 */
public static byte[] encrypt(byte[] src, byte[] key) throws Exception {
    // DES算法要求有一个可信任的随机数源
    SecureRandom sr = new SecureRandom();
    // 从原始密匙数据创建DESKeySpec对象
    DESKeySpec dks = new DESKeySpec(key);
    // 创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
    SecretKey securekey = keyFactory.generateSecret(dks);
    // Cipher对象实际完成加密操作
    Cipher cipher = Cipher.getInstance(DES);
    // 用密匙初始化Cipher对象
    cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
    // 现在,获取数据并加密
    // 正式执行加密操作
    return cipher.doFinal(src);
}
项目:MyFire    文件:DESBase64Util.java   
/**
 * DES解密
 * 
 * @param src
 * @param key
 * @return
 * @throws Exception
 */
public static byte[] decrypt(byte[] src, byte[] key) throws Exception {
    // DES算法要求有一个可信任的随机数源
    SecureRandom sr = new SecureRandom();
    // 从原始密匙数据创建一个DESKeySpec对象
    DESKeySpec dks = new DESKeySpec(key);
    // 创建一个密匙工厂,然后用它把DESKeySpec对象转换成
    // 一个SecretKey对象
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
    SecretKey securekey = keyFactory.generateSecret(dks);
    // Cipher对象实际完成解密操作
    Cipher cipher = Cipher.getInstance(DES);
    // 用密匙初始化Cipher对象
    cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
    // 现在,获取数据并解密
    // 正式执行解密操作
    return cipher.doFinal(src);
}
项目:jdk8u-jdk    文件:PBKDF2Translate.java   
/**
 * The test case scenario implemented in the method: - create my own secret
 * Key2 as an instance of a class implements PBEKey - spoil the key (set
 * iteration count to 0, for example) - try to translate key -
 * InvalidKeyException is expected.
 *
 * @return true if InvalidKeyException occurred; false - otherwise.
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public boolean translateSpoiledKey() throws NoSuchAlgorithmException,
        InvalidKeySpecException {
    // derive the key
    SecretKey key1 = getMyOwnSecretKey();

    // spoil the key
    ((MyPBKDF2SecretKey) key1).spoil();

    // translate key
    SecretKeyFactory skf = SecretKeyFactory.getInstance(algoToTest);
    try {
        SecretKey key2 = skf.translateKey(key1);
    } catch (InvalidKeyException ike) {
        // this is expected
        return true;
    }

    return false;
}
项目:openjdk-jdk10    文件:SslMacCore.java   
/**
 * Initializes the Mac with the given secret key and algorithm parameters.
 *
 * @param key the secret key.
 * @param params the algorithm parameters.
 *
 * @exception InvalidKeyException if the given key is inappropriate for
 * initializing this MAC.
 * @exception InvalidAlgorithmParameterException if the given algorithm
 * parameters are inappropriate for this MAC.
 */
void init(Key key, AlgorithmParameterSpec params)
        throws InvalidKeyException, InvalidAlgorithmParameterException {

    if (params != null) {
        throw new InvalidAlgorithmParameterException
            ("SslMac does not use parameters");
    }

    if (!(key instanceof SecretKey)) {
        throw new InvalidKeyException("Secret key expected");
    }

    secret = key.getEncoded();
    if (secret == null || secret.length == 0) {
        throw new InvalidKeyException("Missing key data");
    }

    reset();
}
项目:mi-firma-android    文件:JseCryptoHelper.java   
private static byte[] doDesede(final byte[] data, final byte[] key, final int direction) throws IOException {
    final byte[] ivBytes = new byte[8];
    for (int i = 0; i < 8; i++) {
        ivBytes[i] = 0x00;
    }

    final SecretKey k = new SecretKeySpec(prepareDesedeKey(key), "DESede"); //$NON-NLS-1$
    try {
        final Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding"); //$NON-NLS-1$
        cipher.init(direction, k, new IvParameterSpec(ivBytes));
        final byte[] cipheredData = cipher.doFinal(data);
        // Machacamos los datos para evitar que queden en memoria
        for(int i=0;i<data.length;i++) {
            data[i] = '\0';
        }
        return cipheredData;
    }
    catch (final Exception e) {
        // Machacamos los datos para evitar que queden en memoria
        for(int i=0;i<data.length;i++) {
            data[i] = '\0';
        }
        throw new IOException("Error encriptando datos: " + e, e); //$NON-NLS-1$
    }
}
项目:openjdk-jdk10    文件:DESedeKeyFactory.java   
/**
 * Generates a <code>SecretKey</code> object from the provided key
 * specification (key material).
 *
 * @param keySpec the specification (key material) of the secret key
 *
 * @return the secret key
 *
 * @exception InvalidKeySpecException if the given key specification
 * is inappropriate for this key factory to produce a public key.
 */
protected SecretKey engineGenerateSecret(KeySpec keySpec)
    throws InvalidKeySpecException {

    try {
        if (keySpec instanceof DESedeKeySpec) {
            return new DESedeKey(((DESedeKeySpec)keySpec).getKey());
        }
        if (keySpec instanceof SecretKeySpec) {
            return new DESedeKey(((SecretKeySpec)keySpec).getEncoded());

        }
        throw new InvalidKeySpecException
            ("Inappropriate key specification");
    } catch (InvalidKeyException e) {
        throw new InvalidKeySpecException(e.getMessage());
    }
}
项目:OAuth-2.0-Cookbook    文件:JweTokenSerializer.java   
public Map<String, Object> decode(String base64EncodedKey, String content) {
    try {
        byte[] decodedKey = Base64.getDecoder().decode(base64EncodedKey);
        SecretKey key = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
        JWEObject jwe = JWEObject.parse(content);
        jwe.decrypt(new AESDecrypter(key));

        ObjectMapper objectMapper = new ObjectMapper();
        ObjectReader reader = objectMapper.readerFor(Map.class);
        return reader.with(DeserializationFeature.USE_LONG_FOR_INTS)
                .readValue(jwe.getPayload().toString());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}
项目:openjdk-jdk10    文件:PBEKeyCleanupTest.java   
static void testCleanupSecret(String algorithm, SecretKey key) throws Exception {

        // Break into the implementation to observe the key byte array.
        Class<?> keyClass = key.getClass();
        Field keyField = keyClass.getDeclaredField("key");
        keyField.setAccessible(true);
        byte[] array = (byte[])keyField.get(key);

        byte[] zeros = new byte[array.length];
        do {
            // Wait for array to be cleared;  if not cleared test will timeout
            System.out.printf("%s array: %s%n", algorithm, Arrays.toString(array));
            key = null;
            System.gc();        // attempt to reclaim the key
        } while (Arrays.compare(zeros, array) != 0);
        System.out.printf("%s array: %s%n", algorithm, Arrays.toString(array));

        Reference.reachabilityFence(key); // Keep key alive
        Reference.reachabilityFence(array); // Keep array alive
    }
项目:DRM-Desktop    文件:Security.java   
public static String getDecryptedMessage(byte[] message) throws GeneralSecurityException {
    byte[] salt = Arrays.copyOfRange(message, 0, SALT_SIZE);
    byte[] iv = Arrays.copyOfRange(message, SALT_SIZE, 16 + SALT_SIZE);
    message = Arrays.copyOfRange(message, 16 + SALT_SIZE, message.length);
    SecretKey key = getEncryptionKey(Config.SECRET_KEY.toCharArray(), salt);

    return decrypt(key, iv, message);
}
项目:NoteBuddy    文件:AesCbcWithIntegrity.java   
/**
 * A function that generates random AES & HMAC keys and prints out exceptions but
 * doesn't throw them since none should be encountered. If they are
 * encountered, the return value is null.
 *
 * @return The AES & HMAC keys.
 * @throws GeneralSecurityException if AES is not implemented on this system,
 *                                  or a suitable RNG is not available
 */
public static SecretKeys generateKey() throws GeneralSecurityException {
    fixPrng();
    KeyGenerator keyGen = KeyGenerator.getInstance(CIPHER);
    // No need to provide a SecureRandom or set a seed since that will
    // happen automatically.
    keyGen.init(AES_KEY_LENGTH_BITS);
    SecretKey confidentialityKey = keyGen.generateKey();

    //Now make the HMAC key
    byte[] integrityKeyBytes = randomBytes(HMAC_KEY_LENGTH_BITS / 8);//to get bytes
    SecretKey integrityKey = new SecretKeySpec(integrityKeyBytes, HMAC_ALGORITHM);

    return new SecretKeys(confidentialityKey, integrityKey);
}
项目:CustomWorldGen    文件:NetworkManager.java   
/**
 * Adds an encoder+decoder to the channel pipeline. The parameter is the secret key used for encrypted communication
 */
public void enableEncryption(SecretKey key)
{
    this.isEncrypted = true;
    this.channel.pipeline().addBefore("splitter", "decrypt", new NettyEncryptingDecoder(CryptManager.createNetCipherInstance(2, key)));
    this.channel.pipeline().addBefore("prepender", "encrypt", new NettyEncryptingEncoder(CryptManager.createNetCipherInstance(1, key)));
}
项目:MovingGdufe-Android    文件:AESUtils.java   
private static byte[] getRawKey(byte[] seed) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", new CryptoProvider());   //原第二个参数为 "Crypto",现兼容7.0而new个类
    sr.setSeed(seed);
    kgen.init(128, sr);
    SecretKey skey = kgen.generateKey();
    byte[] raw = skey.getEncoded();
    return raw;
}
项目:PeSanKita-android    文件:MasterSecretUtil.java   
private static Mac getMacForPassphrase(String passphrase, byte[] salt, int iterations)
    throws GeneralSecurityException
{
  SecretKey     key     = getKeyFromPassphrase(passphrase, salt, iterations);
  byte[]        pbkdf2  = key.getEncoded();
  SecretKeySpec hmacKey = new SecretKeySpec(pbkdf2, "HmacSHA1");
  Mac           hmac    = Mac.getInstance("HmacSHA1");
  hmac.init(hmacKey);

  return hmac;
}
项目:googles-monorepo-demo    文件:MacHashFunctionTest.java   
private static void assertMacHashing(
    byte[] input, String algorithm, SecretKey key, HashFunction hashFunc) throws Exception {
  Mac mac = Mac.getInstance(algorithm);
  mac.init(key);
  mac.update(input);

  assertEquals(HashCode.fromBytes(mac.doFinal()), hashFunc.hashBytes(input));
  assertEquals(HashCode.fromBytes(mac.doFinal(input)), hashFunc.hashBytes(input));
}
项目:hackmelock-android    文件:DeviceControlActivity.java   
/**
 * Pairing in config mode
 */
public void startPairing() {
    Log.d("Pairing","START");
    hackmelockDevice.status=HackmelockDevice.Status.PAIRING;

    Random r = new Random();
    int Major = r.nextInt(65535);
    int Minor = r.nextInt(65535);

    hackmelockDevice.Major = Major;
    hackmelockDevice.Minor = Minor;

    Log.d("Pairing","Major: " + Integer.toString(Major) + " Minor: " + Integer.toString(Minor));
    displayData("Pairing - Major:" + Integer.toString(Major) + " Minor:" + Integer.toString(Minor));

    byte[] value = utils.majorMinorToByteArray(Major, Minor);
    mBluetoothLeService.queueWriteDataToCharacteristic(hackmelockCommandChar,value);

    for (int i = 0; i<24; i++) {
        try {
            KeyGenerator keyGen = KeyGenerator.getInstance("AES");
            keyGen.init(96);
            SecretKey secretKey = keyGen.generateKey();
            hackmelockDevice.keys[i] = secretKey.getEncoded();

            mBluetoothLeService.queueWriteDataToCharacteristic(hackmelockCommandChar,secretKey.getEncoded());
        }
        catch (NoSuchAlgorithmException e) {
            Log.e("Pairing", "CANNOT INITIALIZE AES RANDOM!!!");
            //tbd exception notification to user

        }
    }
    dbHelper.insertConfig(Major, Minor, "my lock", 1, 1, 0, 0);
    dbHelper.insertKeys(Major, Minor, hackmelockDevice.keys);
    hackmelockDevice.own=1;
    invalidateOptionsMenu();
}
项目:jdk8u-jdk    文件:ServerHandshaker.java   
private SecretKey clientKeyExchange(ECDHClientKeyExchange mesg)
        throws IOException {

    if (debug != null && Debug.isOn("handshake")) {
        mesg.print(System.out);
    }

    byte[] publicPoint = mesg.getEncodedPoint();

    // check algorithm constraints
    ecdh.checkConstraints(algorithmConstraints, publicPoint);

    return ecdh.getAgreedSecret(publicPoint);
}
项目:Android_Code_Arbiter    文件:InsufficientKeySizeBlowfish.java   
public SecretKey weakKeySize1() throws NoSuchAlgorithmException {
    KeyGenerator keyGen = KeyGenerator.getInstance("Blowfish");
    keyGen.init(64);

    SecretKey key = keyGen.generateKey();
    return key;
}
项目:automat    文件:HmacCoder.java   
/**
 * 初始化HmacMD5密钥
 * 
 * @return
 * @throws Exception
 */
public static byte[] initHmacMD5Key() throws Exception {
    // 初始化KeyGenerator
    KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacMD5");
    // 产生秘密密钥
    SecretKey secretKey = keyGenerator.generateKey();
    // 获得密钥
    return secretKey.getEncoded();
}
项目:mumu    文件:HmacCoder.java   
/**
 * HmacMD2消息摘要
 * 
 * @param data 待做消息摘要处理的数据
 * @param byte[] 密钥
 * @return byte[] 消息摘要
 * @throws Exception
 */
public static byte[] encodeHmacMD2(byte[] data, byte[] key) throws Exception {
    // 还原密钥
    SecretKey secretKey = new SecretKeySpec(key, "HmacMD2");
    // 实例化Mac
    Mac mac = Mac.getInstance(secretKey.getAlgorithm());
    // 初始化Mac
    mac.init(secretKey);
    // 执行消息摘要
    return mac.doFinal(data);
}
项目:mumu    文件:HmacCoder.java   
/**
 * 初始化HmacMD2密钥
 * 
 * @return byte[] 密钥
 * @throws Exception
 */
public static byte[] initHmacMD2Key() throws Exception {
    // 初始化KeyGenerator
    KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacMD2");
    // 产生秘密密钥
    SecretKey secretKey = keyGenerator.generateKey();
    // 获得密钥
    return secretKey.getEncoded();
}
项目:java-dukpt    文件:Dukpt.java   
/**
 * Performs Single DES Encryption.
 * 
 * @param key The key for encryption.
 * @param data The data to encrypt.
 * @param padding When true, PKCS5 Padding will be used.  This is most likely not desirable.
 * @return The encrypted.
 * @throws Exception
 */
public static byte[] encryptDes(byte[] key, byte[] data, boolean padding) throws Exception {
    IvParameterSpec iv = new IvParameterSpec(new byte[8]);
    SecretKey encryptKey = SecretKeyFactory.getInstance("DES").generateSecret(new DESKeySpec(key));
    Cipher encryptor;
    if (padding)
        encryptor = Cipher.getInstance("DES/CBC/PKCS5Padding");
    else
        encryptor = Cipher.getInstance("DES/CBC/NoPadding");
    encryptor.init(Cipher.ENCRYPT_MODE, encryptKey, iv);
    return encryptor.doFinal(data);
}
项目:xmanager    文件:JwtUtil.java   
/**
 * 由字符串生成加密key
 * @return
 */
public SecretKey generalKey(){
    String stringKey = Constant.JWT_SECRET;
    byte[] encodedKey = Base64.getDecoder().decode(stringKey);
    SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
    return key;
}
项目:buildAPKsSamples    文件:StringCryptor.java   
public static byte[] generateKey( byte[] seed ) throws Exception
{
    KeyGenerator keyGenerator = KeyGenerator.getInstance( CIPHER_ALGORITHM );
    SecureRandom secureRandom = SecureRandom.getInstance( RANDOM_GENERATOR_ALGORITHM );
    secureRandom.setSeed( seed );
    keyGenerator.init( RANDOM_KEY_SIZE, secureRandom );
    SecretKey secretKey = keyGenerator.generateKey();
    return secretKey.getEncoded();
}
项目:JAVA-    文件:HmacCoder.java   
/**
 * 初始化HmacSHA224密钥
 * 
 * @return byte[] 密钥
 * @throws Exception
 */
public static byte[] initHmacSHA224Key() throws Exception {
    // 初始化KeyGenerator
    KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacSHA224");
    // 产生秘密密钥
    SecretKey secretKey = keyGenerator.generateKey();
    // 获得密钥
    return secretKey.getEncoded();
}
项目:OpenJSharp    文件:ECDHCrypt.java   
SecretKey getAgreedSecret(PublicKey peerPublicKey) throws SSLHandshakeException {
    try {
        KeyAgreement ka = JsseJce.getKeyAgreement("ECDH");
        ka.init(privateKey);
        ka.doPhase(peerPublicKey, true);
        return ka.generateSecret("TlsPremasterSecret");
    } catch (GeneralSecurityException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
            "Could not generate secret").initCause(e);
    }
}
项目:edge-jwt-sample    文件:JWTValidatorTest.java   
@Test
public void testJWSWithExpiredJWT() {
    String claimsJSON = claims(SAMPLE_CLAIMS, "edge-jwt-gen", "aud-1", 0);
    SecretKey key = getHmacSHA512Key();
    String jwt = jwsSign(claimsJSON, key, "HMAC_SHA512");

    JWTValidator validator = jwsValidator(keyToString(key), "HMAC_SHA512", jwt, "edge-jwt-gen", "aud-1", "300");
    ExecutionResult result = validator.execute(this.mctx, this.ectx);

    verifyFailureResult(result);
}
项目:SecureUtils    文件:AES128PKCS5Padding.java   
private static SecretKey generateKeyAES128(String key)
        throws InvalidAlgorithmParameterException, UnsupportedEncodingException {
    if (key.getBytes().length != 16){
        throw new InvalidAlgorithmParameterException("Key length must be 16 bytes");
    }
    return new SecretKeySpec(key.getBytes(TEXT_ENCODING), KEY_ENCODING);
}