Java tutorial
//package com.java2s; /* * Copyright (C) 2014 The Android Open Source Project * * 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. */ import java.security.Key; import java.security.PrivateKey; import java.security.PublicKey; import java.security.KeyFactory; import java.security.Signature; import java.security.spec.ECPublicKeySpec; import java.security.spec.ECPrivateKeySpec; import java.security.spec.InvalidKeySpecException; public class Main { static byte[] sign(PrivateKey privateKey, byte[] input) throws Exception { Signature signer = Signature.getInstance(getSignatureAlgorithm(privateKey)); signer.initSign(privateKey); signer.update(input); return signer.sign(); } private static String getSignatureAlgorithm(Key key) throws Exception { if ("EC".equals(key.getAlgorithm())) { int curveSize; KeyFactory factory = KeyFactory.getInstance("EC"); if (key instanceof PublicKey) { ECPublicKeySpec spec = factory.getKeySpec(key, ECPublicKeySpec.class); curveSize = spec.getParams().getCurve().getField().getFieldSize(); } else if (key instanceof PrivateKey) { ECPrivateKeySpec spec = factory.getKeySpec(key, ECPrivateKeySpec.class); curveSize = spec.getParams().getCurve().getField().getFieldSize(); } else { throw new InvalidKeySpecException(); } if (curveSize <= 256) { return "SHA256withECDSA"; } else if (curveSize <= 384) { return "SHA384withECDSA"; } else { return "SHA512withECDSA"; } } else if ("RSA".equals(key.getAlgorithm())) { return "SHA256withRSA"; } else { throw new IllegalArgumentException("Unsupported key type " + key.getAlgorithm()); } } }