All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.seppiko.commons.utils.crypto.AsymmetricUtil Maven / Gradle / Ivy

There is a newer version: 2.11.0
Show newest version
/*
 * Copyright 2023 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.seppiko.commons.utils.crypto;

import java.io.Serial;
import java.io.Serializable;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Objects;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

/**
 * Public-key cryptography (aka Asymmetric cryptography) util
 *
 * @see 
 *     Cipher Algorithm Names
 * @see Public-key cryptography
 * @author Leonard Woo
 */
public class AsymmetricUtil implements Cryptography, Serializable {

  @Serial
  private static final long serialVersionUID = 8711682631532844830L;

  /** algorithm name */
  private final NMPUtil algorithm;

  /** default provider */
  private Provider provider = CryptoUtil.NONPROVIDER;

  /** default params */
  private AlgorithmParameterSpec params = null;

  /** public key */
  private PublicKey publicKey;

  /** private key */
  private PrivateKey privateKey;

  /**
   * Public-key cryptography algorithm
   *
   * @param algorithm Algorithm name.
   * @throws NoSuchAlgorithmException Algorithm name parser failed.
   */
  public AsymmetricUtil(String algorithm) throws NoSuchAlgorithmException {
    this.algorithm = new NMPUtil(algorithm);
  }

  /** {@inheritDoc} */
  @Override
  public void setProvider(Provider provider) {
    this.provider = provider;
  }

  /**
   * Set key-pair
   *
   * @see GeneratorUtil#keyPairGenerator
   * @param publicKey public key.
   * @param privateKey private key.
   */
  public void setKeyPair(PublicKey publicKey, PrivateKey privateKey) {
    this.publicKey = publicKey;
    this.privateKey = privateKey;
  }

  /** {@inheritDoc} */
  @Override
  public void setParameterSpec(AlgorithmParameterSpec params) {
    this.params = params;
  }

  /**
   * Encrypt data with Asymmetric cryptography
   *
   * @param data plaintext data buffer
   * @return ciphertext data buffer
   * @throws InvalidAlgorithmParameterException if the given algorithm parameters are inappropriate
   *     for this cipher, or this cipher requires algorithm parameters and params is null, or the
   *     given algorithm parameters imply a cryptographic strength that would exceed the legal
   *     limits (as determined from the configured jurisdiction policy files).
   * @throws NoSuchPaddingException if transformation contains a padding scheme that is not
   *     available.
   * @throws IllegalBlockSizeException if this cipher is a block cipher, no padding has been
   *     requested (only in encryption mode), and the total input length of the data processed by
   *     this cipher is not a multiple of block size; or if this encryption algorithm is unable to
   *     process the input data provided.
   * @throws NoSuchAlgorithmException if transformation is null, empty, in an invalid format, or if
   *     no Provider supports a CipherSpi implementation for the specified algorithm.
   * @throws BadPaddingException if this cipher is in decryption mode, and (un)padding has been
   *     requested, but the decrypted data is not bounded by the appropriate padding bytes.
   * @throws InvalidKeyException if the given key is inappropriate for initializing this cipher, or
   *     its key-size exceeds the maximum allowable key-size (as determined from the configured
   *     jurisdiction policy files).
   * @throws NullPointerException public key is {@code null}.
   */
  @Override
  public byte[] encrypt(byte[] data)
      throws InvalidAlgorithmParameterException, NoSuchPaddingException, IllegalBlockSizeException,
          NoSuchAlgorithmException, BadPaddingException, InvalidKeyException, NullPointerException {
    Objects.requireNonNull(publicKey);
    return CryptoUtil.cipher(algorithm.toString(), provider, Cipher.ENCRYPT_MODE, publicKey, params, data);
  }

  /**
   * Decrypt data with Asymmetric cryptography
   *
   * @param data ciphertext data buffer
   * @return plaintext data buffer
   * @throws InvalidAlgorithmParameterException if the given algorithm parameters are inappropriate
   *     for this cipher, or this cipher requires algorithm parameters and params is null, or the
   *     given algorithm parameters imply a cryptographic strength that would exceed the legal
   *     limits (as determined from the configured jurisdiction policy files).
   * @throws NoSuchPaddingException if transformation contains a padding scheme that is not
   *     available.
   * @throws IllegalBlockSizeException if this cipher is a block cipher, no padding has been
   *     requested (only in encryption mode), and the total input length of the data processed by
   *     this cipher is not a multiple of block size; or if this encryption algorithm is unable to
   *     process the input data provided.
   * @throws NoSuchAlgorithmException if transformation is null, empty, in an invalid format, or if
   *     no Provider supports a CipherSpi implementation for the specified algorithm.
   * @throws BadPaddingException if this cipher is in decryption mode, and (un)padding has been
   *     requested, but the decrypted data is not bounded by the appropriate padding bytes.
   * @throws InvalidKeyException if the given key is inappropriate for initializing this cipher, or
   *     its key-size exceeds the maximum allowable key-size (as determined from the configured
   *     jurisdiction policy files).
   * @throws NullPointerException private key is {@code null}.
   */
  @Override
  public byte[] decrypt(byte[] data)
      throws InvalidAlgorithmParameterException, NoSuchPaddingException, IllegalBlockSizeException,
          NoSuchAlgorithmException, BadPaddingException, InvalidKeyException, NullPointerException {
    Objects.requireNonNull(privateKey);
    return CryptoUtil.cipher(algorithm.toString(), provider, Cipher.DECRYPT_MODE, privateKey, params, data);
  }

  /**
   * Encrypt data with Asymmetric cryptography
   *
   * @param data plaintext data buffer
   * @return ciphertext data buffer
   * @throws InvalidAlgorithmParameterException if the given algorithm parameters are inappropriate
   *     for this cipher, or this cipher requires algorithm parameters and params is null, or the
   *     given algorithm parameters imply a cryptographic strength that would exceed the legal
   *     limits (as determined from the configured jurisdiction policy files).
   * @throws NoSuchPaddingException if transformation contains a padding scheme that is not
   *     available.
   * @throws IllegalBlockSizeException if this cipher is a block cipher, no padding has been
   *     requested (only in encryption mode), and the total input length of the data processed by
   *     this cipher is not a multiple of block size; or if this encryption algorithm is unable to
   *     process the input data provided.
   * @throws NoSuchAlgorithmException if transformation is null, empty, in an invalid format, or if
   *     no Provider supports a CipherSpi implementation for the specified algorithm.
   * @throws BadPaddingException if this cipher is in decryption mode, and (un)padding has been
   *     requested, but the decrypted data is not bounded by the appropriate padding bytes.
   * @throws InvalidKeyException if the given key is inappropriate for initializing this cipher, or
   *     its key-size exceeds the maximum allowable key-size (as determined from the configured
   *     jurisdiction policy files).
   * @throws NullPointerException private key is {@code null}.
   */
  public byte[] encryptWithPrivateKey(byte[] data)
      throws InvalidAlgorithmParameterException, NoSuchPaddingException, IllegalBlockSizeException,
          NoSuchAlgorithmException, BadPaddingException, InvalidKeyException, NullPointerException {
    Objects.requireNonNull(privateKey);
    return CryptoUtil.cipher(algorithm.toString(), provider, Cipher.ENCRYPT_MODE, privateKey, params, data);
  }

  /**
   * Decrypt data with Asymmetric cryptography
   *
   * @param data ciphertext data buffer
   * @return plaintext data buffer
   * @throws InvalidAlgorithmParameterException if the given algorithm parameters are inappropriate
   *     for this cipher, or this cipher requires algorithm parameters and params is null, or the
   *     given algorithm parameters imply a cryptographic strength that would exceed the legal
   *     limits (as determined from the configured jurisdiction policy files).
   * @throws NoSuchPaddingException if transformation contains a padding scheme that is not
   *     available.
   * @throws IllegalBlockSizeException if this cipher is a block cipher, no padding has been
   *     requested (only in encryption mode), and the total input length of the data processed by
   *     this cipher is not a multiple of block size; or if this encryption algorithm is unable to
   *     process the input data provided.
   * @throws NoSuchAlgorithmException if transformation is null, empty, in an invalid format, or if
   *     no Provider supports a CipherSpi implementation for the specified algorithm.
   * @throws BadPaddingException if this cipher is in decryption mode, and (un)padding has been
   *     requested, but the decrypted data is not bounded by the appropriate padding bytes.
   * @throws InvalidKeyException if the given key is inappropriate for initializing this cipher, or
   *     its key-size exceeds the maximum allowable key-size (as determined from the configured
   *     jurisdiction policy files).
   * @throws NullPointerException public key is {@code null}.
   */
  public byte[] decryptWithPublicKey(byte[] data)
      throws InvalidAlgorithmParameterException, NoSuchPaddingException, IllegalBlockSizeException,
          NoSuchAlgorithmException, BadPaddingException, InvalidKeyException, NullPointerException {
    Objects.requireNonNull(publicKey);
    return CryptoUtil.cipher(algorithm.toString(), provider, Cipher.DECRYPT_MODE, publicKey, params, data);
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy