Search in sources :

Example 41 with SecretKeySpec

use of javax.crypto.spec.SecretKeySpec in project weixin-java-tools by chanjarster.

the class WxCryptUtil method decrypt.

/**
   * 对密文进行解密.
   *
   * @param cipherText 需要解密的密文
   * @return 解密得到的明文
   */
public String decrypt(String cipherText) {
    byte[] original;
    try {
        // 设置解密模式为AES的CBC模式
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        SecretKeySpec key_spec = new SecretKeySpec(aesKey, "AES");
        IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16));
        cipher.init(Cipher.DECRYPT_MODE, key_spec, iv);
        // 使用BASE64对密文进行解码
        byte[] encrypted = Base64.decodeBase64(cipherText);
        // 解密
        original = cipher.doFinal(encrypted);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    String xmlContent, from_appid;
    try {
        // 去除补位字符
        byte[] bytes = PKCS7Encoder.decode(original);
        // 分离16位随机字符串,网络字节序和AppId
        byte[] networkOrder = Arrays.copyOfRange(bytes, 16, 20);
        int xmlLength = bytesNetworkOrder2Number(networkOrder);
        xmlContent = new String(Arrays.copyOfRange(bytes, 20, 20 + xmlLength), CHARSET);
        from_appid = new String(Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length), CHARSET);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    // appid不相同的情况
    if (!from_appid.equals(appidOrCorpid)) {
        throw new RuntimeException("AppID不正确");
    }
    return xmlContent;
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 42 with SecretKeySpec

use of javax.crypto.spec.SecretKeySpec in project UltimateAndroid by cymcsg.

the class TripleDES method decrypt.

/**
     * Decrypt the message with TripleDES
     *
     * @param message
     * @return
     * @throws Exception
     */
public static String decrypt(String message) throws Exception {
    if (message == null || message == "")
        return "";
    byte[] values = Base64decoding(message, 0);
    final MessageDigest md = MessageDigest.getInstance("SHA-1");
    final byte[] digestOfPassword = md.digest(token.getBytes("utf-8"));
    final byte[] keyBytes = copyOf(digestOfPassword, 24);
    for (int j = 0, k = 16; j < 8; ) {
        keyBytes[k++] = keyBytes[j++];
    }
    final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
    String s1 = "12345678";
    byte[] bytes = s1.getBytes();
    final IvParameterSpec iv = new IvParameterSpec(bytes);
    final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
    decipher.init(Cipher.DECRYPT_MODE, key, iv);
    final byte[] plainText = decipher.doFinal(values);
    return new String(plainText, "UTF-8");
}
Also used : SecretKey(javax.crypto.SecretKey) SecretKeySpec(javax.crypto.spec.SecretKeySpec) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) MessageDigest(java.security.MessageDigest)

Example 43 with SecretKeySpec

use of javax.crypto.spec.SecretKeySpec in project Openfire by igniterealtime.

the class N method A.

public static byte[] A(byte[] abyte0, byte[] abyte1, int i, byte[] abyte2) {
    try {
        SecretKeySpec secretkeyspec = new SecretKeySpec(abyte2, "hmacSHA256");
        Mac mac = Mac.getInstance("hmacSHA256");
        mac.init(secretkeyspec);
        mac.update(abyte1, 0, i);
        byte[] abyte3 = mac.doFinal();
        secretkeyspec = new SecretKeySpec(abyte0, "hmacSHA256");
        mac = Mac.getInstance("hmacSHA256");
        mac.init(secretkeyspec);
        return mac.doFinal(abyte3);
    } catch (NoSuchAlgorithmException nosuchalgorithmexception) {
        E.error(nosuchalgorithmexception.getMessage(), nosuchalgorithmexception);
    } catch (InvalidKeyException invalidkeyexception) {
        E.error(invalidkeyexception.getMessage(), invalidkeyexception);
    }
    return null;
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) Mac(javax.crypto.Mac)

Example 44 with SecretKeySpec

use of javax.crypto.spec.SecretKeySpec in project jjwt by jwtk.

the class DefaultJwtBuilder method compact.

@Override
public String compact() {
    if (payload == null && Collections.isEmpty(claims)) {
        throw new IllegalStateException("Either 'payload' or 'claims' must be specified.");
    }
    if (payload != null && !Collections.isEmpty(claims)) {
        throw new IllegalStateException("Both 'payload' and 'claims' cannot both be specified. Choose either one.");
    }
    if (key != null && keyBytes != null) {
        throw new IllegalStateException("A key object and key bytes cannot both be specified. Choose either one.");
    }
    Header header = ensureHeader();
    Key key = this.key;
    if (key == null && !Objects.isEmpty(keyBytes)) {
        key = new SecretKeySpec(keyBytes, algorithm.getJcaName());
    }
    JwsHeader jwsHeader;
    if (header instanceof JwsHeader) {
        jwsHeader = (JwsHeader) header;
    } else {
        jwsHeader = new DefaultJwsHeader(header);
    }
    if (key != null) {
        jwsHeader.setAlgorithm(algorithm.getValue());
    } else {
        //no signature - plaintext JWT:
        jwsHeader.setAlgorithm(SignatureAlgorithm.NONE.getValue());
    }
    if (compressionCodec != null) {
        jwsHeader.setCompressionAlgorithm(compressionCodec.getAlgorithmName());
    }
    String base64UrlEncodedHeader = base64UrlEncode(jwsHeader, "Unable to serialize header to json.");
    String base64UrlEncodedBody;
    if (compressionCodec != null) {
        byte[] bytes;
        try {
            bytes = this.payload != null ? payload.getBytes(Strings.UTF_8) : toJson(claims);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException("Unable to serialize claims object to json.");
        }
        base64UrlEncodedBody = TextCodec.BASE64URL.encode(compressionCodec.compress(bytes));
    } else {
        base64UrlEncodedBody = this.payload != null ? TextCodec.BASE64URL.encode(this.payload) : base64UrlEncode(claims, "Unable to serialize claims object to json.");
    }
    String jwt = base64UrlEncodedHeader + JwtParser.SEPARATOR_CHAR + base64UrlEncodedBody;
    if (key != null) {
        //jwt must be signed:
        JwtSigner signer = createSigner(algorithm, key);
        String base64UrlSignature = signer.sign(jwt);
        jwt += JwtParser.SEPARATOR_CHAR + base64UrlSignature;
    } else {
        // no signature (plaintext), but must terminate w/ a period, see
        // https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-25#section-6.1
        jwt += JwtParser.SEPARATOR_CHAR;
    }
    return jwt;
}
Also used : JwtSigner(io.jsonwebtoken.impl.crypto.JwtSigner) DefaultJwtSigner(io.jsonwebtoken.impl.crypto.DefaultJwtSigner) Header(io.jsonwebtoken.Header) JwsHeader(io.jsonwebtoken.JwsHeader) SecretKeySpec(javax.crypto.spec.SecretKeySpec) JwsHeader(io.jsonwebtoken.JwsHeader) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Key(java.security.Key)

Example 45 with SecretKeySpec

use of javax.crypto.spec.SecretKeySpec in project OpenAttestation by OpenAttestation.

the class Diagnostic method tryMacWithPassword.

private static void tryMacWithPassword(String algorithmName, String message, String password) {
    try {
        SecretKeySpec key = new SecretKeySpec(password.getBytes(), algorithmName);
        // a string like "HmacSHA256"
        Mac mac = Mac.getInstance(algorithmName, "BC");
        mac.init(key);
        byte[] digest = mac.doFinal(message.getBytes());
        System.out.println("Created " + algorithmName + " digest of length " + digest.length);
    } catch (NoSuchProviderException e) {
        System.err.println("Cannot use provider: BC: " + e.toString());
    } catch (NoSuchAlgorithmException e) {
        System.err.println("Cannot use algorithm: " + algorithmName + ": " + e.toString());
    } catch (InvalidKeyException e) {
        System.err.println("Cannot use key: " + password + ": " + e.toString());
    }
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NoSuchProviderException(java.security.NoSuchProviderException) InvalidKeyException(java.security.InvalidKeyException) Mac(javax.crypto.Mac)

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