1 2 29 30 package com.jcraft.jsch.jce; 31 32 import java.math.BigInteger ; 33 import java.security.*; 34 import java.security.spec.*; 35 36 public class SignatureDSA implements com.jcraft.jsch.SignatureDSA{ 37 38 java.security.Signature signature; 39 KeyFactory keyFactory; 40 41 public void init() throws Exception { 42 signature=java.security.Signature.getInstance("SHA1withDSA"); 43 keyFactory=KeyFactory.getInstance("DSA"); 44 } 45 public void setPubKey(byte[] y, byte[] p, byte[] q, byte[] g) throws Exception { 46 DSAPublicKeySpec dsaPubKeySpec = 47 new DSAPublicKeySpec(new BigInteger (y), 48 new BigInteger (p), 49 new BigInteger (q), 50 new BigInteger (g)); 51 PublicKey pubKey=keyFactory.generatePublic(dsaPubKeySpec); 52 signature.initVerify(pubKey); 53 } 54 public void setPrvKey(byte[] x, byte[] p, byte[] q, byte[] g) throws Exception { 55 DSAPrivateKeySpec dsaPrivKeySpec = 56 new DSAPrivateKeySpec(new BigInteger (x), 57 new BigInteger (p), 58 new BigInteger (q), 59 new BigInteger (g)); 60 PrivateKey prvKey = keyFactory.generatePrivate(dsaPrivKeySpec); 61 signature.initSign(prvKey); 62 } 63 public byte[] sign() throws Exception { 64 byte[] sig=signature.sign(); 65 72 int len=0; 75 int index=3; 76 len=sig[index++]&0xff; 77 byte[] r=new byte[len]; 79 System.arraycopy(sig, index, r, 0, r.length); 80 index=index+len+1; 81 len=sig[index++]&0xff; 82 byte[] s=new byte[len]; 84 System.arraycopy(sig, index, s, 0, s.length); 85 86 byte[] result=new byte[40]; 87 88 90 System.arraycopy(r, (r.length>20)?1:0, 91 result, (r.length>20)?0:20-r.length, 92 (r.length>20)?20:r.length); 93 System.arraycopy(s, (s.length>20)?1:0, 94 result, (s.length>20)?20:40-s.length, 95 (s.length>20)?20:s.length); 96 97 100 return result; 101 } 102 public void update(byte[] foo) throws Exception { 103 signature.update(foo); 104 } 105 public boolean verify(byte[] sig) throws Exception { 106 int i=0; 107 int j=0; 108 byte[] tmp; 109 110 if(sig[0]==0 && sig[1]==0 && sig[2]==0){ 111 j=((sig[i++]<<24)&0xff000000)|((sig[i++]<<16)&0x00ff0000)| 112 ((sig[i++]<<8)&0x0000ff00)|((sig[i++])&0x000000ff); 113 i+=j; 114 j=((sig[i++]<<24)&0xff000000)|((sig[i++]<<16)&0x00ff0000)| 115 ((sig[i++]<<8)&0x0000ff00)|((sig[i++])&0x000000ff); 116 tmp=new byte[j]; 117 System.arraycopy(sig, i, tmp, 0, j); sig=tmp; 118 } 119 120 int frst=((sig[0]&0x80)!=0?1:0); 122 int scnd=((sig[20]&0x80)!=0?1:0); 123 125 int length=sig.length+6+frst+scnd; 126 tmp=new byte[length]; 127 tmp[0]=(byte)0x30; tmp[1]=(byte)0x2c; 128 tmp[1]+=frst; tmp[1]+=scnd; 129 tmp[2]=(byte)0x02; tmp[3]=(byte)0x14; 130 tmp[3]+=frst; 131 System.arraycopy(sig, 0, tmp, 4+frst, 20); 132 tmp[4+tmp[3]]=(byte)0x02; tmp[5+tmp[3]]=(byte)0x14; 133 tmp[5+tmp[3]]+=scnd; 134 System.arraycopy(sig, 20, tmp, 6+tmp[3]+scnd, 20); 135 sig=tmp; 136 137 145 return signature.verify(sig); 146 } 147 } 148 | Popular Tags |