Java Code Examples for org.bouncycastle.asn1.x509.AlgorithmIdentifier

The following examples show how to use org.bouncycastle.asn1.x509.AlgorithmIdentifier. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: xipki   Source File: AlgorithmUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static AlgorithmIdentifier extractDigesetAlgFromSigAlg(AlgorithmIdentifier sigAlgId)
    throws NoSuchAlgorithmException {
  ASN1ObjectIdentifier algOid = sigAlgId.getAlgorithm();

  ASN1ObjectIdentifier digestAlgOid;
  if (PKCSObjectIdentifiers.id_RSASSA_PSS.equals(algOid)) {
    ASN1Encodable asn1Encodable = sigAlgId.getParameters();
    RSASSAPSSparams param = RSASSAPSSparams.getInstance(asn1Encodable);
    digestAlgOid = param.getHashAlgorithm().getAlgorithm();
  } else {
    HashAlgo digestAlg = sigAlgOidToDigestMap.get(algOid);
    if (digestAlg == null) {
      throw new NoSuchAlgorithmException("unknown signature algorithm " + algOid.getId());
    }
    digestAlgOid = digestAlg.getOid();
  }

  return new AlgorithmIdentifier(digestAlgOid, DERNull.INSTANCE);
}
 
Example 2
Source Project: xipki   Source File: P11ContentSigner.java    License: Apache License 2.0 6 votes vote down vote up
ECDSA(P11CryptService cryptService, P11IdentityId identityId,
    AlgorithmIdentifier signatureAlgId, boolean plain)
    throws XiSecurityException, P11TokenException {
  super(cryptService, identityId, signatureAlgId);

  this.plain = plain;

  String algOid = signatureAlgId.getAlgorithm().getId();
  HashAlgo hashAlgo = sigAlgHashMap.get(algOid);
  if (hashAlgo == null) {
    throw new XiSecurityException("unsupported signature algorithm " + algOid);
  }

  P11Slot slot = cryptService.getSlot(identityId.getSlotId());

  long mech = hashMechMap.get(hashAlgo).longValue();
  if (slot.supportsMechanism(mech)) {
    mechanism = mech;
    this.outputStream = new ByteArrayOutputStream();
  } else if (slot.supportsMechanism(PKCS11Constants.CKM_ECDSA)) {
    mechanism = PKCS11Constants.CKM_ECDSA;
    this.outputStream = new DigestOutputStream(hashAlgo.createDigest());
  } else {
    throw new XiSecurityException("unsupported signature algorithm " + algOid);
  }
}
 
Example 3
Source Project: xipki   Source File: AlgorithmUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean isRSASigAlgId(AlgorithmIdentifier algId) {
  ASN1ObjectIdentifier oid = Args.notNull(algId, "algId").getAlgorithm();
  if (PKCSObjectIdentifiers.sha1WithRSAEncryption.equals(oid)
      || PKCSObjectIdentifiers.sha224WithRSAEncryption.equals(oid)
      || PKCSObjectIdentifiers.sha256WithRSAEncryption.equals(oid)
      || PKCSObjectIdentifiers.sha384WithRSAEncryption.equals(oid)
      || PKCSObjectIdentifiers.sha512WithRSAEncryption.equals(oid)
      || NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_224.equals(oid)
      || NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_256.equals(oid)
      || NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_384.equals(oid)
      || NISTObjectIdentifiers.id_rsassa_pkcs1_v1_5_with_sha3_512.equals(oid)
      || PKCSObjectIdentifiers.id_RSASSA_PSS.equals(oid)) {
    return true;
  }

  return false;
}
 
Example 4
Source Project: protect   Source File: RsaCertificateAuthorityClient.java    License: MIT License 6 votes vote down vote up
/*** Static Methods ***/

	private static BigInteger EMSA_PKCS1_V1_5_ENCODE(byte[] input, final BigInteger modulus)
			throws NoSuchAlgorithmException, IOException {

		// Digest the input
		final MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM);
		final byte[] digest = md.digest(input);

		// Create a digest info consisting of the algorithm id and the hash
		final AlgorithmIdentifier algId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512, DERNull.INSTANCE);
		final DigestInfo digestInfo = new DigestInfo(algId, digest);
		final byte[] message = digestInfo.getEncoded(ASN1Encoding.DER);

		// Do PKCS1 padding
		final byte[] block = new byte[((modulus.bitLength() + 7) / 8) - 1];
		System.arraycopy(message, 0, block, block.length - message.length, message.length);
		block[0] = 0x01; // type code 1
		for (int i = 1; i != block.length - message.length - 1; i++) {
			block[i] = (byte) 0xFF;
		}

		return new BigInteger(1, block);
	}
 
Example 5
/**
 * This method gets called after the bean is created.
 */
@PostConstruct
private void postConstruct() {

    // Set signatureAlgorithmId.
    try {

        signatureAlgorithmId = new AlgorithmIdentifier((ASN1ObjectIdentifier) EdECObjectIdentifiers.class
                .getDeclaredField("id_" + cryptographyProperties.getSignatureAlgorithm()).get(null));

    } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
        throw new RuntimeException(String.format(
                "Error creating the AlgorithmIdentifier corresponding to the signature algorithm %s",
                cryptographyProperties.getSignatureAlgorithm()));
    }

}
 
Example 6
Source Project: xipki   Source File: KeypairGenControl.java    License: Apache License 2.0 6 votes vote down vote up
public DSAKeypairGenControl(int pLength, int qLength, ASN1ObjectIdentifier keyAlgorithmOid) {
  if (pLength < 1024 | pLength % 1024 != 0) {
    throw new IllegalArgumentException("invalid pLength " + pLength);
  }

  if (qLength == 0) {
    if (pLength < 2048) {
      qLength = 160;
    } else if (pLength < 3072) {
      qLength = 224;
    } else {
      qLength = 256;
    }
  }

  this.parameterSpec = DSAParameterCache.getDSAParameterSpec(pLength, qLength, null);
  this.keyAlgorithm = new AlgorithmIdentifier(
      (keyAlgorithmOid != null) ? keyAlgorithmOid : X9ObjectIdentifiers.id_dsa,
      new DSAParameter(parameterSpec.getP(), parameterSpec.getQ(), parameterSpec.getG()));
}
 
Example 7
private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0)
    throws GeneralSecurityException, IOException
{
    ASN1InputStream asn1inputstream = 
        new ASN1InputStream(new ByteArrayInputStream(x509certificate.getTBSCertificate()));
    TBSCertificateStructure tbscertificatestructure = 
        TBSCertificateStructure.getInstance(asn1inputstream.readObject());
    AlgorithmIdentifier algorithmidentifier = tbscertificatestructure.getSubjectPublicKeyInfo().getAlgorithm();
    IssuerAndSerialNumber issuerandserialnumber = 
        new IssuerAndSerialNumber(
            tbscertificatestructure.getIssuer(), 
            tbscertificatestructure.getSerialNumber().getValue());
    Cipher cipher = Cipher.getInstance(algorithmidentifier.getAlgorithm().getId());        
    cipher.init(1, x509certificate);
    DEROctetString deroctetstring = new DEROctetString(cipher.doFinal(abyte0));
    RecipientIdentifier recipId = new RecipientIdentifier(issuerandserialnumber);
    return new KeyTransRecipientInfo( recipId, algorithmidentifier, deroctetstring);
}
 
Example 8
Source Project: xipki   Source File: AlgorithmUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static String getSignatureAlgoName(AlgorithmIdentifier sigAlgId)
    throws NoSuchAlgorithmException {
  ASN1ObjectIdentifier algOid = Args.notNull(sigAlgId, "sigAlgId").getAlgorithm();
  String name = null;
  if (PKCSObjectIdentifiers.id_RSASSA_PSS.equals(algOid)) {
    RSASSAPSSparams param = RSASSAPSSparams.getInstance(sigAlgId.getParameters());
    ASN1ObjectIdentifier digestAlgOid = param.getHashAlgorithm().getAlgorithm();
    name = digestOidToMgf1SigNameMap.get(digestAlgOid);
    if (name == null) {
      throw new NoSuchAlgorithmException("unsupported digest algorithm " + digestAlgOid);
    }
  } else {
    name = sigAlgOidToNameMap.get(algOid);
  }

  if (name == null) {
    throw new NoSuchAlgorithmException("unsupported signature algorithm " + algOid.getId());
  }
  return name;
}
 
Example 9
Source Project: xipki   Source File: CaClientExample.java    License: Apache License 2.0 6 votes vote down vote up
protected static MyKeypair generateDsaKeypair() throws Exception {
  // plen: 2048, qlen: 256
  DSAParameterSpec spec = new DSAParameterSpec(P2048_Q256_P, P2048_Q256_Q, P2048_Q256_G);
  KeyPairGenerator kpGen = KeyPairGenerator.getInstance("DSA");
  kpGen.initialize(spec);
  KeyPair kp = kpGen.generateKeyPair();

  DSAPublicKey dsaPubKey = (DSAPublicKey) kp.getPublic();
  ASN1EncodableVector vec = new ASN1EncodableVector();
  vec.add(new ASN1Integer(dsaPubKey.getParams().getP()));
  vec.add(new ASN1Integer(dsaPubKey.getParams().getQ()));
  vec.add(new ASN1Integer(dsaPubKey.getParams().getG()));
  ASN1Sequence dssParams = new DERSequence(vec);

  SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(
      new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, dssParams),
      new ASN1Integer(dsaPubKey.getY()));

  return new MyKeypair(kp.getPrivate(), subjectPublicKeyInfo);
}
 
Example 10
Source Project: xipki   Source File: AlgorithmUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static AlgorithmIdentifier getSigAlgId(PublicKey pubKey, HashAlgo hashAlgo,
    SignatureAlgoControl algoControl) throws NoSuchAlgorithmException {
  Args.notNull(hashAlgo, "hashAlgo");

  if (pubKey instanceof RSAPublicKey) {
    boolean rsaMgf1 = (algoControl == null) ? false : algoControl.isRsaMgf1();
    return getRSASigAlgId(hashAlgo, rsaMgf1);
  } else if (pubKey instanceof ECPublicKey) {
    boolean dsaPlain = (algoControl == null) ? false : algoControl.isDsaPlain();
    boolean gm =  (algoControl == null) ? false : algoControl.isGm();
    return getECSigAlgId(hashAlgo, dsaPlain, gm);
  } else if (pubKey instanceof DSAPublicKey) {
    return getDSASigAlgId(hashAlgo);
  } else {
    throw new NoSuchAlgorithmException("Unknown public key '" + pubKey.getClass().getName());
  }
}
 
Example 11
Source Project: xipki   Source File: AlgorithmUtil.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean isECDSASigAlg(AlgorithmIdentifier algId) {
  ASN1ObjectIdentifier oid = Args.notNull(algId, "algId").getAlgorithm();
  if (X9ObjectIdentifiers.ecdsa_with_SHA1.equals(oid)
      || X9ObjectIdentifiers.ecdsa_with_SHA224.equals(oid)
      || X9ObjectIdentifiers.ecdsa_with_SHA256.equals(oid)
      || X9ObjectIdentifiers.ecdsa_with_SHA384.equals(oid)
      || X9ObjectIdentifiers.ecdsa_with_SHA512.equals(oid)
      || NISTObjectIdentifiers.id_ecdsa_with_sha3_224.equals(oid)
      || NISTObjectIdentifiers.id_ecdsa_with_sha3_256.equals(oid)
      || NISTObjectIdentifiers.id_ecdsa_with_sha3_384.equals(oid)
      || NISTObjectIdentifiers.id_ecdsa_with_sha3_512.equals(oid)) {
    return true;
  }

  return false;
}
 
Example 12
Source Project: xipki   Source File: RequestOptions.java    License: Apache License 2.0 6 votes vote down vote up
public static RSASSAPSSparams createPSSRSAParams(ASN1ObjectIdentifier digestAlgOid) {
  int saltSize;
  if (X509ObjectIdentifiers.id_SHA1.equals(digestAlgOid)) {
    saltSize = 20;
  } else if (NISTObjectIdentifiers.id_sha224.equals(digestAlgOid)) {
    saltSize = 28;
  } else if (NISTObjectIdentifiers.id_sha256.equals(digestAlgOid)) {
    saltSize = 32;
  } else if (NISTObjectIdentifiers.id_sha384.equals(digestAlgOid)) {
    saltSize = 48;
  } else if (NISTObjectIdentifiers.id_sha512.equals(digestAlgOid)) {
    saltSize = 64;
  } else {
    throw new IllegalStateException("unknown digest algorithm " + digestAlgOid);
  }

  AlgorithmIdentifier digAlgId = new AlgorithmIdentifier(digestAlgOid, DERNull.INSTANCE);
  return new RSASSAPSSparams(digAlgId,
      new AlgorithmIdentifier(PKCSObjectIdentifiers.id_mgf1, digAlgId),
      new ASN1Integer(saltSize), RSASSAPSSparams.DEFAULT_TRAILER_FIELD);
}
 
Example 13
Source Project: xipki   Source File: AlgorithmUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean isDSASigAlg(AlgorithmIdentifier algId) {
  ASN1ObjectIdentifier oid = Args.notNull(algId, "algId").getAlgorithm();
  if (X9ObjectIdentifiers.id_dsa_with_sha1.equals(oid)
      || NISTObjectIdentifiers.dsa_with_sha224.equals(oid)
      || NISTObjectIdentifiers.dsa_with_sha256.equals(oid)
      || NISTObjectIdentifiers.dsa_with_sha384.equals(oid)
      || NISTObjectIdentifiers.dsa_with_sha512.equals(oid)
      || NISTObjectIdentifiers.id_dsa_with_sha3_224.equals(oid)
      || NISTObjectIdentifiers.id_dsa_with_sha3_256.equals(oid)
      || NISTObjectIdentifiers.id_dsa_with_sha3_384.equals(oid)
      || NISTObjectIdentifiers.id_dsa_with_sha3_512.equals(oid)) {
    return true;
  }

  return false;
}
 
Example 14
Source Project: xipki   Source File: HmacContentSigner.java    License: Apache License 2.0 6 votes vote down vote up
public HmacContentSigner(HashAlgo hashAlgo, AlgorithmIdentifier algorithmIdentifier,
    SecretKey signingKey) throws XiSecurityException {
  this.algorithmIdentifier = Args.notNull(algorithmIdentifier, "algorithmIdentifier");
  Args.notNull(signingKey, "signingKey");
  try {
    this.encodedAlgorithmIdentifier = algorithmIdentifier.getEncoded();
  } catch (IOException ex) {
    throw new XiSecurityException("could not encode AlgorithmIdentifier", ex);
  }
  if (hashAlgo == null) {
    hashAlgo = AlgorithmUtil.extractHashAlgoFromMacAlg(algorithmIdentifier);
  }

  this.hmac = new HMac(hashAlgo.createDigest());
  byte[] keyBytes = signingKey.getEncoded();
  this.hmac.init(new KeyParameter(keyBytes, 0, keyBytes.length));
  this.outLen = hmac.getMacSize();
  this.outputStream = new HmacOutputStream();
}
 
Example 15
private Attribute getComposedAtsHashIndex(AlgorithmIdentifier algorithmIdentifiers, ASN1Sequence certificatesHashIndex, ASN1Sequence crLsHashIndex,
		ASN1Sequence unsignedAttributesHashIndex, ASN1ObjectIdentifier atsHashIndexVersionIdentifier) {
	final ASN1EncodableVector vector = new ASN1EncodableVector();
	if (algorithmIdentifiers != null) {
		vector.add(algorithmIdentifiers);
	} else if (id_aa_ATSHashIndexV2.equals(atsHashIndexVersionIdentifier) || id_aa_ATSHashIndexV3.equals(atsHashIndexVersionIdentifier)) {
		// for id_aa_ATSHashIndexV2 and id_aa_ATSHashIndexV3, the algorithmIdentifier is required
		AlgorithmIdentifier sha256AlgorithmIdentifier = new AlgorithmIdentifier(new ASN1ObjectIdentifier(DigestAlgorithm.SHA256.getOid()));
		vector.add(sha256AlgorithmIdentifier);
	}
	if (certificatesHashIndex != null) {
		vector.add(certificatesHashIndex);
	}
	if (crLsHashIndex != null) {
		vector.add(crLsHashIndex);
	}
	if (unsignedAttributesHashIndex != null) {
		vector.add(unsignedAttributesHashIndex);
	}
	final ASN1Sequence derSequence = new DERSequence(vector);
	return new Attribute(atsHashIndexVersionIdentifier, new DERSet(derSequence));
}
 
Example 16
Source Project: xipki   Source File: AlgorithmUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static AlgorithmCode getSigOrMacAlgoCode(AlgorithmIdentifier algId)
    throws NoSuchAlgorithmException {
  ASN1ObjectIdentifier oid = algId.getAlgorithm();
  AlgorithmCode code = algOidToCodeMap.get(oid);
  if (code != null) {
    return code;
  }

  if (PKCSObjectIdentifiers.id_RSASSA_PSS.equals(oid)) {
    RSASSAPSSparams param = RSASSAPSSparams.getInstance(algId.getParameters());
    ASN1ObjectIdentifier digestAlgOid = param.getHashAlgorithm().getAlgorithm();
    code = digestToMgf1AlgCodeMap.get(digestAlgOid);
    if (code == null) {
      throw new NoSuchAlgorithmException("unsupported digest algorithm " + digestAlgOid);
    }
    return code;
  } else {
    throw new NoSuchAlgorithmException("unsupported signature algorithm " + oid.getId());
  }
}
 
Example 17
Source Project: dss   Source File: DSSASN1Utils.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Gets the ASN.1 algorithm identifier structure corresponding to the algorithm 
 * found in the provided Timestamp Hash Index Table, if such algorithm is present
 *
 * @param atsHashIndexValue
 *            ats-hash-index table from a timestamp
 * @return the ASN.1 algorithm identifier structure
 */
public static AlgorithmIdentifier getAlgorithmIdentifier(final ASN1Sequence atsHashIndexValue) {
	if (atsHashIndexValue != null && atsHashIndexValue.size() > 3) {
		final int algorithmIndex = 0;
		final ASN1Encodable asn1Encodable = atsHashIndexValue.getObjectAt(algorithmIndex);
		
		if (asn1Encodable instanceof ASN1Sequence) {
			final ASN1Sequence asn1Sequence = (ASN1Sequence) asn1Encodable;
			return AlgorithmIdentifier.getInstance(asn1Sequence);
		} else if (asn1Encodable instanceof ASN1ObjectIdentifier) {
			// TODO (16/11/2014): The relevance and usefulness of the test case must be checked (do the signatures
			// like this exist?)
			ASN1ObjectIdentifier derObjectIdentifier = ASN1ObjectIdentifier.getInstance(asn1Encodable);
			return new AlgorithmIdentifier(derObjectIdentifier);
		}
	}
	return null;
}
 
Example 18
Source Project: xipki   Source File: Responder.java    License: Apache License 2.0 5 votes vote down vote up
public boolean isPbmMacPermitted(AlgorithmIdentifier pbmMac) {
  ASN1ObjectIdentifier macOid = pbmMac.getAlgorithm();
  for (ASN1ObjectIdentifier oid : macAlgos) {
    if (oid.equals(macOid)) {
      return true;
    }
  }
  return false;
}
 
Example 19
Source Project: netty-4.1.22   Source File: Digester.java    License: Apache License 2.0 5 votes vote down vote up
public static DigestCalculator sha1() {
    Digest digest = new SHA1Digest();
    AlgorithmIdentifier algId = new AlgorithmIdentifier(
            OIWObjectIdentifiers.idSHA1);

    return new Digester(digest, algId);
}
 
Example 20
Source Project: netty-4.1.22   Source File: Digester.java    License: Apache License 2.0 5 votes vote down vote up
public static DigestCalculator sha256() {
    Digest digest = new SHA256Digest();

    // The OID for SHA-256: http://www.oid-info.com/get/2.16.840.1.101.3.4.2.1
    ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier(
            "2.16.840.1.101.3.4.2.1").intern();
    AlgorithmIdentifier algId = new AlgorithmIdentifier(oid);

    return new Digester(digest, algId);
}
 
Example 21
Source Project: xipki   Source File: AlgorithmUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static HashAlgo extractHashAlgoFromMacAlg(AlgorithmIdentifier macAlg) {
  ASN1ObjectIdentifier oid = macAlg.getAlgorithm();
  HashAlgo hashAlgo = macAlgOidToDigestMap.get(oid);
  if (hashAlgo == null) {
    throw new IllegalArgumentException("unknown algorithm identifier " + oid.getId());
  }
  return hashAlgo;
}
 
Example 22
private int getKeySize(SubjectPublicKeyInfo subjectPKInfo) {
   try {
      X509EncodedKeySpec xspec = new X509EncodedKeySpec((new DERBitString(subjectPKInfo.getEncoded())).getBytes());
      AlgorithmIdentifier keyAlg = subjectPKInfo.getAlgorithm();
      PublicKey publicKey = KeyFactory.getInstance(keyAlg.getAlgorithm().getId()).generatePublic(xspec);
      String algorithm = publicKey.getAlgorithm();
      KeyFactory keyFact = KeyFactory.getInstance(algorithm);
      RSAPublicKeySpec keySpec = (RSAPublicKeySpec)keyFact.getKeySpec(publicKey, RSAPublicKeySpec.class);
      BigInteger modulus = keySpec.getModulus();
      return modulus.toString(2).length();
   } catch (Exception var9) {
      throw new IllegalArgumentException(var9);
   }
}
 
Example 23
private static int getKeySize(SubjectPublicKeyInfo subjectPKInfo) {
   try {
      X509EncodedKeySpec xspec = new X509EncodedKeySpec((new DERBitString(subjectPKInfo.getEncoded())).getBytes());
      AlgorithmIdentifier keyAlg = subjectPKInfo.getAlgorithm();
      PublicKey publicKey = KeyFactory.getInstance(keyAlg.getAlgorithm().getId()).generatePublic(xspec);
      String algorithm = publicKey.getAlgorithm();
      KeyFactory keyFact = KeyFactory.getInstance(algorithm);
      RSAPublicKeySpec keySpec = (RSAPublicKeySpec)keyFact.getKeySpec(publicKey, RSAPublicKeySpec.class);
      BigInteger modulus = keySpec.getModulus();
      return modulus.toString(2).length();
   } catch (Exception var8) {
      throw new IllegalArgumentException(var8);
   }
}
 
Example 24
Source Project: gmhelper   Source File: BCECUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 将SEC1标准的私钥字节流恢复为PKCS8标准的字节流
 *
 * @param sec1Key
 * @return
 * @throws IOException
 */
public static byte[] convertECPrivateKeySEC1ToPKCS8(byte[] sec1Key) throws IOException {
    /**
     * 参考org.bouncycastle.asn1.pkcs.PrivateKeyInfo和
     * org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey,逆向拼装
     */
    X962Parameters params = getDomainParametersFromName(SM2Util.JDK_EC_SPEC, false);
    ASN1OctetString privKey = new DEROctetString(sec1Key);
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new ASN1Integer(0)); //版本号
    v.add(new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, params)); //算法标识
    v.add(privKey);
    DERSequence ds = new DERSequence(v);
    return ds.getEncoded(ASN1Encoding.DER);
}
 
Example 25
Source Project: xipki   Source File: ResponseSigner.java    License: Apache License 2.0 5 votes vote down vote up
private static String getSignatureAlgorithmName(AlgorithmIdentifier sigAlgId) {
  ASN1ObjectIdentifier algOid = sigAlgId.getAlgorithm();
  if (!PKCSObjectIdentifiers.id_RSASSA_PSS.equals(algOid)) {
    return algOid.getId();
  }

  ASN1Encodable asn1Encodable = sigAlgId.getParameters();
  RSASSAPSSparams param = RSASSAPSSparams.getInstance(asn1Encodable);
  ASN1ObjectIdentifier digestAlgOid = param.getHashAlgorithm().getAlgorithm();
  return digestAlgOid.getId() + "WITHRSAANDMGF1";
}
 
Example 26
Source Project: xipki   Source File: CaEnrollBenchKeyEntry.java    License: Apache License 2.0 5 votes vote down vote up
private void init(BigInteger p, BigInteger q, BigInteger g, BigInteger y) throws IOException {
  ASN1EncodableVector vec = new ASN1EncodableVector();
  vec.add(new ASN1Integer(p));
  vec.add(new ASN1Integer(q));
  vec.add(new ASN1Integer(g));
  ASN1Sequence dssParams = new DERSequence(vec);
  AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, dssParams);
  this.spki = new SubjectPublicKeyInfo(algId, new ASN1Integer(y));
}
 
Example 27
Source Project: xipki   Source File: P11ContentSigner.java    License: Apache License 2.0 5 votes vote down vote up
P11ContentSigner(P11CryptService cryptService, P11IdentityId identityId,
    AlgorithmIdentifier signatureAlgId)
    throws XiSecurityException, P11TokenException {
  this.identityId = Args.notNull(identityId, "identityId");
  this.cryptService = Args.notNull(cryptService, "cryptService");
  this.algorithmIdentifier = Args.notNull(signatureAlgId, "signatureAlgId");
  try {
    this.encodedAlgorithmIdentifier = algorithmIdentifier.getEncoded();
  } catch (IOException ex) {
    throw new XiSecurityException("could not encode AlgorithmIdentifier", ex);
  }
}
 
Example 28
Source Project: xipki   Source File: CmpControl.java    License: Apache License 2.0 5 votes vote down vote up
public boolean isRequestPbmMacPermitted(AlgorithmIdentifier pbmMac) {
  ASN1ObjectIdentifier macOid = pbmMac.getAlgorithm();
  for (ASN1ObjectIdentifier oid : requestPbmMacs) {
    if (oid.equals(macOid)) {
      return true;
    }
  }
  return false;
}
 
Example 29
/**
 * <a href="http://stackoverflow.com/questions/33305800/difference-between-sha256withrsa-and-sha256-then-rsa">
 * Difference between SHA256withRSA and SHA256 then RSA
 * </a>
 * <p>
 * This method is the updated code provided by the OP. As expected it shows two equal signatures.
 * The OP's observations seem to differ, though.
 * </p>
 */
public void testAsGreenhandUpdated(PrivateKey privateKey) throws GeneralSecurityException, IOException
{
    System.out.println("\nGreenhandUpdated:");

    String s = "1234";
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    messageDigest.update(s.getBytes());
    byte[] outputDigest = messageDigest.digest();

    AlgorithmIdentifier sha256Aid = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256, DERNull.INSTANCE);
    DigestInfo di = new DigestInfo(sha256Aid, outputDigest);
    //sign SHA256 with RSA
    Signature rsaSignature = Signature.getInstance("RSA");
    rsaSignature.initSign(privateKey);
    byte[] encodedDigestInfo = di.toASN1Primitive().getEncoded();
    rsaSignature.update(encodedDigestInfo);
    byte[] signed = rsaSignature.sign();
    System.out.println("method 1: "+bytesToHex(signed));
    System.out.println("    hash: " + bytesToHex(outputDigest));
    System.out.println("    algo: " + sha256Aid.getAlgorithm());
    System.out.println("    info: " + bytesToHex(encodedDigestInfo));

    //compute SHA256withRSA as a single step
    Signature rsaSha256Signature = Signature.getInstance("SHA256withRSA");
    rsaSha256Signature.initSign(privateKey);
    rsaSha256Signature.update(s.getBytes());
    byte[] signed2 = rsaSha256Signature.sign();
    System.out.println("method 2: "+bytesToHex(signed2));
}
 
Example 30
Source Project: dremio-oss   Source File: ElasticsearchCluster.java    License: Apache License 2.0 5 votes vote down vote up
private static ContentSigner newSigner(PrivateKey privateKey, String algo) {
    try {
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algo);
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);

        return new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
                .build(PrivateKeyFactory.createKey(privateKey.getEncoded()));
    } catch (OperatorCreationException | IOException e) {
        throw new RuntimeException(e);
    }
}