Search in sources :

Example 86 with SecretKeySpec

use of javax.crypto.spec.SecretKeySpec in project azure-iot-sdk-java by Azure.

the class IotHubServiceSasTokenTest method constructor_good_case_flow_check.

// Tests_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_002: [The constructor shall create a target uri from the url encoded host name)]
// Tests_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_003: [The constructor shall create a string to sign by concatenating the target uri and the expiry time string]
// Tests_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_004: [The constructor shall create a key from the shared access key signing with HmacSHA256]
// Tests_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_005: [The constructor shall compute the final signature by url encoding the signed key]
// Tests_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_006: [The constructor shall concatenate the target uri, the signature, the expiry time and the key name using the format: "SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s"]
@Test
public void constructor_good_case_flow_check() throws Exception {
    // Arrange
    String cryptoProvider = "HmacSHA256";
    String charset = "UTF-8";
    String iotHubName = "b.c.d";
    String hostName = "HOSTNAME." + iotHubName;
    String sharedAccessKeyName = "ACCESSKEYNAME";
    String policyName = "SharedAccessKey";
    String sharedAccessKey = "1234567890abcdefghijklmnopqrstvwxyz=";
    String connectionString = "HostName=" + hostName + ";SharedAccessKeyName=" + sharedAccessKeyName + ";" + policyName + "=" + sharedAccessKey;
    String expectedToken = "SharedAccessSignature sr=hostname.b.c.d&sig=M%2FT5oCM8WWs%2B%2FMv7okAVmfrzVM%2FGUyA7EIp%2FfKo8BeQ%3D&se=1474065852&skn=ACCESSKEYNAME";
    IotHubConnectionString iotHubConnectionString = IotHubConnectionStringBuilder.createConnectionString(connectionString);
    // Assert
    new Expectations() {

        URLEncoder urlEncoder;

        Base64 base64;

        System system;

        SecretKeySpec secretKeySpec;

        Mac mac;

        {
            urlEncoder.encode(hostName.toLowerCase(), String.valueOf(StandardCharsets.UTF_8));
            system.currentTimeMillis();
            Base64.decodeBase64(sharedAccessKey.getBytes(charset));
            byte[] body = { 1 };
            secretKeySpec = new SecretKeySpec(body, cryptoProvider);
            mac.getInstance(cryptoProvider);
        }
    };
    // Act
    IotHubServiceSasToken iotHubServiceSasToken = new IotHubServiceSasToken(iotHubConnectionString);
}
Also used : Expectations(mockit.Expectations) Base64(org.apache.commons.codec.binary.Base64) IotHubServiceSasToken(com.microsoft.azure.sdk.iot.service.auth.IotHubServiceSasToken) SecretKeySpec(javax.crypto.spec.SecretKeySpec) IotHubConnectionString(com.microsoft.azure.sdk.iot.service.IotHubConnectionString) IotHubConnectionString(com.microsoft.azure.sdk.iot.service.IotHubConnectionString) URLEncoder(java.net.URLEncoder) Mac(javax.crypto.Mac) Test(org.junit.Test)

Example 87 with SecretKeySpec

use of javax.crypto.spec.SecretKeySpec in project azure-sdk-for-java by Azure.

the class AesCbcHmacSha2 method GetAlgorithmParameters.

private static Triple<byte[], byte[], Mac> GetAlgorithmParameters(String algorithm, byte[] key) throws InvalidKeyException, NoSuchAlgorithmException {
    byte[] aes_key;
    byte[] hmac_key;
    Mac hmac;
    if (algorithm.equalsIgnoreCase(Aes128CbcHmacSha256.ALGORITHM_NAME)) {
        if ((key.length << 3) < 256) {
            throw new IllegalArgumentException(String.format("%s key length in bits %d < 256", algorithm, key.length << 3));
        }
        hmac_key = new byte[128 >> 3];
        aes_key = new byte[128 >> 3];
        // The HMAC key precedes the AES key
        System.arraycopy(key, 0, hmac_key, 0, 128 >> 3);
        System.arraycopy(key, 128 >> 3, aes_key, 0, 128 >> 3);
        hmac = Mac.getInstance("HmacSHA256");
        hmac.init(new SecretKeySpec(hmac_key, "HmacSHA256"));
    } else if (algorithm.equalsIgnoreCase(Aes192CbcHmacSha384.ALGORITHM_NAME)) {
        if ((key.length << 3) < 384) {
            throw new IllegalArgumentException(String.format("%s key length in bits %d < 384", algorithm, key.length << 3));
        }
        hmac_key = new byte[192 >> 3];
        aes_key = new byte[192 >> 3];
        // The HMAC key precedes the AES key
        System.arraycopy(key, 0, hmac_key, 0, 192 >> 3);
        System.arraycopy(key, 192 >> 3, aes_key, 0, 192 >> 3);
        hmac = Mac.getInstance("HmacSHA384");
        hmac.init(new SecretKeySpec(hmac_key, "HmacSHA384"));
    } else if (algorithm.equalsIgnoreCase(Aes256CbcHmacSha512.ALGORITHM_NAME)) {
        if ((key.length << 3) < 512) {
            throw new IllegalArgumentException(String.format("%s key length in bits %d < 512", algorithm, key.length << 3));
        }
        hmac_key = new byte[256 >> 3];
        aes_key = new byte[256 >> 3];
        // The HMAC key precedes the AES key
        System.arraycopy(key, 0, hmac_key, 0, 256 >> 3);
        System.arraycopy(key, 256 >> 3, aes_key, 0, 256 >> 3);
        hmac = Mac.getInstance("HmacSHA512");
        hmac.init(new SecretKeySpec(hmac_key, "HmacSHA512"));
    } else {
        throw new IllegalArgumentException(String.format("Unsupported algorithm: %s", algorithm));
    }
    return Triple.of(aes_key, hmac_key, hmac);
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) Mac(javax.crypto.Mac)

Example 88 with SecretKeySpec

use of javax.crypto.spec.SecretKeySpec in project CloudStack-archive by CloudStack-extras.

the class UtilsForTest method signRequest.

public static String signRequest(String request, String key) {
    try {
        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
        mac.init(keySpec);
        mac.update(request.getBytes());
        byte[] encryptedBytes = mac.doFinal();
        //System.out.println("HmacSHA1 hash: " + encryptedBytes);
        return Base64.encodeBytes(encryptedBytes);
    } catch (Exception ex) {
        System.out.println("unable to sign request");
        ex.printStackTrace();
    }
    return null;
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) Mac(javax.crypto.Mac) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 89 with SecretKeySpec

use of javax.crypto.spec.SecretKeySpec in project AndroidUtilCode by Blankj.

the class EncryptUtils method desTemplate.

/**
     * DES加密模板
     *
     * @param data           数据
     * @param key            秘钥
     * @param algorithm      加密算法
     * @param transformation 转变
     * @param isEncrypt      {@code true}: 加密 {@code false}: 解密
     * @return 密文或者明文,适用于DES,3DES,AES
     */
public static byte[] desTemplate(byte[] data, byte[] key, String algorithm, String transformation, boolean isEncrypt) {
    if (data == null || data.length == 0 || key == null || key.length == 0)
        return null;
    try {
        SecretKeySpec keySpec = new SecretKeySpec(key, algorithm);
        Cipher cipher = Cipher.getInstance(transformation);
        SecureRandom random = new SecureRandom();
        cipher.init(isEncrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, keySpec, random);
        return cipher.doFinal(data);
    } catch (Throwable e) {
        e.printStackTrace();
        return null;
    }
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) SecureRandom(java.security.SecureRandom) Cipher(javax.crypto.Cipher)

Example 90 with SecretKeySpec

use of javax.crypto.spec.SecretKeySpec in project OpenAM by OpenRock.

the class ReplayPasswd method encryptPassword.

/**
     * Encrypts the provided password.
     * @param userpasswd the password
     * @return the encrypted password
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws InvalidKeyException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws SSOException
     */
private String encryptPassword(String userpasswd) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, SSOException {
    String deskeystr = SystemProperties.get(REPLAY_PASSWORD_KEY);
    if (StringUtils.isBlank(deskeystr)) {
        if (debug.messageEnabled()) {
            debug.message("ReplayPasswd.encodePassword: cannot encode password, Replay PaswordKey is empty");
        }
        return null;
    }
    byte[] desKey = Base64.decode(deskeystr);
    SecretKeySpec keySpec = new SecretKeySpec(desKey, "DES");
    Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE_NAME);
    cipher.init(Cipher.ENCRYPT_MODE, keySpec);
    // The array size must be a multiply of 8 (DES block size)
    int length = userpasswd.length() + (8 - userpasswd.length() % 8);
    byte[] data = new byte[length];
    System.arraycopy(userpasswd.getBytes(), 0, data, 0, userpasswd.length());
    byte[] ciphertext = cipher.doFinal(data);
    return Base64.encode(ciphertext);
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) Cipher(javax.crypto.Cipher)

Aggregations

SecretKeySpec (javax.crypto.spec.SecretKeySpec)498 Cipher (javax.crypto.Cipher)194 SecretKey (javax.crypto.SecretKey)142 Mac (javax.crypto.Mac)110 IvParameterSpec (javax.crypto.spec.IvParameterSpec)106 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)94 InvalidKeyException (java.security.InvalidKeyException)67 IOException (java.io.IOException)44 Key (java.security.Key)36 SecureRandom (java.security.SecureRandom)30 Test (org.junit.Test)30 UnsupportedEncodingException (java.io.UnsupportedEncodingException)29 GeneralSecurityException (java.security.GeneralSecurityException)27 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)27 MessageDigest (java.security.MessageDigest)25 BadPaddingException (javax.crypto.BadPaddingException)25 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)25 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)18 PrivateKey (java.security.PrivateKey)18 PublicKey (java.security.PublicKey)16