Java Examples for javax.crypto.spec.SecretKeySpec

The following java examples will help you to understand the usage of javax.crypto.spec.SecretKeySpec. These source code samples are taken from different open source projects.

Example 1
Project: atlas-lb-master  File: JceAsymmetricKeyUnwrapper.java View source code
public GenericKey generateUnwrappedKey(AlgorithmIdentifier encryptedKeyAlgorithm, byte[] encryptedKey) throws OperatorException {
    try {
        Key sKey = null;
        Cipher keyCipher = helper.createAsymmetricWrapper(this.getAlgorithmIdentifier().getAlgorithm());
        try {
            keyCipher.init(Cipher.UNWRAP_MODE, privKey);
            sKey = keyCipher.unwrap(encryptedKey, encryptedKeyAlgorithm.getAlgorithm().getId(), Cipher.SECRET_KEY);
        } catch (GeneralSecurityException e) {
        } catch (IllegalStateException e) {
        } catch (UnsupportedOperationException e) {
        } catch (ProviderException e) {
        }
        // some providers do not support UNWRAP (this appears to be only for asymmetric algorithms)
        if (sKey == null) {
            keyCipher.init(Cipher.DECRYPT_MODE, privKey);
            sKey = new SecretKeySpec(keyCipher.doFinal(encryptedKey), encryptedKeyAlgorithm.getAlgorithm().getId());
        }
        return new GenericKey(sKey);
    } catch (InvalidKeyException e) {
        throw new OperatorException("key invalid: " + e.getMessage(), e);
    } catch (IllegalBlockSizeException e) {
        throw new OperatorException("illegal blocksize: " + e.getMessage(), e);
    } catch (BadPaddingException e) {
        throw new OperatorException("bad padding: " + e.getMessage(), e);
    }
}
Example 2
Project: bc-java-master  File: ThreefishTest.java View source code
public void performTest() throws Exception {
    // padding test at 128 pad bytes.
    final SecretKey secretKey = new SecretKeySpec(SECRET_KEY_1024, "Threefish-1024");
    Cipher cipher = Cipher.getInstance("Threefish-1024/CBC/ISO10126Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(new byte[128]));
    byte[] iv = cipher.getIV();
    byte[] ciphertext = cipher.doFinal(TEST_BYTES);
    cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv));
    byte[] cleartext = cipher.doFinal(ciphertext);
    if (!Arrays.areEqual(TEST_BYTES, cleartext)) {
        fail("Invalid cleartext - ISO10126Padding.");
    }
    cipher = Cipher.getInstance("Threefish-1024/CBC/PKCS7Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);
    iv = cipher.getIV();
    ciphertext = cipher.doFinal(TEST_BYTES);
    cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv));
    cleartext = cipher.doFinal(ciphertext);
    if (!Arrays.areEqual(TEST_BYTES, cleartext)) {
        fail("Invalid cleartext - PKCS7.");
    }
}
Example 3
Project: irma_future_id-master  File: SipHashTest.java View source code
public void performTest() throws Exception {
    byte[] key = Hex.decode("000102030405060708090a0b0c0d0e0f");
    byte[] input = Hex.decode("000102030405060708090a0b0c0d0e");
    byte[] expected = Hex.decode("e545be4961ca29a1");
    Mac mac = Mac.getInstance("SipHash", "BC");
    mac.init(new SecretKeySpec(key, "SipHash"));
    mac.update(input, 0, input.length);
    byte[] result = mac.doFinal();
    if (!Arrays.areEqual(expected, result)) {
        fail("Result does not match expected value for doFinal()");
    }
    mac.init(new SecretKeySpec(key, "SipHash-2-4"));
    mac.update(input, 0, input.length);
    result = mac.doFinal();
    if (!Arrays.areEqual(expected, result)) {
        fail("Result does not match expected value for second doFinal()");
    }
    mac = Mac.getInstance("SipHash-2-4", "BC");
    mac.init(new SecretKeySpec(key, "SipHash-2-4"));
    mac.update(input, 0, input.length);
    result = mac.doFinal();
    if (!Arrays.areEqual(expected, result)) {
        fail("Result does not match expected value for alias");
    }
    // SipHash 4-8
    expected = Hex.decode("e0a6a97dd589d383");
    mac = Mac.getInstance("SipHash-4-8", "BC");
    mac.init(new SecretKeySpec(key, "SipHash"));
    mac.update(input, 0, input.length);
    result = mac.doFinal();
    if (!Arrays.areEqual(expected, result)) {
        fail("Result does not match expected value for SipHash 4-8");
    }
}
Example 4
Project: oobd-master  File: OperatorUtils.java View source code
static Key getJceKey(GenericKey key) {
    if (key.getRepresentation() instanceof Key) {
        return (Key) key.getRepresentation();
    }
    if (key.getRepresentation() instanceof byte[]) {
        return new SecretKeySpec((byte[]) key.getRepresentation(), "ENC");
    }
    throw new IllegalArgumentException("unknown generic key type");
}
Example 5
Project: keycloak-master  File: HmacTest.java View source code
@Test
public void testHmacSignatures() throws Exception {
    SecretKey secret = new SecretKeySpec(UUID.randomUUID().toString().getBytes(), "HmacSHA256");
    String encoded = new JWSBuilder().content("12345678901234567890".getBytes()).hmac256(secret);
    System.out.println("length: " + encoded.length());
    JWSInput input = new JWSInput(encoded);
    Assert.assertTrue(HMACProvider.verify(input, secret));
}
Example 6
Project: braintree_java-master  File: Sha256Hasher.java View source code
public String hmacHash(String privateKey, String content) {
    String hash = "";
    try {
        SecretKeySpec signingKey = new SecretKeySpec(sha256Bytes(privateKey), "SHA-256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(signingKey);
        byte[] rawMac = mac.doFinal(content.getBytes("UTF-8"));
        byte[] hexBytes = new Hex().encode(rawMac);
        hash = new String(hexBytes, "ISO-8859-1");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return hash;
}
Example 7
Project: elf-master  File: SampleApplication.java View source code
@Override
public void onCreate() {
    super.onCreate();
    try {
        Cipher cipher = Cipher.getInstance("AES");
        SecretKeySpec secretKeySpec = new SecretKeySpec("ElfSampleKey1234".getBytes(), "AES");
        secureSessionStorage = new SecureSessionStorage(this, getAppEnvironment().getSessionDirectory(), cipher, secretKeySpec);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    }
}
Example 8
Project: haox-master  File: DesProvider.java View source code
@Override
protected void doEncrypt(byte[] input, byte[] key, byte[] cipherState, boolean encrypt) throws KrbException {
    Cipher cipher = null;
    try {
        cipher = Cipher.getInstance("DES/CBC/NoPadding");
    } catch (GeneralSecurityException e) {
        throw new KrbException("Failed to init cipher", e);
    }
    IvParameterSpec params = new IvParameterSpec(cipherState);
    SecretKeySpec skSpec = new SecretKeySpec(key, "DES");
    try {
        SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
        SecretKey sk = (SecretKey) skSpec;
        cipher.init(encrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, sk, params);
        byte[] output = cipher.doFinal(input);
        System.arraycopy(output, 0, input, 0, output.length);
    } catch (GeneralSecurityException e) {
        KrbException ke = new KrbException(e.getMessage());
        ke.initCause(e);
        throw ke;
    }
}
Example 9
Project: netty-wamp-master  File: HmacSHA256.java View source code
public static String generate(final String key, final String data) throws NoSuchAlgorithmException, InvalidKeyException {
    if (key == null || data == null)
        throw new NullPointerException();
    final Mac hMacSHA256 = Mac.getInstance(HMAC_SHA256);
    byte[] hmacKeyBytes = key.getBytes(StandardCharsets.UTF_8);
    final SecretKeySpec secretKey = new SecretKeySpec(hmacKeyBytes, HMAC_SHA256);
    hMacSHA256.init(secretKey);
    byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
    byte[] res = hMacSHA256.doFinal(dataBytes);
    return Base64.encodeBase64String(res);
}
Example 10
Project: pili-sdk-java-master  File: HMac.java View source code
public static byte[] HmacSHA1Encrypt(String dataStr, String secretKeyStr) throws Exception {
    SecretKey secretKeySpec = new SecretKeySpec(secretKeyStr.getBytes(), MAC_NAME);
    //生�一个指定 Mac 算法 的 Mac 对象
    Mac mac = Mac.getInstance(MAC_NAME);
    //用给定密钥�始化 Mac 对象
    mac.init(secretKeySpec);
    //完� Mac �作
    return mac.doFinal(dataStr.getBytes());
}
Example 11
Project: restx-master  File: Crypto.java View source code
/**
     * Sign a message with a key
     * @param message The message to sign
     * @param key The key to use
     * @return The signed message (in hexadecimal)
     */
public static String sign(String message, byte[] key) {
    if (key.length == 0) {
        return message;
    }
    try {
        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA1");
        mac.init(signingKey);
        byte[] messageBytes = message.getBytes(Charsets.UTF_8);
        byte[] result = mac.doFinal(messageBytes);
        return BaseEncoding.base64().encode(result);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
Example 12
Project: openbd-core-master  File: hmac.java View source code
public cfData execute(cfSession _session, cfArgStructData argStruct) throws cfmRunTimeException {
    cfData messageData = getNamedParam(argStruct, "message");
    cfData keyData = getNamedParam(argStruct, "key");
    String algorithm = getNamedStringParam(argStruct, "algorithm", "HmacSHA1");
    String encoding = getNamedStringParam(argStruct, "encoding", cfEngine.getDefaultCharset());
    try {
        javax.crypto.spec.SecretKeySpec key;
        javax.crypto.Mac mac = javax.crypto.Mac.getInstance(algorithm);
        // Setup the key
        if (keyData.getDataType() == cfData.CFBINARYDATA)
            key = new javax.crypto.spec.SecretKeySpec(((cfBinaryData) keyData).getByteArray(), algorithm);
        else
            key = new javax.crypto.spec.SecretKeySpec(keyData.getString().getBytes(encoding), algorithm);
        mac.init(key);
        // Encode the message
        byte[] resultBytes;
        if (messageData.getDataType() == cfData.CFBINARYDATA)
            resultBytes = mac.doFinal(((cfBinaryData) messageData).getByteArray());
        else
            resultBytes = mac.doFinal(messageData.getString().getBytes(encoding));
        return new cfStringData(BinaryEncode.encode(BinaryEncode.BASE64, resultBytes));
    } catch (NoSuchAlgorithmException e) {
        throwException(_session, "No such algorithm: " + algorithm);
    } catch (Exception e) {
        throwException(_session, e.getMessage());
    }
    // keep compiler happy
    return null;
}
Example 13
Project: aq2o-master  File: Crypter.java View source code
public String encryptBlowfish(String to_encrypt) {
    try {
        SecretKeySpec key = new SecretKeySpec(strkey.getBytes(), "Blowfish");
        Cipher cipher = Cipher.getInstance("Blowfish");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        BASE64Encoder enc = new BASE64Encoder();
        return enc.encode(cipher.doFinal(to_encrypt.getBytes()));
    } catch (Exception e) {
        return null;
    }
}
Example 14
Project: atricore-idbus-master  File: CipherUtilTest.java View source code
@Test
public void testAES() throws Exception {
    SecretKeySpec key = CipherUtil.generateAESKey();
    String keyText = CipherUtil.encodeBase64(key.getEncoded());
    String msg = "My Test!";
    String text = CipherUtil.encryptAES(msg, keyText);
    String newMsg = CipherUtil.decryptAES(text, keyText);
    assert msg.equals(newMsg) : "Messages do not match : [" + msg + "] != [" + newMsg + "]";
}
Example 15
Project: azure-monitoring-extension-master  File: HmacSHA256Sign.java View source code
private void initHmacSha256(String accountKey) throws InvalidKeyException {
    SecretKey key256 = new SecretKeySpec(BaseEncoding.base64().decode(accountKey), "HmacSHA256");
    try {
        this.hmacSha256 = Mac.getInstance("HmacSHA256");
    } catch (final NoSuchAlgorithmException e) {
        throw new IllegalArgumentException();
    }
    this.hmacSha256.init(key256);
}
Example 16
Project: btpka3.github.com-master  File: GenAESKey.java View source code
private static SecretKey getSecretKeyBaseOnUserPassword(String userPassword, int keySize) {
    try {
        // AES 的密�长度有 128, 192, 256 三�,故在选择满足其最大长度的摘�算法。
        // 注�:如果�使用 256 �的AES,需�下载 JCE
        MessageDigest digester = MessageDigest.getInstance("SHA-256");
        byte[] digest = digester.digest(userPassword.getBytes("UTF-8"));
        byte[] key = new byte[keySize / 8];
        System.arraycopy(digest, 0, key, 0, keySize / 8);
        return new SecretKeySpec(key, "AES");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 17
Project: conceal-master  File: BetterCipherInputStreamTest.java View source code
@Before
public void setUp() throws Exception {
    mData = new byte[1024 * 1024];
    mCipheredData = new byte[mData.length];
    byte[] iv = new byte[16];
    byte[] key = new byte[16];
    mKey = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance(CIPHER_ALG);
    mIV = new IvParameterSpec(iv);
    cipher.init(Cipher.ENCRYPT_MODE, mKey, mIV);
    mCipheredData = cipher.update(mData, 0, mData.length);
    cipher.doFinal();
}
Example 18
Project: core-ng-project-master  File: HMAC.java View source code
public byte[] digest(byte[] message) {
    if (key == null)
        throw new Error("key must not be null");
    try {
        Mac mac = Mac.getInstance(hash.algorithm);
        SecretKey secretKey = new SecretKeySpec(key, hash.algorithm);
        mac.init(secretKey);
        return mac.doFinal(message);
    } catch (NoSuchAlgorithmExceptionInvalidKeyException |  e) {
        throw new Error(e);
    }
}
Example 19
Project: D3Xmpp-master  File: DES.java View source code
public static String encryptDES(String encryptString, String encryptKey) throws Exception {
    IvParameterSpec zeroIv = new IvParameterSpec(iv);
    SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
    Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
    byte[] encryptedData = cipher.doFinal(encryptString.getBytes());
    return android.util.Base64.encodeToString(encryptedData, android.util.Base64.NO_WRAP);
}
Example 20
Project: de.persosim.simulator-master  File: SmDataProviderTr03110GeneratorTest.java View source code
/**
	 * Positive test: check that SmDataProvider is correctly generated and can
	 * be used to reconstruct original DataProvider matching the original object
	 */
@Test
public void testGenerateSmDataProvider_reconstructDataProvider() {
    SecretKeySpec cipherKey = new SecretKeySpec(HexString.toByteArray(ICAO_SK_ENC), "DESede");
    SecretKeySpec macKey = new SecretKeySpec(HexString.toByteArray(ICAO_SK_MAC), "DESede");
    SmDataProviderTr03110 smdpOri = new SmDataProviderTr03110(cipherKey, macKey);
    SmDataProviderTr03110Generator smdpg = new SmDataProviderTr03110Generator(smdpOri);
    SmDataProviderTr03110 smdpNew = smdpg.generateSmDataProvider();
    assertEquals(smdpOri, smdpNew);
    assertNotSame(smdpOri, smdpNew);
}
Example 21
Project: eql-master  File: AesCryptor.java View source code
@SneakyThrows
private void initCipher() {
    final byte[] rawkey = S.alignRight(getKey(), 16, 'L').getBytes("UTF-8");
    SecretKeySpec key1 = new SecretKeySpec(rawkey, "AES");
    encryptCipher = Cipher.getInstance("AES");
    encryptCipher.init(Cipher.ENCRYPT_MODE, key1);
    decryptCipher = Cipher.getInstance("AES");
    decryptCipher.init(Cipher.DECRYPT_MODE, key1);
}
Example 22
Project: find-sec-bugs-master  File: NullCipherUse.java View source code
public static byte[] encryptWithCipher(Cipher cipher, byte[] value) throws KeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
    //Key generation
    byte[] passkey = "BBBBBBBBBBBBBBBB".getBytes("UTF-8");
    Cipher expectedCihper = cipher;
    SecretKeySpec key = new SecretKeySpec(passkey, "AES");
    //Setting the key
    expectedCihper.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(new byte[expectedCihper.getBlockSize()]));
    return cipher.doFinal(value);
}
Example 23
Project: HiveSwarm-master  File: AESDecrypt.java View source code
public Text evaluate(Text encrypted, Text key) {
    Text unencrypted = new Text(encrypted);
    if (encrypted != null && key != null) {
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(key.toString().getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] original = cipher.doFinal(Base32.hexdecode(encrypted.toString()));
            unencrypted.set(original);
        } catch (Exception e) {
        }
        ;
    }
    return unencrypted;
}
Example 24
Project: hsac-fitnesse-fixtures-master  File: SecurityUtil.java View source code
public static String hmacEncode(String algorithm, String input, String privateKey) throws IllegalArgumentException {
    try {
        byte[] keyBytes = privateKey.getBytes();
        Key key = new SecretKeySpec(keyBytes, 0, keyBytes.length, algorithm);
        Mac mac = Mac.getInstance(algorithm);
        mac.init(key);
        return byteArrayToHex(mac.doFinal(input.getBytes()));
    } catch (NoSuchAlgorithmException ex) {
        throw new IllegalArgumentException("Unknown algorithm: " + algorithm);
    } catch (InvalidKeyException ex) {
        throw new IllegalArgumentException("Illegal key: " + privateKey);
    }
}
Example 25
Project: insta4j-master  File: InstagramUtil.java View source code
public static String createSHAKey(String ipAddress, String clientSecret) throws InstagramException {
    String digest = null;
    String clientSecretForSHA = getClientSecret();
    if (clientSecretForSHA == null || clientSecretForSHA.equals("")) {
        clientSecretForSHA = clientSecret;
    }
    SecretKeySpec signingKey = new SecretKeySpec(clientSecretForSHA.getBytes(), Constants.HMAC_SHA256_ALGO);
    Mac mac = null;
    try {
        mac = Mac.getInstance(Constants.HMAC_SHA256_ALGO);
        mac.init(signingKey);
        byte[] rawHmac = mac.doFinal(ipAddress.getBytes());
        digest = Hex.encodeHexString(rawHmac);
    } catch (NoSuchAlgorithmException e) {
        throw new InstagramException(-1, e.getMessage(), "Undefined", e);
    } catch (InvalidKeyException e) {
        throw new InstagramException(-1, e.getMessage(), "Undefined", e);
    }
    return digest;
}
Example 26
Project: interoperability-framework-master  File: Security.java View source code
public static String encrypt(String input, String key) {
    byte[] crypted = null;
    try {
        SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skey);
        crypted = cipher.doFinal(input.getBytes());
    } catch (Exception e) {
        System.out.println(e.toString());
    }
    return new String(Base64.encodeBase64(crypted));
}
Example 27
Project: jersey-hmac-auth-master  File: Signer.java View source code
private byte[] calculateDigest(byte[] message) {
    try {
        byte[] secretKeyBytes = secretKey.getBytes(UTF_8);
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKeyBytes, HMAC_SHA256);
        Mac mac = Mac.getInstance(HMAC_SHA256);
        mac.init(secretKeySpec);
        mac.update(message);
        return mac.doFinal();
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException("Invalid character encoding: " + UTF_8, e);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("Invalid MAC algorithm: " + HMAC_SHA256, e);
    } catch (InvalidKeyException e) {
        throw new IllegalStateException("Invalid MAC secret key", e);
    }
}
Example 28
Project: jInstagram-master  File: EnforceSignedRequestUtils.java View source code
/**
     * signature returns the HmacSHA256 encoded signature used for signed Instagram requests
     * @param endpoint The endpoint
     * @param params   The query parameters
     * @param clientSecret The client application secret
     * @return encoded signature String
     * @throws InstagramException
     */
public static String signature(String endpoint, Map<String, String> params, String clientSecret) throws InstagramException {
    SecretKeySpec keySpec = new SecretKeySpec(clientSecret.getBytes(UTF_8), HMAC_SHA256);
    // ensure we iterate through the keys in sorted order
    List<String> values = new ArrayList<String>(params.size());
    for (String key : MapUtils.getSortedKeys(params)) {
        values.add(String.format("%s=%s", key, params.get(key)));
    }
    // the sig string to sign in the form "endpoint|key1=value1|key2=value2|...."
    String sig = String.format("%s|%s", endpoint, StringUtils.join(values, '|'));
    try {
        Mac mac = Mac.getInstance(HMAC_SHA256);
        mac.init(keySpec);
        byte[] result = mac.doFinal(sig.getBytes(UTF_8));
        return Hex.encodeHexString(result);
    } catch (NoSuchAlgorithmException e) {
        throw new InstagramException("Invalid algorithm name!", e);
    } catch (InvalidKeyException e) {
        throw new InstagramException("Invalid key: " + clientSecret, e);
    }
}
Example 29
Project: magpi-android-master  File: SecurityUtils.java View source code
public static String Hmac(String secret, String data) {
    try {
        SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), HMAC_SHA1_ALGORITHM);
        Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);
        byte[] rawHmac = mac.doFinal(data.getBytes());
        String result = Base64.encodeToString(rawHmac, Base64.NO_WRAP);
        return result;
    } catch (GeneralSecurityException e) {
        throw new IllegalArgumentException();
    }
}
Example 30
Project: MozillaRecovery-master  File: SHA.java View source code
public static byte[] sha1Hmac(byte[] data, byte[] key) {
    try {
        SecretKeySpec signingKey = new SecretKeySpec(key, HMAC_SHA1_ALGORITHM);
        Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);
        return mac.doFinal(data);
    } catch (NoSuchAlgorithmExceptionInvalidKeyException |  e) {
        e.printStackTrace();
        logger.fatal(e.getMessage());
    }
    return null;
}
Example 31
Project: plivo-java-master  File: XPlivoSignature.java View source code
public static Boolean verify(String uri, LinkedHashMap<String, String> parameters, String xsignature, String authToken) throws PlivoException {
    Boolean isMatch = false;
    Map<String, String> sortedParams = new TreeMap<String, String>(parameters);
    for (Entry<String, String> pair : sortedParams.entrySet()) {
        uri += pair.getKey() + pair.getValue();
    }
    try {
        byte[] keyBytes = authToken.getBytes();
        byte[] textBytes = uri.getBytes();
        Mac hmac = Mac.getInstance("HmacSHA1");
        SecretKeySpec macKey = new SecretKeySpec(keyBytes, "HmacSHA1");
        hmac.init(macKey);
        byte[] signBytes = hmac.doFinal(textBytes);
        String signature = new String(Base64.encodeBase64(signBytes));
        if (signature.equals(xsignature))
            isMatch = true;
    } catch (Exception e) {
        throw new PlivoException(e.getLocalizedMessage());
    }
    return isMatch;
}
Example 32
Project: Securecom-Text-master  File: ChainKey.java View source code
private byte[] getBaseMaterial(byte[] seed) {
    try {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(key, "HmacSHA256"));
        return mac.doFinal(seed);
    } catch (NoSuchAlgorithmException e) {
        throw new AssertionError(e);
    } catch (InvalidKeyException e) {
        throw new AssertionError(e);
    }
}
Example 33
Project: Signal-Server-master  File: TurnTokenGenerator.java View source code
public TurnToken generate() {
    try {
        Mac mac = Mac.getInstance("HmacSHA1");
        long validUntilSeconds = (System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1)) / 1000;
        long user = Math.abs(new SecureRandom().nextInt());
        String userTime = validUntilSeconds + ":" + user;
        mac.init(new SecretKeySpec(key, "HmacSHA1"));
        String password = Base64.encodeBytes(mac.doFinal(userTime.getBytes()));
        return new TurnToken(userTime, password, urls);
    } catch (NoSuchAlgorithmExceptionInvalidKeyException |  e) {
        throw new AssertionError(e);
    }
}
Example 34
Project: springsecuritytotp-master  File: TotpAuthenticatorUtil.java View source code
public static long getCode(byte[] secret, long timeIndex) throws NoSuchAlgorithmException, InvalidKeyException {
    SecretKeySpec signKey = new SecretKeySpec(secret, "HmacSHA1");
    ByteBuffer buffer = ByteBuffer.allocate(8);
    buffer.putLong(timeIndex);
    byte[] timeBytes = buffer.array();
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(signKey);
    byte[] hash = mac.doFinal(timeBytes);
    int offset = hash[19] & 0xf;
    long truncatedHash = hash[offset] & 0x7f;
    for (int i = 1; i < 4; i++) {
        truncatedHash <<= 8;
        truncatedHash |= hash[offset + i] & 0xff;
    }
    return truncatedHash %= 1000000;
}
Example 35
Project: TOTP-authentication-demo-master  File: TOTPTest.java View source code
private int generateGoogleOTP(byte[] key) {
    try {
        Mac hmac;
        hmac = Mac.getInstance(CRYPTO);
        SecretKeySpec macKey = new SecretKeySpec(key, "RAW");
        hmac.init(macKey);
        PasscodeGenerator passcodeGenerator = new PasscodeGenerator(hmac);
        return Integer.parseInt(passcodeGenerator.generateTimeoutCode());
    } catch (NumberFormatException e) {
        e.printStackTrace();
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    }
    return 0;
}
Example 36
Project: Urban-Tag-master  File: HMacSha1.java View source code
/**
   * Performs a HMAC using SHA1, output is encoded in hexadecimal.
   * @param secretKey the secret key used for hashing the data.
   * @param data the data to securely hash.
   * @return a hexadecimal digest.
   * @throws IllegalArgumentException if secret key is empty.
   */
public static String asHexDigest(String secretKey, String data) {
    SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), ALGORITHM);
    Mac mac;
    try {
        mac = Mac.getInstance(ALGORITHM);
    } catch (NoSuchAlgorithmException nsae) {
        throw new RuntimeException(nsae);
    }
    try {
        mac.init(secretKeySpec);
    } catch (InvalidKeyException ike) {
        throw new IllegalArgumentException("Unsuitable secret key", ike);
    }
    byte[] rawHmac = mac.doFinal(data.getBytes());
    return Hex.encode(rawHmac);
}
Example 37
Project: webpasswordsafe-master  File: Util.java View source code
public static byte[] hmacSha1(byte[] key_bytes, byte[] text_bytes) throws NoSuchAlgorithmException, InvalidKeyException {
    Mac hmacSha1;
    try {
        hmacSha1 = Mac.getInstance("HmacSHA1");
    } catch (NoSuchAlgorithmException nsae) {
        hmacSha1 = Mac.getInstance("HMAC-SHA-1");
    }
    SecretKeySpec macKey = new SecretKeySpec(key_bytes, "RAW");
    hmacSha1.init(macKey);
    return hmacSha1.doFinal(text_bytes);
}
Example 38
Project: with-aes-master  File: RC4Implementation.java View source code
public Key computeKey(final SecurityHandler securityHandler, final long objectNumber, final long genNumber) throws CryptographyException {
    final byte[] newKey = generateKeyBase(securityHandler, objectNumber, genNumber);
    // step 3
    byte[] digestedKey = null;
    try {
        final MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(newKey);
        digestedKey = md.digest();
    } catch (final NoSuchAlgorithmException e) {
        throw new CryptographyException(e);
    }
    // step 4
    final int length = Math.min(newKey.length, 16);
    final byte[] finalKey = new byte[length];
    System.arraycopy(digestedKey, 0, finalKey, 0, length);
    final SecretKey key = new SecretKeySpec(finalKey, "RC4");
    return key;
}
Example 39
Project: wonder-master  File: ERXAESCrypter.java View source code
/**
	 * Generates a secret key from the System property
	 * <b>er.extensions.ERXAESCipherKey</b>. This secret key is used when
	 * generating the AES cipher.
	 * 
	 * @return a secret key for the cipher
	 */
@Override
protected Key secretKey() throws NoSuchAlgorithmException {
    String secretKey = ERXProperties.stringForKey("er.extensions.ERXAESCipherKey");
    if (secretKey == null) {
        log.warn("er.extensions.ERXAESCipherKey not set in defaults.  Should be set before using the cipher.");
        secretKey = "DefaultCipherKey";
    }
    return new SecretKeySpec(secretKey.getBytes(), "AES");
}
Example 40
Project: XPagesToolkit-master  File: UNIDKeyProvider.java View source code
@Override
public SecretKeySpec getKey() {
    try {
        String passphrase = ExtLibUtil.getCurrentDatabase().getReplicaID();
        MessageDigest digest = MessageDigest.getInstance("SHA");
        digest.update(passphrase.getBytes());
        return new SecretKeySpec(digest.digest(), 0, 16, "AES");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Example 41
Project: picketbox-json-master  File: HmacSha256Util.java View source code
/**
     * Encode a payload using HMAC SHA 256 algorithm
     *
     * @param payload
     * @return
     * @throws ProcessingException
     */
public static String encode(String payload) throws ProcessingException {
    final Charset charSet = Charset.forName("UTF-8");
    Mac sha256_HMAC = null;
    try {
        sha256_HMAC = Mac.getInstance("HmacSHA256");
    } catch (NoSuchAlgorithmException e1) {
        throw PicketBoxJSONMessages.MESSAGES.noSuchAlgorithm(e1);
    }
    final SecretKeySpec secret_key = new javax.crypto.spec.SecretKeySpec(charSet.encode("key").array(), "HmacSHA256");
    try {
        sha256_HMAC.init(secret_key);
    } catch (InvalidKeyException e) {
        throw PicketBoxJSONMessages.MESSAGES.processingException(e);
    }
    final byte[] mac_data = sha256_HMAC.doFinal(charSet.encode(payload).array());
    String result = "";
    for (final byte element : mac_data) {
        result += Integer.toString((element & 0xff) + 0x100, 16).substring(1);
    }
    return result;
}
Example 42
Project: active-directory-android-master  File: Utils.java View source code
public static void setupKeyForSample() throws NoSuchAlgorithmException, InvalidKeySpecException, UnsupportedEncodingException {
    if (AuthenticationSettings.INSTANCE.getSecretKeyData() == null) {
        // use same key for tests
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithSHA256And256BitAES-CBC-BC");
        SecretKey tempkey = keyFactory.generateSecret(new PBEKeySpec("test".toCharArray(), "abcdedfdfd".getBytes("UTF-8"), 100, 256));
        SecretKey secretKey = new SecretKeySpec(tempkey.getEncoded(), "AES");
        AuthenticationSettings.INSTANCE.setSecretKey(secretKey.getEncoded());
    }
}
Example 43
Project: aDoubanReader-master  File: HmacSha1MessageSigner.java View source code
@Override
public String sign(HttpRequest request, HttpParameters requestParams) throws OAuthMessageSignerException {
    try {
        String keyString = OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret());
        byte[] keyBytes = keyString.getBytes(OAuth.ENCODING);
        SecretKey key = new SecretKeySpec(keyBytes, MAC_NAME);
        Mac mac = Mac.getInstance(MAC_NAME);
        mac.init(key);
        String sbs = new SignatureBaseString(request, requestParams).generate();
        OAuth.debugOut("SBS", sbs);
        byte[] text = sbs.getBytes(OAuth.ENCODING);
        return base64Encode(mac.doFinal(text)).trim();
    } catch (GeneralSecurityException e) {
        throw new OAuthMessageSignerException(e);
    } catch (UnsupportedEncodingException e) {
        throw new OAuthMessageSignerException(e);
    }
}
Example 44
Project: AltManager-master  File: Encryption.java View source code
public static void setKey(String myKey) {
    MessageDigest sha = null;
    try {
        key = myKey.getBytes("UTF-8");
        sha = MessageDigest.getInstance("SHA-1");
        key = sha.digest(key);
        key = Arrays.copyOf(key, 16);
        secretKey = new SecretKeySpec(key, "AES");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}
Example 45
Project: andbase2x-master  File: AbDes.java View source code
public String encrypt(byte[] encryptByte, String encryptKey) {
    try {
        IvParameterSpec zeroIv = new IvParameterSpec(iv);
        SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
        byte[] encryptedData = cipher.doFinal(encryptByte);
        return AbBase64.encode(encryptedData);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Example 46
Project: android-15-master  File: MacThread.java View source code
@Override
public void test() throws Exception {
    int size = 256;
    byte[] src1 = new byte[size];
    byte[] src2 = new byte[size];
    byte[] src3 = new byte[size];
    int i;
    for (i = 0; i < size; i++) {
        src1[i] = (byte) i;
        src2[i] = (byte) i;
        src3[i] = (byte) (size - i - 1);
    }
    Mac m = Mac.getInstance(algName);
    byte[] b = { (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0 };
    SecretKeySpec sks = new SecretKeySpec(b, "SHA1");
    m.init(sks);
    byte[] res = m.doFinal(src1);
    String sign1 = new String(res);
    m.init(sks);
    res = m.doFinal(src2);
    String sign2 = new String(res);
    m.init(sks);
    res = m.doFinal(src3);
    String sign3 = new String(res);
    if (sign1.compareTo(sign2) != 0 || sign1.compareTo(sign3) == 0 || sign2.compareTo(sign3) == 0) {
        throw new Exception("Signature is not correct for algorithm " + algName);
    }
}
Example 47
Project: android-libcore64-master  File: MacThread.java View source code
@Override
public void test() throws Exception {
    int size = 256;
    byte[] src1 = new byte[size];
    byte[] src2 = new byte[size];
    byte[] src3 = new byte[size];
    int i;
    for (i = 0; i < size; i++) {
        src1[i] = (byte) i;
        src2[i] = (byte) i;
        src3[i] = (byte) (size - i - 1);
    }
    Mac m = Mac.getInstance(algName);
    byte[] b = { (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0 };
    SecretKeySpec sks = new SecretKeySpec(b, "SHA1");
    m.init(sks);
    byte[] res = m.doFinal(src1);
    String sign1 = new String(res);
    m.init(sks);
    res = m.doFinal(src2);
    String sign2 = new String(res);
    m.init(sks);
    res = m.doFinal(src3);
    String sign3 = new String(res);
    if (sign1.compareTo(sign2) != 0 || sign1.compareTo(sign3) == 0 || sign2.compareTo(sign3) == 0) {
        throw new Exception("Signature is not correct for algorithm " + algName);
    }
}
Example 48
Project: android-sdk-sources-for-api-level-23-master  File: MacThread.java View source code
@Override
public void test() throws Exception {
    int size = 256;
    byte[] src1 = new byte[size];
    byte[] src2 = new byte[size];
    byte[] src3 = new byte[size];
    int i;
    for (i = 0; i < size; i++) {
        src1[i] = (byte) i;
        src2[i] = (byte) i;
        src3[i] = (byte) (size - i - 1);
    }
    Mac m = Mac.getInstance(algName);
    byte[] b = { (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0 };
    SecretKeySpec sks = new SecretKeySpec(b, "SHA1");
    m.init(sks);
    byte[] res = m.doFinal(src1);
    String sign1 = new String(res);
    m.init(sks);
    res = m.doFinal(src2);
    String sign2 = new String(res);
    m.init(sks);
    res = m.doFinal(src3);
    String sign3 = new String(res);
    if (sign1.compareTo(sign2) != 0 || sign1.compareTo(sign3) == 0 || sign2.compareTo(sign3) == 0) {
        throw new Exception("Signature is not correct for algorithm " + algName);
    }
}
Example 49
Project: Android-Simple-Social-Sharing-master  File: HmacSha1MessageSigner.java View source code
@Override
public String sign(HttpRequest request, HttpParameters requestParams) throws OAuthMessageSignerException {
    try {
        String keyString = OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret());
        byte[] keyBytes = keyString.getBytes(OAuth.ENCODING);
        SecretKey key = new SecretKeySpec(keyBytes, MAC_NAME);
        Mac mac = Mac.getInstance(MAC_NAME);
        mac.init(key);
        String sbs = new SignatureBaseString(request, requestParams).generate();
        OAuth.debugOut("SBS", sbs);
        byte[] text = sbs.getBytes(OAuth.ENCODING);
        return base64Encode(mac.doFinal(text)).trim();
    } catch (GeneralSecurityException e) {
        throw new OAuthMessageSignerException(e);
    } catch (UnsupportedEncodingException e) {
        throw new OAuthMessageSignerException(e);
    }
}
Example 50
Project: AndroidStudyDemo-master  File: DES3.java View source code
/**
     * 加密方法
     * @param src �数�的字节数组
     * @return
     */
public static byte[] encryptMode(byte[] src) {
    try {
        // 生�密钥
        SecretKey deskey = new SecretKeySpec(build3DesKey(PASSWORD_CRYPT_KEY), Algorithm);
        // 实例化Cipher
        Cipher cipher = Cipher.getInstance(Algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, deskey);
        return cipher.doFinal(src);
    } catch (Exception e) {
        Logger.e(e);
    }
    return null;
}
Example 51
Project: android_libcore-master  File: MacThread.java View source code
@Override
public void test() throws Exception {
    int size = 256;
    byte[] src1 = new byte[size];
    byte[] src2 = new byte[size];
    byte[] src3 = new byte[size];
    int i;
    for (i = 0; i < size; i++) {
        src1[i] = (byte) i;
        src2[i] = (byte) i;
        src3[i] = (byte) (size - i - 1);
    }
    Mac m = Mac.getInstance(algName);
    byte[] b = { (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0 };
    SecretKeySpec sks = new SecretKeySpec(b, "SHA1");
    m.init(sks);
    byte[] res = m.doFinal(src1);
    String sign1 = new String(res);
    m.init(sks);
    res = m.doFinal(src2);
    String sign2 = new String(res);
    m.init(sks);
    res = m.doFinal(src3);
    String sign3 = new String(res);
    if (sign1.compareTo(sign2) != 0 || sign1.compareTo(sign3) == 0 || sign2.compareTo(sign3) == 0) {
        throw new Exception("Signature is not correct for algorithm " + algName);
    }
}
Example 52
Project: android_platform_libcore-master  File: MacThread.java View source code
@Override
public void test() throws Exception {
    int size = 256;
    byte[] src1 = new byte[size];
    byte[] src2 = new byte[size];
    byte[] src3 = new byte[size];
    int i;
    for (i = 0; i < size; i++) {
        src1[i] = (byte) i;
        src2[i] = (byte) i;
        src3[i] = (byte) (size - i - 1);
    }
    Mac m = Mac.getInstance(algName);
    byte[] b = { (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0 };
    SecretKeySpec sks = new SecretKeySpec(b, "SHA1");
    m.init(sks);
    byte[] res = m.doFinal(src1);
    String sign1 = new String(res);
    m.init(sks);
    res = m.doFinal(src2);
    String sign2 = new String(res);
    m.init(sks);
    res = m.doFinal(src3);
    String sign3 = new String(res);
    if (sign1.compareTo(sign2) != 0 || sign1.compareTo(sign3) == 0 || sign2.compareTo(sign3) == 0) {
        throw new Exception("Signature is not correct for algorithm " + algName);
    }
}
Example 53
Project: any-video-master  File: AesUtils.java View source code
/**
   * 使用AES 算法 加密,默认模� AES/CBC/PKCS5Padding
   */
public static String encrypt(String str, String iv, String pass) {
    try {
        Cipher cipher = Cipher.getInstance(TYPE);
        SecretKey secretKey = new SecretKeySpec(pass.getBytes(), KEY_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv.getBytes()));
        byte[] encrypt = cipher.doFinal(str.getBytes());
        return Base64.getEncoder().encodeToString(encrypt);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    }
    return null;
}
Example 54
Project: ARTPart-master  File: MacThread.java View source code
@Override
public void test() throws Exception {
    int size = 256;
    byte[] src1 = new byte[size];
    byte[] src2 = new byte[size];
    byte[] src3 = new byte[size];
    int i;
    for (i = 0; i < size; i++) {
        src1[i] = (byte) i;
        src2[i] = (byte) i;
        src3[i] = (byte) (size - i - 1);
    }
    Mac m = Mac.getInstance(algName);
    byte[] b = { (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0 };
    SecretKeySpec sks = new SecretKeySpec(b, "SHA1");
    m.init(sks);
    byte[] res = m.doFinal(src1);
    String sign1 = new String(res);
    m.init(sks);
    res = m.doFinal(src2);
    String sign2 = new String(res);
    m.init(sks);
    res = m.doFinal(src3);
    String sign3 = new String(res);
    if (sign1.compareTo(sign2) != 0 || sign1.compareTo(sign3) == 0 || sign2.compareTo(sign3) == 0) {
        throw new Exception("Signature is not correct for algorithm " + algName);
    }
}
Example 55
Project: audit-master  File: MainActivity.java View source code
private //固定密钥
String cipher() {
    try {
        SecretKeySpec securekey = new // 使用
        SecretKeySpec(// 使用
        "0123456789abcdef".getBytes(), // 使用
        "AES");
        // 创建密�器
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding ");
        SecureRandom random = new SecureRandom();
        byte[] iv = new byte[16];
        random.nextBytes(iv);
        cipher.init(Cipher.ENCRYPT_MODE, securekey, new IvParameterSpec(iv));
        byte[] byteContent = plaintext.getText().toString().getBytes("utf-8");
        byte[] result = cipher.doFinal(byteContent);
        return parseByte2HexStr(result);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
Example 56
Project: bigbluebutton-master  File: TurnServer.java View source code
/**
   * Computes RFC 2104-compliant HMAC signature.
   * * @param data
   * The data to be signed.
   * @param key
   * The signing key.
   * @return
   * The Base64-encoded RFC 2104-compliant HMAC signature.
   * @throws
   * java.security.SignatureException when signature generation fails
   */
private String calculateRFC2104HMAC(String data, String key) throws java.security.SignatureException {
    String result;
    try {
        // get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
        // get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);
        // compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(data.getBytes());
        // base64-encode the hmac
        result = new String(Base64.encodeBase64(rawHmac));
    } catch (Exception e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }
    return result;
}
Example 57
Project: bluetooth_social-master  File: HmacSha1MessageSigner.java View source code
@Override
public String sign(HttpRequest request, HttpParameters requestParams) throws OAuthMessageSignerException {
    try {
        String keyString = OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret());
        byte[] keyBytes = keyString.getBytes(OAuth.ENCODING);
        SecretKey key = new SecretKeySpec(keyBytes, MAC_NAME);
        Mac mac = Mac.getInstance(MAC_NAME);
        mac.init(key);
        String sbs = new SignatureBaseString(request, requestParams).generate();
        OAuth.debugOut("SBS", sbs);
        byte[] text = sbs.getBytes(OAuth.ENCODING);
        return base64Encode(mac.doFinal(text)).trim();
    } catch (GeneralSecurityException e) {
        throw new OAuthMessageSignerException(e);
    } catch (UnsupportedEncodingException e) {
        throw new OAuthMessageSignerException(e);
    }
}
Example 58
Project: bnd-master  File: ClassRefInStackMapTable.java View source code
public static void main(String[] args) {
    /*
		 * Create an object and assign it to a super-type variable. Note the
		 * super-type is in a different package from the concrete type.
		 */
    SecretKey key = new SecretKeySpec(new byte[] { 0 }, "NULL");
    /*
		 * This branch causes the compiler to emit a StackMapTable in the byte
		 * code. The table will refer to the local 'key' and force a reference
		 * to the 'SecretKey' class to appear in the constant pool (which would
		 * not be required without the StackMapTable). Bnd sees the 'SecretKey'
		 * class in the constant pool but assumes its an orphan because it has
		 * no associated entries that refer to it. When it double checks by
		 * crawling the byte code the StackMapTable is ignored. Bnd decides that
		 * 'SecretKey' is an orphan and does not emit and Import-Package
		 * directive for its package. This causes a NoClassDefFoundError at
		 * runtime.
		 */
    if (System.currentTimeMillis() > 0) {
        System.out.println("Toast!");
    }
    System.out.println(key);
}
Example 59
Project: bugvm-master  File: BaseSecretKeyFactory.java View source code
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());
    }
}
Example 60
Project: cambodia-master  File: DESmain.java View source code
public static void main(String args[]) {
    //¼ÓÃÜÔ´Îļþ
    String txt = "busi";
    try {
        byte[] txtBytes = new byte[48];
        System.arraycopy(txt.getBytes(), 0, txtBytes, 0, txt.getBytes().length);
        int len = txt.getBytes().length;
        int len2 = len % 8;
        if (len2 > 0) {
            for (int i = 0; i < 8 - len2; i++) {
                txtBytes[len++] = 0x00;
            }
        }
        Cipher cipherEn = null;
        try {
            cipherEn = Cipher.getInstance("DES/ECB/Nopadding");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }
        //Cipher cipherEn = Cipher.getInstance("DES/CBC/PKCS5Padding");
        Key keyK = new javax.crypto.spec.SecretKeySpec("abcdefgh".getBytes(), "DES");
        cipherEn.init(Cipher.ENCRYPT_MODE, keyK);
        byte[] pnBytes = cipherEn.doFinal(txtBytes, 0, len);
        System.out.println(CATools.byte2HexStr(pnBytes));
        System.exit(1);
    } catch (InvalidKeyException e1) {
        e1.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    }
}
Example 61
Project: cas-addons-master  File: TOTP.java View source code
/**
     * This method uses the JCE to provide the crypto algorithm. HMAC computes a
     * Hashed Message Authentication Code with the crypto hash algorithm as a
     * parameter.
     *
     * @param crypto
     *            : the crypto algorithm (HmacSHA1, HmacSHA256, HmacSHA512)
     * @param keyBytes
     *            : the bytes to use for the HMAC key
     * @param text
     *            : the message or text to be authenticated
     */
private static byte[] hmacSha(String crypto, byte[] keyBytes, byte[] text) {
    try {
        Mac hmac;
        hmac = Mac.getInstance(crypto);
        SecretKeySpec macKey = new SecretKeySpec(keyBytes, "RAW");
        hmac.init(macKey);
        return hmac.doFinal(text);
    } catch (GeneralSecurityException gse) {
        throw new UndeclaredThrowableException(gse);
    }
}
Example 62
Project: cattle-master  File: RegistrationToken.java View source code
public static final String createToken(String accessKey, String secretKey, Date date) {
    String prefix = String.format("%s:%d", accessKey, date.getTime());
    try {
        SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), HMAC_SHA1_ALGORITHM);
        Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);
        String signature = Base64.encodeBase64String(mac.doFinal(prefix.getBytes("UTF-8"))).replaceAll("[/=+]", "");
        return String.format("%s:%s", prefix, signature);
    } catch (InvalidKeyException e) {
        throw new IllegalStateException("Failed to generate signature key for [" + prefix + "]", e);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("Failed to generate signature key for [" + prefix + "]", e);
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException("Failed to generate signature key for [" + prefix + "]", e);
    }
}
Example 63
Project: cloud-storage-vault-master  File: KeyChain.java View source code
private void common() {
    PBKDF2Parameters param = new PBKDF2Parameters(HASH_ALG, ENCODING, this.salt, ITERATION_COUNT);
    PBKDF2Engine engine = new PBKDF2Engine(param);
    param.setDerivedKey(engine.deriveKey(password, (Cryptoutil.SYM_SIZE / Byte.SIZE)));
    byte tmp[] = param.getDerivedKey();
    this.key = new SecretKeySpec(tmp, Cryptoutil.SYM_CIPHER);
}
Example 64
Project: cloudstore-master  File: SignedAuthTokenDecrypter.java View source code
public byte[] decrypt(final EncryptedSignedAuthToken encryptedSignedAuthToken) {
    AssertUtil.assertNotNull(encryptedSignedAuthToken, "encryptedSignedAuthToken");
    AssertUtil.assertNotNull(encryptedSignedAuthToken.getEncryptedSignedAuthTokenData(), "encryptedSignedAuthToken.encryptedSignedAuthTokenData");
    AssertUtil.assertNotNull(encryptedSignedAuthToken.getEncryptedSymmetricKey(), "encryptedSignedAuthToken.encryptedSymmetricKey");
    try {
        final Cipher asymCipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA1ANDMGF1PADDING");
        asymCipher.init(Cipher.DECRYPT_MODE, privateKey);
        final byte[] symKey = asymCipher.doFinal(encryptedSignedAuthToken.getEncryptedSymmetricKey());
        final Cipher symCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        symCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(symKey, "AES"), new IvParameterSpec(encryptedSignedAuthToken.getEncryptedSignedAuthTokenDataIV()));
        final byte[] signedAuthTokenData = symCipher.doFinal(encryptedSignedAuthToken.getEncryptedSignedAuthTokenData());
        return signedAuthTokenData;
    } catch (final RuntimeException e) {
        throw e;
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
Example 65
Project: codeine-master  File: EncryptionUtils.java View source code
private static byte[] encrypt(String key, String value) {
    byte[] raw = key.getBytes(Charsets.US_ASCII);
    if (raw.length != 16) {
        throw ExceptionUtils.asUnchecked(new IllegalArgumentException("Invalid key size."));
    }
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    try {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16]));
        return cipher.doFinal(value.getBytes(Charsets.US_ASCII));
    } catch (Exception e) {
        throw ExceptionUtils.asUnchecked(e);
    }
}
Example 66
Project: computoser-master  File: SecurityUtils.java View source code
/**
     * Calculates a HmacSHA1 value
     *
     * @param data
     * @param key
     * @return HmacSHA1
     */
public static String hmac(String data, String key) {
    try {
        // get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
        Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);
        // compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(data.getBytes());
        String result = new String(Hex.encodeHex(rawHmac));
        return result.toUpperCase();
    } catch (Exception ex) {
        throw new RuntimeException("Problem with calculating hmac", ex);
    }
}
Example 67
Project: craken-master  File: TestEncrypt.java View source code
public void testCiper() throws Exception {
    byte[] keyBytes = "40674244".getBytes();
    byte[] ivBytes = "@1B2c3D4".getBytes();
    // wrap key data in Key/IV specs to pass to cipher
    SecretKeySpec key = new SecretKeySpec(keyBytes, "DES");
    IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
    // create the cipher with the algorithm you choose see javadoc for Cipher class for more info, e.g.
    Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    byte[] input = "administrator".getBytes("UTF-8");
    cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
    byte[] encrypted = new byte[cipher.getOutputSize(input.length)];
    int enc_len = cipher.update(input, 0, input.length, encrypted, 0);
    enc_len += cipher.doFinal(encrypted, enc_len);
    Debug.line(encrypted, enc_len);
    cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
    byte[] decrypted = new byte[cipher.getOutputSize(enc_len)];
    int dec_len = cipher.update(encrypted, 0, enc_len, decrypted, 0);
    dec_len += cipher.doFinal(decrypted, dec_len);
    Debug.line(decrypted, dec_len, new String(decrypted, "UTF-8").trim());
}
Example 68
Project: CrocodileNote-master  File: PBKDF2.java View source code
private byte[] generateDerivedKey(int dkLen, byte[] password, byte[] salt, int iterationCount) {
    int hLen = hMac.getMacLength();
    int l = (dkLen + hLen - 1) / hLen;
    byte[] iBuf = new byte[4];
    byte[] outBytes = new byte[l * hLen];
    int outPos = 0;
    try {
        SecretKeySpec key = new SecretKeySpec(password, "AES");
        hMac.init(key);
        for (int i = 1; i <= l; i++) {
            int pos = 3;
            while (++iBuf[pos] == 0) {
                --pos;
            }
            F(salt, iterationCount, iBuf, outBytes, outPos);
            outPos += hLen;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return outBytes;
}
Example 69
Project: CupCarbon-master  File: Blowfish.java View source code
public String encrypt() throws Exception {
    byte[] byteKey = key.getBytes();
    String IV = "12345678";
    // Create new Blowfish cipher
    SecretKeySpec keySpec = new SecretKeySpec(byteKey, "Blowfish");
    Cipher cipher = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, keySpec, new javax.crypto.spec.IvParameterSpec(IV.getBytes()));
    byte[] encoding = cipher.doFinal(message.getBytes());
    return bytesToHex(encoding);
}
Example 70
Project: cxf-master  File: TestUtils.java View source code
public static boolean checkUnrestrictedPoliciesInstalled() {
    boolean unrestrictedPoliciesInstalled = false;
    try {
        byte[] data = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
        SecretKey key192 = new SecretKeySpec(new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 }, "AES");
        Cipher c = Cipher.getInstance("AES");
        c.init(Cipher.ENCRYPT_MODE, key192);
        c.doFinal(data);
        unrestrictedPoliciesInstalled = true;
    } catch (Exception e) {
        return unrestrictedPoliciesInstalled;
    }
    return unrestrictedPoliciesInstalled;
}
Example 71
Project: CZD_Android_Lib-master  File: Rijndael.java View source code
public static String encrypt(String plainText, byte[] key) {
    try {
        Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
        int blockSize = cipher.getBlockSize();
        byte[] dataBytes = plainText.getBytes();
        int plaintTextLength = dataBytes.length;
        if (plaintTextLength % blockSize != 0) {
            plaintTextLength = plaintTextLength + (blockSize - (plaintTextLength % blockSize));
        }
        byte[] plainTextByte = new byte[plaintTextLength];
        System.arraycopy(dataBytes, 0, plainTextByte, 0, dataBytes.length);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"));
        return Base64.encode(cipher.doFinal(plainTextByte)) + String.format("%06d", plainText.length());
    } 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 "";
}
Example 72
Project: dashencrypt-master  File: DashEncryptedBuilderTest.java View source code
@Test
public void stabilize() throws IOException {
    DashBuilder dashEncryptedBuilder = new DashBuilder();
    Movie m1 = MovieCreator.build(this.getClass().getProtectionDomain().getCodeSource().getLocation().getFile() + "/v1.mp4");
    Movie m2 = new Movie();
    Track t = m1.getTracks().get(0);
    UUID keyId = UUIDConverter.convert(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 });
    SecretKey key = new SecretKeySpec(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }, "AES");
    CencEncryptingTrackImpl cencEncryptingTrack = new CencEncryptingTrackImpl(t, keyId, key, true);
    m2.addTrack(cencEncryptingTrack);
    dashEncryptedBuilder.setFragmenter(new DefaultFragmenterImpl(-1));
    Container i1 = dashEncryptedBuilder.build(m2);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    i1.writeContainer(Channels.newChannel(baos));
    FileChannel fc = new FileOutputStream("v1-reference.mp4").getChannel();
    i1.writeContainer(fc);
    DataSource dataSourceRef = new FileDataSourceImpl(this.getClass().getProtectionDomain().getCodeSource().getLocation().getFile() + "/v1-reference.mp4");
    IsoFile i2 = new IsoFile(dataSourceRef);
    BoxComparator.check(i1, i2, "/moov[0]/mvhd[0]", "/moov[0]/trak[0]/tkhd[0]", "/moov[0]/trak[0]/mdia[0]/mdhd[0]");
}
Example 73
Project: descts-master  File: UsingDES.java View source code
public static void main(String[] args) throws Exception {
    byte[] keyBytes = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
    byte[] IV = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
    SecretKeySpec key = new SecretKeySpec(keyBytes, "DES");
    System.out.println("\n\n");
    System.out.println("DES ENCRYPTION EXAMPLE");
    System.out.println();
    // HERE COMES THE PLAINTEXT
    //String plaintext = new String("CPSC495 is super. I wish it would be a multi-year course12.");
    String plaintext = new String("0123456789abcdefgoooooo11111111");
    //String plaintext = new String("CPSC495aFOOOOBAR");
    // TURN PLAINTEXT STRING INTO BYTE ARRAY
    // AND OUTPUT SOME INFORMATION ABOUT PLAINTEXT
    byte[] dataBytes = plaintext.getBytes();
    System.out.println("Plaintext \"" + plaintext + "\" in Bytes: " + Arrays.toString(dataBytes));
    System.out.println("Length of plain text: " + dataBytes.length);
    System.out.println();
    // DO ENCRYPTION
    // AND OUTPUT SOME INFORMATION ABOUT CIPHERTEXT
    System.out.print("Encryption starting...");
    byte[] encBytes = DESCTS.encrypt(dataBytes, key, IV);
    System.out.println("finished!");
    System.out.println("Ciphertext: " + Arrays.toString(encBytes));
    System.out.println("Length of cipher text: " + encBytes.length);
    System.out.println();
    // DO DECRYPTION
    // AND OUTPUT SOME INFORMATION ABOUT RECOVERED PLAINTEXT
    System.out.print("Decryption starting...");
    byte[] decBytes = DESCTS.decrypt(encBytes, key, IV);
    System.out.println("finished!");
    System.out.println("Recovered plaintext: \"" + new String(decBytes) + "\" in Bytes: " + Arrays.toString(decBytes));
    System.out.println("Length of recovered plaintext: " + decBytes.length);
    boolean expected = java.util.Arrays.equals(dataBytes, decBytes);
    System.out.println("Encryption/Decryption " + (expected ? "SUCCEEDED!" : "FAILED!"));
    System.out.println();
}
Example 74
Project: despotify-master  File: Hash.java View source code
public static void hmacSha1(byte[] buffer, byte[] key, byte[] output, int offset) {
    if (hmacSha1 == null) {
        return;
    }
    SecretKeySpec secretKey = new SecretKeySpec(key, "HmacSHA1");
    try {
        hmacSha1.init(secretKey);
    } catch (InvalidKeyException e) {
        System.err.println("Invalid key: " + e.getMessage());
        return;
    }
    hmacSha1.update(buffer);
    try {
        hmacSha1.doFinal(output, offset);
    } catch (ShortBufferException e) {
        System.err.println("Output buffer is too short: " + e.getMessage());
    } catch (IllegalStateException e) {
        System.err.println("Illegal state: " + e.getMessage());
    }
}
Example 75
Project: DLect-master  File: DatabaseKeyHandler.java View source code
public static DatabaseKeyHandler getKeyHandler(Database db) {
    String keyString = db.getSetting(AES_KEY_SETTING_NAME);
    byte[] key = null;
    if (keyString != null) {
        byte[] decodedKey = BytesToString.decode(keyString);
        if (decodedKey.length == 16) {
            key = decodedKey;
        }
    }
    if (key == null) {
        key = newKey();
        db.addSetting(AES_KEY_SETTING_NAME, BytesToString.encode(key));
    }
    Key aesKey = new SecretKeySpec(key, "AES");
    return new DatabaseKeyHandler(aesKey);
}
Example 76
Project: EECE496-master  File: AssociationTest.java View source code
public void testGenerateSha1() {
    SecretKey secretKey = Association.generateMacSha1Key();
    assertNotNull(secretKey);
    assertTrue(secretKey instanceof SecretKeySpec);
    SecretKeySpec secretKeySpec = (SecretKeySpec) secretKey;
    assertEquals(Association.HMAC_SHA1_ALGORITHM.toUpperCase(), secretKeySpec.getAlgorithm().toUpperCase());
    assertEquals(20, secretKeySpec.getEncoded().length);
}
Example 77
Project: ermaster-b-master  File: PasswordCrypt.java View source code
private static Key getKey() throws Exception {
    if (KEY_FILE.exists()) {
        byte[] key = FileUtils.readFileToByteArray(KEY_FILE);
        SecretKeySpec keySpec = new SecretKeySpec(key, KEY_ALGORITHM);
        return keySpec;
    } else {
        Key key = generateKey();
        FileUtils.writeByteArrayToFile(KEY_FILE, key.getEncoded());
        return key;
    }
}
Example 78
Project: esb-message-admin-master  File: EncryptionUtility.java View source code
public String encrypt(String sensitiveInfo) {
    try {
        Cipher cipher = Cipher.getInstance(ALGORITHM, SECURITY_PROVIDER);
        SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes(FILE_ENCODING), "AES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return Base64.encodeBase64String(cipher.doFinal(sensitiveInfo.getBytes(FILE_ENCODING)));
    } catch (NoSuchAlgorithmExceptionNoSuchProviderException | NoSuchPaddingException | UnsupportedEncodingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException |  e) {
        LOGGER.error("EMA Encryption error!", e);
        return null;
    }
}
Example 79
Project: fred-master  File: HMAC.java View source code
public static byte[] mac(HMAC hash, byte[] key, byte[] data) {
    if (key.length != hash.digestSize)
        throw new IllegalArgumentException("Wrong keysize! We're not doing key stretching " + key.length + " expected " + hash.digestSize);
    SecretKeySpec signingKey = new SecretKeySpec(key, hash.algo);
    Mac mac;
    try {
        mac = Mac.getInstance(hash.algo);
    } catch (NoSuchAlgorithmException e) {
        Logger.error(HMAC.class, "No such AlgorithmException", e);
        throw new Error(e);
    }
    try {
        mac.init(signingKey);
    } catch (InvalidKeyException e) {
        Logger.error(HMAC.class, "Impossible InvalidKeyException", e);
        throw new Error(e);
    }
    return mac.doFinal(data);
}
Example 80
Project: galaxy-sdk-java-master  File: SignatureUtil.java View source code
public static byte[] sign(MacAlgorithm algorithm, byte[] secretKey, byte[] data) {
    try {
        Mac mac = Mac.getInstance(algorithm.name());
        mac.init(new SecretKeySpec(secretKey, algorithm.name()));
        return mac.doFinal(data);
    } catch (GeneralSecurityException e) {
        throw new RuntimeException("MAC algorithm not found: " + algorithm, e);
    }
}
Example 81
Project: gazpachoquest-master  File: HMACSignature.java View source code
/**
     * Computes RFC 2104-compliant HMAC signature.
     * * @param data
     * The data to be signed.
     * 
     * @param key
     *            The signing key.
     * @return
     *         The Base64-encoded RFC 2104-compliant HMAC signature.
     * @throws java.security.SignatureException
     *             when signature generation fails
     */
public static String calculateRFC2104HMAC(String data, String key) throws java.security.SignatureException {
    String result = null;
    try {
        Charset utf8ChartSet = Charset.forName("UTF-8");
        // get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(utf8ChartSet), HMAC_SHA1_ALGORITHM);
        // get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);
        // compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(data.getBytes(utf8ChartSet));
        // base64-encode the hmac
        result = Base64.encodeToString(rawHmac);
    } catch (NoSuchAlgorithmExceptionInvalidKeyException |  e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }
    return result;
}
Example 82
Project: gcontact-excel-sync-master  File: OAuthHmacSha1Signer.java View source code
public String getSignature(String baseString, OAuthParameters oauthParameters) throws OAuthException {
    try {
        if (oauthParameters == null) {
            throw new OAuthException("OAuth parameters cannot be null");
        }
        String keyString = getKey(oauthParameters);
        SecretKey key = new SecretKeySpec(keyString.getBytes("UTF-8"), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(key);
        return Base64.encode(mac.doFinal(baseString.getBytes("UTF-8")));
    } catch (UnsupportedEncodingException e) {
        throw new OAuthException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new OAuthException(e);
    } catch (InvalidKeyException e) {
        throw new OAuthException(e);
    }
}
Example 83
Project: gdata-java-client-master  File: OAuthHmacSha1Signer.java View source code
public String getSignature(String baseString, OAuthParameters oauthParameters) throws OAuthException {
    try {
        if (oauthParameters == null) {
            throw new OAuthException("OAuth parameters cannot be null");
        }
        String keyString = getKey(oauthParameters);
        SecretKey key = new SecretKeySpec(keyString.getBytes("UTF-8"), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(key);
        return Base64.encode(mac.doFinal(baseString.getBytes("UTF-8")));
    } catch (UnsupportedEncodingException e) {
        throw new OAuthException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new OAuthException(e);
    } catch (InvalidKeyException e) {
        throw new OAuthException(e);
    }
}
Example 84
Project: geofence-master  File: PwEncoderTest.java View source code
@Test
public void cannotDecodePwWithCustomKey() throws Exception {
    Properties originalProperties = System.getProperties();
    Properties properties = new Properties();
    properties.putAll(originalProperties);
    System.setProperties(properties);
    properties.setProperty("GEOFENCE_PWENCODER_KEY", "mycustomkeyforencrypting");
    String encoded = PwEncoder.encode("test");
    System.out.println(encoded);
    String defaultKey = "installation dependant key needed";
    byte[] bytes = defaultKey.substring(0, 16).getBytes();
    SecretKeySpec keySpec = new SecretKeySpec(bytes, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, keySpec);
    try {
        cipher.doFinal(Base64.decodeBase64(encoded));
        fail();
    } catch (GeneralSecurityException e) {
    }
    System.setProperties(originalProperties);
}
Example 85
Project: google-oauth-java-client-master  File: OAuthHmacSigner.java View source code
public String computeSignature(String signatureBaseString) throws GeneralSecurityException {
    // compute key
    StringBuilder keyBuf = new StringBuilder();
    String clientSharedSecret = this.clientSharedSecret;
    if (clientSharedSecret != null) {
        keyBuf.append(OAuthParameters.escape(clientSharedSecret));
    }
    keyBuf.append('&');
    String tokenSharedSecret = this.tokenSharedSecret;
    if (tokenSharedSecret != null) {
        keyBuf.append(OAuthParameters.escape(tokenSharedSecret));
    }
    String key = keyBuf.toString();
    // sign
    SecretKey secretKey = new SecretKeySpec(StringUtils.getBytesUtf8(key), "HmacSHA1");
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(secretKey);
    return Base64.encodeBase64String(mac.doFinal(StringUtils.getBytesUtf8(signatureBaseString)));
}
Example 86
Project: Growth-and-Decay-master  File: Signer.java View source code
public String sign(String path, String method, long secondsSinceEpoch, OrderedArgList unsignedParams) {
    if (mAccessToken != null) {
        unsignedParams.put("token", mAccessToken);
    }
    StringBuilder sigbase = new StringBuilder();
    sigbase.append(path);
    sigbase.append('+');
    sigbase.append(mSecret);
    sigbase.append('+');
    sigbase.append(method);
    sigbase.append('+');
    final String argString = unsignedParams.getArgString();
    sigbase.append(argString == null ? "" : argString);
    try {
        SecretKeySpec key = new SecretKeySpec((mSigningKey).getBytes("UTF-8"), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(key);
        byte[] bytes = mac.doFinal(sigbase.toString().getBytes("UTF-8"));
        return new String(Base64.encodeBase64(bytes)).replace("\r\n", "");
    } catch (UnsupportedEncodingException e) {
    } catch (InvalidKeyException e) {
    } catch (NoSuchAlgorithmException e) {
    }
    return null;
}
Example 87
Project: Hammerhead-StatsCollector-master  File: EncryptionHelper.java View source code
private static Key createKey() {
    try {
        byte[] key = "Ev932238Wd874gdOpAGiGDI1yx1OV72g".getBytes("UTF-8");
        MessageDigest sha = MessageDigest.getInstance(HASH_ALGORITHM);
        key = sha.digest(key);
        // use only first 128 bit
        key = Arrays.copyOf(key, 16);
        return new SecretKeySpec(key, ENCRYPTION_ALGORITHM);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("Need UTF-8 Support !");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Need SHA-1 Support !");
    }
}
Example 88
Project: hazelcast-archive-master  File: RFC2104HMAC.java View source code
public static String calculateRFC2104HMAC(String data, String key) throws SignatureException {
    String result = null;
    try {
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), SIGNATURE_METHOD);
        Mac mac = Mac.getInstance(SIGNATURE_METHOD);
        mac.init(signingKey);
        byte[] rawSignature = mac.doFinal(data.getBytes());
        result = new String(encode(rawSignature));
        result = result.trim();
    } catch (Exception e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }
    return result;
}
Example 89
Project: hudson_plugins-master  File: PwdCrypt.java View source code
static String encode(String toCrypt, String pass) {
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Cipher c = Cipher.getInstance(CRYPTO_ALGORITHM);
        Key k = new SecretKeySpec(pass.substring(0, 24).getBytes(), CRYPTO_ALGORITHM);
        c.init(Cipher.ENCRYPT_MODE, k);
        OutputStream cos = new CipherOutputStream(out, c);
        cos.write(toCrypt.getBytes());
        cos.close();
        return new String(new Base64().encode(out.toByteArray()));
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, MessageFormat.format("Encode failed: {0}", e.getMessage()));
        throw new EncryptionException(e);
    }
}
Example 90
Project: ISO8583Mediator-master  File: SecurityUtils.java View source code
public static byte[] encryptSymmetric(byte[] key, byte[] dataToEncrypt) throws CryptoException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    Cipher c = Cipher.getInstance("AES");
    //based on the strength of the key, change this algorithm. 
    MessageDigest md = MessageDigest.getInstance("MD5");
    //128 bits - MD5			256 bits - SHA-256
    //512 bits - SHA-512. Also, please include JCE to use 256 or 512 bits keys. 
    byte[] digetstKey = md.digest(key);
    SecretKeySpec k = new SecretKeySpec(digetstKey, "AES");
    c.init(Cipher.ENCRYPT_MODE, k);
    byte[] encryptedData = c.doFinal(dataToEncrypt);
    return encryptedData;
}
Example 91
Project: j2ssh-maverick-master  File: HmacSha512.java View source code
public void init(byte[] keydata) throws SshException {
    try {
        mac = JCEProvider.getProviderForAlgorithm(jceAlgorithm) == null ? Mac.getInstance(jceAlgorithm) : Mac.getInstance(jceAlgorithm, JCEProvider.getProviderForAlgorithm(jceAlgorithm));
        // Create a key of 16 bytes
        byte[] key = new byte[64];
        System.arraycopy(keydata, 0, key, 0, key.length);
        SecretKeySpec keyspec = new SecretKeySpec(key, jceAlgorithm);
        mac.init(keyspec);
    } catch (Throwable t) {
        throw new SshException(t);
    }
}
Example 92
Project: java_security-master  File: HMACTest.java View source code
// 用jdk实现:
public static void jdkHmacMD5() {
    try {
        // �始化KeyGenerator
        KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacMD5");
        // 产生密钥
        SecretKey secretKey = keyGenerator.generateKey();
        // 获�密钥
        //			byte[] key = secretKey.getEncoded();
        byte[] key = Hex.decodeHex(new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e' });
        // 还原密钥
        SecretKey restoreSecretKey = new SecretKeySpec(key, "HmacMD5");
        // 实例化MAC
        Mac mac = Mac.getInstance(restoreSecretKey.getAlgorithm());
        // �始化MAC
        mac.init(restoreSecretKey);
        // 执行摘�
        byte[] hmacMD5Bytes = mac.doFinal(src.getBytes());
        System.out.println("jdk hmacMD5:" + Hex.encodeHexString(hmacMD5Bytes));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 93
Project: jcrypt-master  File: Main.java View source code
public static void main(String[] args) throws Exception {
    ZipFile zip = new ZipFile(Utils.getJarFile());
    ZipEntry e = zip.getEntry("jar.dat");
    byte[] extra = e.getExtra();
    byte[] key = new byte[16];
    System.arraycopy(extra, 0, key, 0, 16);
    byte[] iv = new byte[16];
    System.arraycopy(extra, 16, iv, 0, 16);
    boolean cryptAll = extra[32] == 1;
    byte[] bMainClass = new byte[extra.length - 33];
    System.arraycopy(extra, 33, bMainClass, 0, extra.length - 33);
    String mainClass = new String(bMainClass);
    zip.close();
    InputStream resource = Main.class.getResourceAsStream(ENCRYPTED_ARCHIVE);
    Cipher cipher = Cipher.getInstance("AES/CBC/NOPADDING");
    Key sks = new SecretKeySpec(key, "AES");
    cipher.init(Cipher.DECRYPT_MODE, sks, new IvParameterSpec(iv));
    JarInputStream jarInputStream = new JarInputStream(new CipherInputStream(resource, cipher));
    EncryptedClassLoader classLoader = new EncryptedClassLoader(Main.class.getClassLoader(), jarInputStream, cryptAll);
    Class<?> classToLoad = classLoader.loadClass(mainClass);
    Method method = classToLoad.getMethod("main", new Class[] { String[].class });
    method.invoke(classToLoad.newInstance(), new Object[] { args });
    jarInputStream.close();
}
Example 94
Project: jenkins-master  File: CryptoConfidentialKey.java View source code
private SecretKey getKey() {
    try {
        if (secret == null) {
            synchronized (this) {
                if (secret == null) {
                    byte[] payload = load();
                    if (payload == null) {
                        payload = ConfidentialStore.get().randomBytes(256);
                        store(payload);
                    }
                    // Due to the stupid US export restriction JDK only ships 128bit version.
                    secret = new SecretKeySpec(payload, 0, 128 / 8, ALGORITHM);
                }
            }
        }
        return secret;
    } catch (IOException e) {
        throw new Error("Failed to load the key: " + getId(), e);
    }
}
Example 95
Project: jfexmpp-master  File: OAuthUtils.java View source code
public static byte[] computeSignature(String baseString, String consumerSecret, String tokenSecret) throws GeneralSecurityException, UnsupportedEncodingException {
    SecretKey key = null;
    String keyString = OAuth.percentEncode(consumerSecret) + '&' + OAuth.percentEncode(tokenSecret);
    byte[] keyBytes = keyString.getBytes(ENCODING);
    key = new SecretKeySpec(keyBytes, MAC_NAME);
    Mac mac = Mac.getInstance(MAC_NAME);
    mac.init(key);
    byte[] text = baseString.getBytes(ENCODING);
    return mac.doFinal(text);
}
Example 96
Project: JNCryptor-master  File: KeyTestVectorTest.java View source code
@Test
public void testKeyVector() throws Exception {
    AES256JNCryptor cryptor = new AES256JNCryptor();
    assertEquals("Test not suitable for current version.", cryptor.getVersionNumber(), vector.getVersion());
    byte[] plaintext = cryptor.decryptData(vector.getCiphertext(), new SecretKeySpec(vector.getEncryptionKey(), "AES"), new SecretKeySpec(vector.getHmacKey(), "AES"));
    assertArrayEquals(vector.getTitle(), vector.getExpectedPlaintext(), plaintext);
}
Example 97
Project: josm-master  File: HmacSha1MessageSigner.java View source code
@Override
public String sign(HttpRequest request, HttpParameters requestParams) throws OAuthMessageSignerException {
    try {
        String keyString = OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret());
        byte[] keyBytes = keyString.getBytes(OAuth.ENCODING);
        SecretKey key = new SecretKeySpec(keyBytes, MAC_NAME);
        Mac mac = Mac.getInstance(MAC_NAME);
        mac.init(key);
        String sbs = new SignatureBaseString(request, requestParams).generate();
        OAuth.debugOut("SBS", sbs);
        byte[] text = sbs.getBytes(OAuth.ENCODING);
        return base64Encode(mac.doFinal(text)).trim();
    } catch (GeneralSecurityException e) {
        throw new OAuthMessageSignerException(e);
    } catch (UnsupportedEncodingException e) {
        throw new OAuthMessageSignerException(e);
    }
}
Example 98
Project: josso1-master  File: CipherUtilTest.java View source code
@Test
public void testAES() throws Exception {
    SecretKeySpec key = CipherUtil.generateAESKey();
    String keyText = CipherUtil.encodeBase64(key.getEncoded());
    String msg = "My Test!";
    String text = CipherUtil.encryptAES(msg, keyText);
    String newMsg = CipherUtil.decryptAES(text, keyText);
    assert msg.equals(newMsg) : "Messages do not match : [" + msg + "] != [" + newMsg + "]";
}
Example 99
Project: jwt4j-master  File: JWTEncoder.java View source code
private String sign(final String message) {
    try {
        final Mac mac = Mac.getInstance(algorithm.name);
        mac.init(new SecretKeySpec(secret, algorithm.name));
        final String signature = new String(Base64.getEncoder().encodeToString(mac.doFinal(message.getBytes())));
        return signature;
    } catch (NoSuchAlgorithmExceptionInvalidKeyException | IllegalArgumentException |  e) {
        throw new AlgorithmException(e);
    }
}
Example 100
Project: keywhiz-master  File: HkdfTest.java View source code
@Test
public void extract_nullSaltSameAsZeros() {
    byte[] ikm = HEX.decode("DEADBEEF");
    Hkdf hkdf = Hkdf.usingDefaults();
    byte[] prkFromNullSalt = hkdf.extract(null, ikm).getEncoded();
    SecretKeySpec zeroSalt = new SecretKeySpec(HEX.decode(Strings.repeat("00", Hash.SHA256.getByteLength())), Hash.SHA256.getAlgorithm());
    byte[] prkFromZeroSalt = hkdf.extract(zeroSalt, ikm).getEncoded();
    assertThat(prkFromNullSalt).isEqualTo(prkFromZeroSalt);
}
Example 101
Project: korok-master  File: Signature.java View source code
public byte[] calculate(String url, long timestamp, byte[] body) {
    try {
        SecretKeySpec key = new SecretKeySpec(secret, HMAC_SHA1_ALGO);
        Mac hmac = Mac.getInstance(HMAC_SHA1_ALGO);
        hmac.init(key);
        return hmac.doFinal(createSignatureBase(url, timestamp, body));
    } catch (NoSuchAlgorithmException ex) {
        logger.error("HmacSHA1 is not supported.", ex);
    } catch (InvalidKeyException ex) {
        logger.error("Invalid key.", ex);
    }
    return new byte[0];
}